@goodtiming/baton-sdk 0.5.8 → 0.6.2
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 +25 -11
- package/dist/index.cjs +1071 -342
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +490 -34
- package/dist/index.d.ts +490 -34
- package/dist/index.js +1066 -342
- 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,
|
|
@@ -97,7 +102,7 @@ __export(index_exports, {
|
|
|
97
102
|
module.exports = __toCommonJS(index_exports);
|
|
98
103
|
|
|
99
104
|
// src/version.ts
|
|
100
|
-
var SDK_VERSION = "ts-0.
|
|
105
|
+
var SDK_VERSION = "ts-0.6.2";
|
|
101
106
|
|
|
102
107
|
// src/events.ts
|
|
103
108
|
var import_zod = require("zod");
|
|
@@ -218,6 +223,10 @@ var SurfaceSnapshotPayloadSchema = import_zod.z.object({
|
|
|
218
223
|
tools: import_zod.z.array(import_zod.z.record(import_zod.z.string(), import_zod.z.unknown())).default([]),
|
|
219
224
|
seam_augmentations: import_zod.z.record(import_zod.z.string(), import_zod.z.unknown()).default({})
|
|
220
225
|
}).strict();
|
|
226
|
+
var ClientReportPayloadSchema = import_zod.z.object({
|
|
227
|
+
instance_id: import_zod.z.uuid(),
|
|
228
|
+
dropped: import_zod.z.record(import_zod.z.string(), import_zod.z.number().int().nonnegative())
|
|
229
|
+
}).strict();
|
|
221
230
|
var DEFAULT_CONSENT_TOKEN = "customer-consented";
|
|
222
231
|
var ClientObservedSchema = import_zod.z.object({
|
|
223
232
|
info: import_zod.z.object({ name: import_zod.z.string().optional(), version: import_zod.z.string().optional() }).strict().optional(),
|
|
@@ -242,6 +251,7 @@ var envelopeShape = {
|
|
|
242
251
|
// consumer names the client from `client_observed`.
|
|
243
252
|
agent_runtime: import_zod.z.string().default("unknown"),
|
|
244
253
|
principal: PrincipalWireSchema.nullable().default(null),
|
|
254
|
+
organization: PrincipalWireSchema.nullable().default(null),
|
|
245
255
|
transport_observed: import_zod.z.string().nullable().default(null),
|
|
246
256
|
session_id_origin: import_zod.z.string().nullable().default(null),
|
|
247
257
|
client_observed: ClientObservedSchema.nullable().default(null),
|
|
@@ -254,6 +264,7 @@ var EventTypeSchema = import_zod.z.enum([
|
|
|
254
264
|
"tool_call_error",
|
|
255
265
|
"annotation",
|
|
256
266
|
"surface_snapshot",
|
|
267
|
+
"client_report",
|
|
257
268
|
// The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose
|
|
258
269
|
// shapes were set by `baton-proxy`, which has been emitting all of them in
|
|
259
270
|
// production — see the payload schemas below.
|
|
@@ -363,6 +374,11 @@ var SurfaceSnapshotEventSchema = import_zod.z.object({
|
|
|
363
374
|
event_type: import_zod.z.literal("surface_snapshot").default("surface_snapshot"),
|
|
364
375
|
payload: SurfaceSnapshotPayloadSchema
|
|
365
376
|
}).strict();
|
|
377
|
+
var ClientReportEventSchema = import_zod.z.object({
|
|
378
|
+
...envelopeShape,
|
|
379
|
+
event_type: import_zod.z.literal("client_report").default("client_report"),
|
|
380
|
+
payload: ClientReportPayloadSchema
|
|
381
|
+
}).strict();
|
|
366
382
|
var ResourceListStartEventSchema = import_zod.z.object({
|
|
367
383
|
...envelopeShape,
|
|
368
384
|
event_type: import_zod.z.literal("resource_list_start").default("resource_list_start"),
|
|
@@ -444,6 +460,7 @@ var EventSchema = import_zod.z.discriminatedUnion("event_type", [
|
|
|
444
460
|
ToolCallErrorEventSchema,
|
|
445
461
|
AnnotationEventSchema,
|
|
446
462
|
SurfaceSnapshotEventSchema,
|
|
463
|
+
ClientReportEventSchema,
|
|
447
464
|
ResourceListStartEventSchema,
|
|
448
465
|
ResourceListEndEventSchema,
|
|
449
466
|
ResourceListErrorEventSchema,
|
|
@@ -461,8 +478,33 @@ var EventSchema = import_zod.z.discriminatedUnion("event_type", [
|
|
|
461
478
|
ToolListErrorEventSchema
|
|
462
479
|
]);
|
|
463
480
|
|
|
481
|
+
// src/warn.ts
|
|
482
|
+
function warn(message) {
|
|
483
|
+
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
484
|
+
process.emitWarning(message);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
function printable(err) {
|
|
488
|
+
try {
|
|
489
|
+
return String(err);
|
|
490
|
+
} catch {
|
|
491
|
+
return "(an error that cannot be printed)";
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// src/_object.ts
|
|
496
|
+
function isPlainObject(value) {
|
|
497
|
+
if (typeof value !== "object" || value === null) return false;
|
|
498
|
+
const proto = Object.getPrototypeOf(value);
|
|
499
|
+
return proto === Object.prototype || proto === null;
|
|
500
|
+
}
|
|
501
|
+
function isRecord(value) {
|
|
502
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
503
|
+
}
|
|
504
|
+
|
|
464
505
|
// src/scrub.ts
|
|
465
506
|
var DEPTH_LIMIT = 10;
|
|
507
|
+
var DEPTH_MARKER = "[REDACTED:depth-limit]";
|
|
466
508
|
var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
467
509
|
"email",
|
|
468
510
|
"phone",
|
|
@@ -473,16 +515,21 @@ var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
|
473
515
|
"password",
|
|
474
516
|
"user_name"
|
|
475
517
|
]);
|
|
518
|
+
var WS_CHARS = String.raw` \t\n\r\f\u00a0`;
|
|
519
|
+
var PHONE_SEP = String.raw`[${WS_CHARS}\-.]`;
|
|
476
520
|
var PATTERNS = [
|
|
477
521
|
["jwt", /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g],
|
|
478
|
-
["bearer",
|
|
522
|
+
["bearer", new RegExp(String.raw`\bBearer[${WS_CHARS}]+[A-Za-z0-9_\-.+/=]{16,}`, "gi")],
|
|
479
523
|
["sk_key", /\bsk-[A-Za-z0-9_-]{20,}\b/g],
|
|
480
524
|
["aws_key", /\bAKIA[0-9A-Z]{16}\b/g],
|
|
481
525
|
["email", /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g],
|
|
482
526
|
// Phone: optional `+1`, optional area-code parens, separators
|
|
483
|
-
//
|
|
527
|
+
// `-`, `.` or `WS_CHARS`, 10 digits. Conservative — won't catch every
|
|
484
528
|
// international format, but won't trip on every 10-digit identifier.
|
|
485
|
-
[
|
|
529
|
+
[
|
|
530
|
+
"phone",
|
|
531
|
+
new RegExp(String.raw`\b(?:\+?1${PHONE_SEP}?)?\(?\d{3}\)?${PHONE_SEP}?\d{3}${PHONE_SEP}?\d{4}\b`, "g")
|
|
532
|
+
]
|
|
486
533
|
];
|
|
487
534
|
var CC_CANDIDATE = /\b\d{13,19}\b/g;
|
|
488
535
|
function luhnValid(digits) {
|
|
@@ -497,13 +544,9 @@ function luhnValid(digits) {
|
|
|
497
544
|
}
|
|
498
545
|
return total % 10 === 0;
|
|
499
546
|
}
|
|
500
|
-
function isPlainObject(value) {
|
|
501
|
-
if (typeof value !== "object" || value === null) return false;
|
|
502
|
-
const proto = Object.getPrototypeOf(value);
|
|
503
|
-
return proto === Object.prototype || proto === null;
|
|
504
|
-
}
|
|
505
547
|
var Scrubber = class {
|
|
506
548
|
counts = /* @__PURE__ */ new Map();
|
|
549
|
+
warnedDepth = false;
|
|
507
550
|
/** Bound so `new Scrubber().scrub` can be passed as a bare function
|
|
508
551
|
* reference — the closest TS gets to Python's `__call__`. */
|
|
509
552
|
scrub = (value) => this.walk(value, 0, null);
|
|
@@ -514,8 +557,20 @@ var Scrubber = class {
|
|
|
514
557
|
bump(category) {
|
|
515
558
|
this.counts.set(category, this.count(category) + 1);
|
|
516
559
|
}
|
|
560
|
+
pastTheDepthLimit() {
|
|
561
|
+
this.bump("depth_limit");
|
|
562
|
+
if (!this.warnedDepth) {
|
|
563
|
+
this.warnedDepth = true;
|
|
564
|
+
warn(
|
|
565
|
+
`baton: a payload nests deeper than ${DEPTH_LIMIT} levels; containers past that depth are sent as ${JSON.stringify(DEPTH_MARKER)}`
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
return DEPTH_MARKER;
|
|
569
|
+
}
|
|
517
570
|
walk(value, depth, forceField) {
|
|
518
|
-
if (depth >= DEPTH_LIMIT)
|
|
571
|
+
if (depth >= DEPTH_LIMIT && (isPlainObject(value) || Array.isArray(value))) {
|
|
572
|
+
return this.pastTheDepthLimit();
|
|
573
|
+
}
|
|
519
574
|
if (isPlainObject(value)) {
|
|
520
575
|
const out = {};
|
|
521
576
|
for (const [k, v] of Object.entries(value)) {
|
|
@@ -556,14 +611,155 @@ function identityScrub(value) {
|
|
|
556
611
|
}
|
|
557
612
|
|
|
558
613
|
// src/sinks.ts
|
|
614
|
+
var import_node_fs = require("fs");
|
|
615
|
+
|
|
616
|
+
// src/_text.ts
|
|
617
|
+
var WHITE_SPACE = /^\p{White_Space}$/u;
|
|
618
|
+
var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
|
|
619
|
+
function stripEdges(value, space) {
|
|
620
|
+
let start = 0;
|
|
621
|
+
let end = value.length;
|
|
622
|
+
while (start < end && space.test(value[start])) start++;
|
|
623
|
+
while (end > start && space.test(value[end - 1])) end--;
|
|
624
|
+
return value.slice(start, end);
|
|
625
|
+
}
|
|
626
|
+
function stripWhiteSpace(value) {
|
|
627
|
+
return stripEdges(value, WHITE_SPACE);
|
|
628
|
+
}
|
|
629
|
+
function isBlank(value) {
|
|
630
|
+
return ALL_WHITE_SPACE.test(value);
|
|
631
|
+
}
|
|
632
|
+
function exceedsCodePoints(value, max) {
|
|
633
|
+
if (value.length <= max) return false;
|
|
634
|
+
if (value.length > 2 * max) return true;
|
|
635
|
+
return [...value].length > max;
|
|
636
|
+
}
|
|
637
|
+
function capCodePoints(value, max) {
|
|
638
|
+
if (value.length <= max) return value;
|
|
639
|
+
return [...value].slice(0, max).join("");
|
|
640
|
+
}
|
|
641
|
+
function escapeForLog(value) {
|
|
642
|
+
return value.replace(/[\\\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (c) => `\\u{${c.codePointAt(0).toString(16)}}`);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// src/deadline.ts
|
|
646
|
+
var TIMED_OUT = /* @__PURE__ */ Symbol("timedOut");
|
|
647
|
+
var MAX_TIMER_MS = 2 ** 31 - 1;
|
|
648
|
+
async function raceDeadline(work, ms) {
|
|
649
|
+
let timer;
|
|
650
|
+
const deadline = new Promise((resolve) => {
|
|
651
|
+
timer = setTimeout(() => resolve(TIMED_OUT), Math.min(ms, MAX_TIMER_MS));
|
|
652
|
+
timer.unref?.();
|
|
653
|
+
});
|
|
654
|
+
try {
|
|
655
|
+
return await Promise.race([work, deadline]);
|
|
656
|
+
} finally {
|
|
657
|
+
clearTimeout(timer);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
var SHUTDOWN_FLUSH_TIMEOUT_MS = 3e3;
|
|
661
|
+
|
|
662
|
+
// src/drops.ts
|
|
663
|
+
var RECOVERY_LOG_MS = 6e4;
|
|
664
|
+
var DropCounts = class {
|
|
665
|
+
#instanceId = uuid7();
|
|
666
|
+
#total = /* @__PURE__ */ new Map();
|
|
667
|
+
#sinceDelivery = /* @__PURE__ */ new Map();
|
|
668
|
+
#lastRecoveryLog = -RECOVERY_LOG_MS;
|
|
669
|
+
add(reason, n = 1) {
|
|
670
|
+
if (n <= 0) return;
|
|
671
|
+
this.#total.set(reason, (this.#total.get(reason) ?? 0) + n);
|
|
672
|
+
this.#sinceDelivery.set(reason, (this.#sinceDelivery.get(reason) ?? 0) + n);
|
|
673
|
+
}
|
|
674
|
+
total() {
|
|
675
|
+
return Object.fromEntries(this.#total);
|
|
676
|
+
}
|
|
677
|
+
/** Called on each delivery: names what was lost before it, the other half of
|
|
678
|
+
* a drop's own warning, which says only that loss started. */
|
|
679
|
+
logRecovery() {
|
|
680
|
+
if (this.#sinceDelivery.size === 0) return;
|
|
681
|
+
const now = performance.now();
|
|
682
|
+
if (now - this.#lastRecoveryLog < RECOVERY_LOG_MS) return;
|
|
683
|
+
const lost = [...this.#sinceDelivery].sort(([a], [b]) => a.localeCompare(b));
|
|
684
|
+
this.#sinceDelivery.clear();
|
|
685
|
+
this.#lastRecoveryLog = now;
|
|
686
|
+
const total = lost.reduce((sum, [, n]) => sum + n, 0);
|
|
687
|
+
warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
|
|
688
|
+
}
|
|
689
|
+
/** For tests: the counts are one per process. */
|
|
690
|
+
/** Names this process in its loss reports (SPEC §11.4.7). */
|
|
691
|
+
get instanceId() {
|
|
692
|
+
return this.#instanceId;
|
|
693
|
+
}
|
|
694
|
+
clear() {
|
|
695
|
+
this.#instanceId = uuid7();
|
|
696
|
+
this.#total.clear();
|
|
697
|
+
this.#sinceDelivery.clear();
|
|
698
|
+
this.#lastRecoveryLog = -RECOVERY_LOG_MS;
|
|
699
|
+
}
|
|
700
|
+
};
|
|
701
|
+
var PROCESS_DROPS = new DropCounts();
|
|
702
|
+
|
|
703
|
+
// src/sequence.ts
|
|
704
|
+
var lastSequence = 0;
|
|
705
|
+
function nextClockSequence() {
|
|
706
|
+
const nowMicros = Math.floor((performance.timeOrigin + performance.now()) * 1e3);
|
|
707
|
+
lastSequence = Math.max(lastSequence + 1, nowMicros);
|
|
708
|
+
return lastSequence;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// src/sinks.ts
|
|
712
|
+
var REFUSAL_BODY_MAX_LEN = 500;
|
|
713
|
+
var REFUSAL_LOG_MS = 6e4;
|
|
559
714
|
async function safeWrite(sink, event) {
|
|
560
715
|
try {
|
|
561
716
|
await sink.write(event);
|
|
562
717
|
} catch (err) {
|
|
563
|
-
|
|
718
|
+
PROCESS_DROPS.add("write_failed");
|
|
719
|
+
process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
|
|
564
720
|
`);
|
|
565
721
|
}
|
|
566
722
|
}
|
|
723
|
+
function stderrLine(message) {
|
|
724
|
+
process.stderr.write(`${message}
|
|
725
|
+
`);
|
|
726
|
+
}
|
|
727
|
+
function isTimerMs(value) {
|
|
728
|
+
return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
|
|
729
|
+
}
|
|
730
|
+
function shutdownFlushTimeoutOption(given) {
|
|
731
|
+
if (isTimerMs(given)) return given;
|
|
732
|
+
if (given !== void 0) {
|
|
733
|
+
warn(`baton: shutdownFlushTimeoutMs must be from 0 to ${MAX_TIMER_MS} ms; using ${SHUTDOWN_FLUSH_TIMEOUT_MS}.`);
|
|
734
|
+
}
|
|
735
|
+
return SHUTDOWN_FLUSH_TIMEOUT_MS;
|
|
736
|
+
}
|
|
737
|
+
function shutdownBudgetMs(sink) {
|
|
738
|
+
try {
|
|
739
|
+
if (sink instanceof MultiSink) return Math.max(...sink["sinks"].map(shutdownBudgetMs));
|
|
740
|
+
const budget = sink instanceof HttpSink ? sink["shutdownFlushTimeoutMs"] : void 0;
|
|
741
|
+
if (isTimerMs(budget)) return budget;
|
|
742
|
+
} catch {
|
|
743
|
+
}
|
|
744
|
+
return SHUTDOWN_FLUSH_TIMEOUT_MS;
|
|
745
|
+
}
|
|
746
|
+
function callWithin(sink, method, ms) {
|
|
747
|
+
if (sink[method] === HttpSink.prototype[method]) return sink[`${method}Within`](ms);
|
|
748
|
+
if (sink[method] === MultiSink.prototype[method]) return sink[`${method}Within`](ms);
|
|
749
|
+
return sink[method]();
|
|
750
|
+
}
|
|
751
|
+
async function boundedSinkCall(sink, method, work = () => sink[method]()) {
|
|
752
|
+
const what = `${method}()`;
|
|
753
|
+
const budget = shutdownBudgetMs(sink);
|
|
754
|
+
const ms = budget + 250;
|
|
755
|
+
const settled = Promise.resolve().then(() => work(budget)).then(
|
|
756
|
+
() => void 0,
|
|
757
|
+
(err) => warn(`baton: ${what} failed: ${printable(err)}`)
|
|
758
|
+
);
|
|
759
|
+
if (await raceDeadline(settled, ms) === TIMED_OUT) {
|
|
760
|
+
warn(`baton: ${what} took over ${String(ms)} ms and was left unfinished.`);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
567
763
|
var StdoutSink = class {
|
|
568
764
|
stream;
|
|
569
765
|
closed = false;
|
|
@@ -580,6 +776,57 @@ var StdoutSink = class {
|
|
|
580
776
|
this.closed = true;
|
|
581
777
|
}
|
|
582
778
|
};
|
|
779
|
+
var FileSink = class {
|
|
780
|
+
constructor(path) {
|
|
781
|
+
this.path = path;
|
|
782
|
+
}
|
|
783
|
+
path;
|
|
784
|
+
fd = null;
|
|
785
|
+
closed = false;
|
|
786
|
+
async write(event) {
|
|
787
|
+
if (this.closed) throw new Error("FileSink is closed");
|
|
788
|
+
this.fd ??= (0, import_node_fs.openSync)(this.path, "a");
|
|
789
|
+
(0, import_node_fs.writeSync)(this.fd, JSON.stringify(event) + "\n");
|
|
790
|
+
}
|
|
791
|
+
async flush() {
|
|
792
|
+
}
|
|
793
|
+
async aclose() {
|
|
794
|
+
if (this.closed) return;
|
|
795
|
+
this.closed = true;
|
|
796
|
+
if (this.fd !== null) {
|
|
797
|
+
(0, import_node_fs.closeSync)(this.fd);
|
|
798
|
+
this.fd = null;
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
var MultiSink = class {
|
|
803
|
+
sinks;
|
|
804
|
+
constructor(sinks) {
|
|
805
|
+
if (sinks.length === 0) throw new Error("MultiSink requires at least one sink");
|
|
806
|
+
this.sinks = [...sinks];
|
|
807
|
+
}
|
|
808
|
+
write(event) {
|
|
809
|
+
return this.fanOut((sink) => sink.write(event));
|
|
810
|
+
}
|
|
811
|
+
flush() {
|
|
812
|
+
return this.flushWithin(Infinity);
|
|
813
|
+
}
|
|
814
|
+
aclose() {
|
|
815
|
+
return this.acloseWithin(Infinity);
|
|
816
|
+
}
|
|
817
|
+
flushWithin(ms) {
|
|
818
|
+
return this.fanOut((sink) => callWithin(sink, "flush", ms));
|
|
819
|
+
}
|
|
820
|
+
acloseWithin(ms) {
|
|
821
|
+
return this.fanOut((sink) => callWithin(sink, "aclose", ms));
|
|
822
|
+
}
|
|
823
|
+
async fanOut(op) {
|
|
824
|
+
const results = await Promise.allSettled(this.sinks.map(async (sink) => op(sink)));
|
|
825
|
+
const errors = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
|
|
826
|
+
if (errors.length === 1) throw errors[0];
|
|
827
|
+
if (errors.length > 1) throw new AggregateError(errors, "MultiSink fan-out failures");
|
|
828
|
+
}
|
|
829
|
+
};
|
|
583
830
|
var CircuitBreaker = class {
|
|
584
831
|
constructor(threshold, resetMs) {
|
|
585
832
|
this.threshold = threshold;
|
|
@@ -609,19 +856,43 @@ var HttpSink = class _HttpSink {
|
|
|
609
856
|
apiKey;
|
|
610
857
|
buffer = [];
|
|
611
858
|
bufferSize;
|
|
859
|
+
requestTimeoutMs;
|
|
860
|
+
shutdownFlushTimeoutMs;
|
|
861
|
+
/** Set when an exit pass ends; cleared once a normal drain empties the
|
|
862
|
+
* buffer, which means the process went on. */
|
|
863
|
+
exitPassRan = false;
|
|
864
|
+
/** Whether the exit pass warned about every event now buffered. */
|
|
865
|
+
unsentWarned = false;
|
|
612
866
|
maxRetries;
|
|
613
867
|
backoffBaseMs;
|
|
614
868
|
backoffMaxMs;
|
|
615
869
|
circuit;
|
|
616
870
|
fetchImpl;
|
|
617
871
|
overflowWarned = false;
|
|
618
|
-
|
|
872
|
+
/** Per status, so a new kind of refusal, such as a 401 after a 422, still warns. */
|
|
873
|
+
refusals = /* @__PURE__ */ new Map();
|
|
874
|
+
/** Aborted once `aclose()` returns: nothing Baton started may keep the
|
|
875
|
+
* process alive after the vendor closed it. */
|
|
876
|
+
closing = new AbortController();
|
|
877
|
+
/** The drain chain's tail when a flush() or aclose() gave up waiting, until it settles. */
|
|
878
|
+
stalledDrain = null;
|
|
879
|
+
skipWarnedFor = null;
|
|
880
|
+
closeOnce;
|
|
619
881
|
drainChain = Promise.resolve();
|
|
620
|
-
|
|
882
|
+
exitHooks = null;
|
|
883
|
+
/** The least time between two of this sink's loss reports. */
|
|
884
|
+
static reportIntervalMs = 6e4;
|
|
885
|
+
/** Totals only grow, so their sum tells whether they changed. */
|
|
886
|
+
reportedSum = 0;
|
|
887
|
+
lastReportAt = -Infinity;
|
|
888
|
+
reportsStopped = false;
|
|
889
|
+
reportInFlight = null;
|
|
621
890
|
constructor(url, options) {
|
|
622
891
|
this.url = url.replace(/\/+$/, "");
|
|
623
892
|
this.apiKey = options.apiKey;
|
|
624
893
|
this.bufferSize = options.bufferSize ?? 1e3;
|
|
894
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
|
|
895
|
+
this.shutdownFlushTimeoutMs = shutdownFlushTimeoutOption(options.shutdownFlushTimeoutMs);
|
|
625
896
|
this.maxRetries = options.maxRetries ?? 3;
|
|
626
897
|
this.backoffBaseMs = options.backoffBaseMs ?? 100;
|
|
627
898
|
this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
|
|
@@ -637,9 +908,7 @@ var HttpSink = class _HttpSink {
|
|
|
637
908
|
* ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it
|
|
638
909
|
* hangs off `BatonHandle.sink` and off the resolved config, so
|
|
639
910
|
* `console.log(handle.sink)` or a structured logger serialising either one
|
|
640
|
-
*
|
|
641
|
-
* asserts the DSN's own string does not survive resolution: it does not, and
|
|
642
|
-
* the key was one field further down. Same treatment as the parsed DSN —
|
|
911
|
+
* would write a publishable key into the vendor's logs. Same treatment as the parsed DSN —
|
|
643
912
|
* `toJSON` for serialisers, the inspect symbol for `console.log`, and
|
|
644
913
|
* `Symbol.for` rather than importing `node:util`, since this package runs on
|
|
645
914
|
* runtimes that have no such module.
|
|
@@ -650,29 +919,84 @@ var HttpSink = class _HttpSink {
|
|
|
650
919
|
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
651
920
|
return this.toJSON();
|
|
652
921
|
}
|
|
922
|
+
get closed() {
|
|
923
|
+
return this.closing.signal.aborted;
|
|
924
|
+
}
|
|
653
925
|
async write(event) {
|
|
654
926
|
if (this.closed) throw new Error("HttpSink is closed");
|
|
655
927
|
this.enqueue(event);
|
|
928
|
+
this.unsentWarned = false;
|
|
656
929
|
void this.scheduleDrain();
|
|
657
|
-
this.
|
|
930
|
+
this.ensureExitHooksRegistered();
|
|
658
931
|
}
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
await this.scheduleDrain();
|
|
932
|
+
flush() {
|
|
933
|
+
return this.flushWithin(Infinity);
|
|
662
934
|
}
|
|
663
|
-
|
|
935
|
+
/** A second call waits for the first (SPEC §11.2 rule 7). */
|
|
936
|
+
aclose() {
|
|
937
|
+
return this.acloseWithin(Infinity);
|
|
938
|
+
}
|
|
939
|
+
async flushWithin(ms) {
|
|
664
940
|
if (this.closed) return;
|
|
665
|
-
await this.flush();
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
941
|
+
await this.drainWithinBudget("flush()", Math.min(ms, this.shutdownFlushTimeoutMs));
|
|
942
|
+
}
|
|
943
|
+
acloseWithin(ms) {
|
|
944
|
+
this.closeOnce ??= this.close(Math.min(ms, this.shutdownFlushTimeoutMs));
|
|
945
|
+
return this.closeOnce;
|
|
946
|
+
}
|
|
947
|
+
async close(ms) {
|
|
948
|
+
this.stopReports();
|
|
949
|
+
await this.drainWithinBudget("aclose()", ms);
|
|
950
|
+
this.closing.abort();
|
|
951
|
+
if (this.buffer.length > 0) {
|
|
952
|
+
PROCESS_DROPS.add("unsent_at_close", this.buffer.length);
|
|
953
|
+
warn(`baton: the sink closed with ${this.buffer.length} event(s) unsent.`);
|
|
954
|
+
}
|
|
955
|
+
this.warnUnloggedRefusals("the sink closed");
|
|
956
|
+
if (this.exitHooks) {
|
|
957
|
+
process.off("beforeExit", this.exitHooks.beforeExit);
|
|
958
|
+
process.off("exit", this.exitHooks.exit);
|
|
959
|
+
this.exitHooks = null;
|
|
670
960
|
}
|
|
671
961
|
}
|
|
962
|
+
/** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and
|
|
963
|
+
* never rejects. While an earlier wait's drain is still stuck, a flush
|
|
964
|
+
* returns at once, without queuing a pass, and a close gives it `ms`. The
|
|
965
|
+
* drain is not cancelled here, so after `flush()` it goes on sending;
|
|
966
|
+
* `aclose()` stops it. */
|
|
967
|
+
async drainWithinBudget(what, ms) {
|
|
968
|
+
if (this.stalledDrain) {
|
|
969
|
+
if (what === "aclose()") {
|
|
970
|
+
await raceDeadline(this.stalledDrain, ms);
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
if (this.skipWarnedFor !== this.stalledDrain) {
|
|
974
|
+
this.skipWarnedFor = this.stalledDrain;
|
|
975
|
+
warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.buffer.length} event(s) wait to be sent.`);
|
|
976
|
+
}
|
|
977
|
+
return;
|
|
978
|
+
}
|
|
979
|
+
const settled = this.scheduleDrain().catch(() => void 0);
|
|
980
|
+
if (await raceDeadline(settled, ms) !== TIMED_OUT) return;
|
|
981
|
+
if (ms < this.shutdownFlushTimeoutMs) return;
|
|
982
|
+
const stalled = this.drainChain.catch(() => void 0);
|
|
983
|
+
this.stalledDrain = stalled;
|
|
984
|
+
void stalled.then(() => {
|
|
985
|
+
if (this.stalledDrain === stalled) this.stalledDrain = null;
|
|
986
|
+
});
|
|
987
|
+
if (what === "flush()") {
|
|
988
|
+
warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
/** A full buffer may already have pushed `event` out while it was being sent. */
|
|
992
|
+
dequeue(event) {
|
|
993
|
+
if (this.buffer[0] === event) this.buffer.shift();
|
|
994
|
+
}
|
|
672
995
|
enqueue(event) {
|
|
673
996
|
if (this.buffer.length >= this.bufferSize) {
|
|
997
|
+
PROCESS_DROPS.add("buffer_full");
|
|
674
998
|
if (!this.overflowWarned) {
|
|
675
|
-
|
|
999
|
+
warn(
|
|
676
1000
|
`Baton HTTP sink buffer full (${this.bufferSize}); oldest events dropped. Further overflows will be silent.`
|
|
677
1001
|
);
|
|
678
1002
|
this.overflowWarned = true;
|
|
@@ -694,18 +1018,58 @@ var HttpSink = class _HttpSink {
|
|
|
694
1018
|
return this.drainChain;
|
|
695
1019
|
}
|
|
696
1020
|
/** Best-effort flush when the process is about to exit without an
|
|
697
|
-
* explicit `aclose()`.
|
|
698
|
-
*
|
|
699
|
-
*
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
1021
|
+
* explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip
|
|
1022
|
+
* both hooks: a vendor needing that guarantee must call `aclose()` from
|
|
1023
|
+
* their own handler. */
|
|
1024
|
+
ensureExitHooksRegistered() {
|
|
1025
|
+
if (this.exitHooks) return;
|
|
1026
|
+
const beforeExit = () => {
|
|
1027
|
+
if (this.buffer.length === 0 || this.exitPassRan) {
|
|
1028
|
+
this.warnUnloggedRefusals("process exiting");
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
this.drainChain = this.drainChain.then(
|
|
1032
|
+
() => this.exitPass(),
|
|
1033
|
+
() => this.exitPass()
|
|
1034
|
+
);
|
|
707
1035
|
};
|
|
708
|
-
|
|
1036
|
+
const exit = () => {
|
|
1037
|
+
try {
|
|
1038
|
+
if (this.buffer.length > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
|
|
1039
|
+
this.warnUnloggedRefusals("process exiting", stderrLine);
|
|
1040
|
+
} catch {
|
|
1041
|
+
}
|
|
1042
|
+
};
|
|
1043
|
+
this.exitHooks = { beforeExit, exit };
|
|
1044
|
+
process.on("beforeExit", beforeExit);
|
|
1045
|
+
process.on("exit", exit);
|
|
1046
|
+
}
|
|
1047
|
+
/** One attempt per event, no retry, within `shutdownFlushTimeoutMs` in
|
|
1048
|
+
* total (SPEC §11.2); what is left is reported, not sent. */
|
|
1049
|
+
async exitPass() {
|
|
1050
|
+
const deadline = Date.now() + this.shutdownFlushTimeoutMs;
|
|
1051
|
+
while (this.buffer.length > 0 && this.circuit.canRequest()) {
|
|
1052
|
+
const timeLeft = deadline - Date.now();
|
|
1053
|
+
if (timeLeft <= 0) break;
|
|
1054
|
+
const event = this.buffer[0];
|
|
1055
|
+
const body = this.encode(event);
|
|
1056
|
+
if (body !== null) {
|
|
1057
|
+
const outcome = await this.postOnce(body, Math.min(this.requestTimeoutMs, timeLeft));
|
|
1058
|
+
if (outcome === "transient_failure") {
|
|
1059
|
+
this.circuit.recordFailure();
|
|
1060
|
+
break;
|
|
1061
|
+
}
|
|
1062
|
+
this.circuit.recordSuccess();
|
|
1063
|
+
}
|
|
1064
|
+
this.dequeue(event);
|
|
1065
|
+
}
|
|
1066
|
+
this.exitPassRan = true;
|
|
1067
|
+
this.unsentWarned = true;
|
|
1068
|
+
if (this.buffer.length > 0) warn(this.unsentAtExit());
|
|
1069
|
+
this.warnUnloggedRefusals("process exiting");
|
|
1070
|
+
}
|
|
1071
|
+
unsentAtExit() {
|
|
1072
|
+
return `baton: process exiting with ${this.buffer.length} unsent event(s).`;
|
|
709
1073
|
}
|
|
710
1074
|
events_url() {
|
|
711
1075
|
return `${this.url}/v0/events`;
|
|
@@ -718,38 +1082,197 @@ var HttpSink = class _HttpSink {
|
|
|
718
1082
|
if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
|
|
719
1083
|
return "transient_failure";
|
|
720
1084
|
}
|
|
1085
|
+
/** A refused event is otherwise dropped silently, which looks the same from
|
|
1086
|
+
* the vendor's process as an accepted one. The collector's own message is
|
|
1087
|
+
* logged because it names the field at fault; it is capped and escaped
|
|
1088
|
+
* because it is a remote server's text landing in the vendor's log. */
|
|
1089
|
+
static async logRefusal(response, unlogged) {
|
|
1090
|
+
const detail = await _HttpSink.readHead(response).then(
|
|
1091
|
+
(text) => escapeForLog(capCodePoints(text, REFUSAL_BODY_MAX_LEN)),
|
|
1092
|
+
() => "<unreadable>"
|
|
1093
|
+
);
|
|
1094
|
+
warn(
|
|
1095
|
+
`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.` : "")
|
|
1096
|
+
);
|
|
1097
|
+
}
|
|
1098
|
+
warnUnloggedRefusals(when, emit2 = warn) {
|
|
1099
|
+
let total = 0;
|
|
1100
|
+
for (const seen of this.refusals.values()) {
|
|
1101
|
+
total += seen.unlogged;
|
|
1102
|
+
seen.unlogged = 0;
|
|
1103
|
+
}
|
|
1104
|
+
if (total > 0) emit2(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);
|
|
1105
|
+
}
|
|
1106
|
+
/** How many refusals with `status` went unlogged before this one, or `null`
|
|
1107
|
+
* when this one goes unlogged too. */
|
|
1108
|
+
refusalToLog(status) {
|
|
1109
|
+
const now = performance.now();
|
|
1110
|
+
const seen = this.refusals.get(status);
|
|
1111
|
+
if (seen !== void 0 && now - seen.loggedAt < REFUSAL_LOG_MS) {
|
|
1112
|
+
seen.unlogged++;
|
|
1113
|
+
return null;
|
|
1114
|
+
}
|
|
1115
|
+
this.refusals.set(status, { loggedAt: now, unlogged: 0 });
|
|
1116
|
+
return seen?.unlogged ?? 0;
|
|
1117
|
+
}
|
|
1118
|
+
/** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is
|
|
1119
|
+
* cancelled unread, so a large error page does not hold the drain. */
|
|
1120
|
+
static async readHead(response) {
|
|
1121
|
+
const reader = response.body?.getReader();
|
|
1122
|
+
if (reader === void 0) return "";
|
|
1123
|
+
const decoder = new TextDecoder();
|
|
1124
|
+
let text = "";
|
|
1125
|
+
try {
|
|
1126
|
+
while (text.length < REFUSAL_BODY_MAX_LEN * 2) {
|
|
1127
|
+
const { done, value } = await reader.read();
|
|
1128
|
+
if (done) return text + decoder.decode();
|
|
1129
|
+
text += decoder.decode(value, { stream: true });
|
|
1130
|
+
}
|
|
1131
|
+
return text;
|
|
1132
|
+
} finally {
|
|
1133
|
+
void reader.cancel().catch(() => {
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
721
1137
|
async drainLocked() {
|
|
722
1138
|
while (this.buffer.length > 0) {
|
|
723
|
-
if (!this.circuit.canRequest()) return;
|
|
1139
|
+
if (!this.circuit.canRequest() || this.closing.signal.aborted) return;
|
|
724
1140
|
const event = this.buffer[0];
|
|
725
1141
|
const outcome = await this.sendWithRetry(event);
|
|
726
1142
|
if (outcome === "success" || outcome === "permanent_failure") {
|
|
727
|
-
this.
|
|
1143
|
+
this.dequeue(event);
|
|
728
1144
|
this.circuit.recordSuccess();
|
|
1145
|
+
if (outcome === "success") {
|
|
1146
|
+
PROCESS_DROPS.logRecovery();
|
|
1147
|
+
this.maybeReport(event);
|
|
1148
|
+
}
|
|
1149
|
+
} else if (outcome === "unencodable") {
|
|
1150
|
+
this.dequeue(event);
|
|
729
1151
|
} else {
|
|
730
1152
|
this.circuit.recordFailure();
|
|
731
1153
|
return;
|
|
732
1154
|
}
|
|
733
1155
|
}
|
|
1156
|
+
this.exitPassRan = false;
|
|
1157
|
+
}
|
|
1158
|
+
/** Starts a report of this process's loss totals (SPEC §11.4.7) beside the
|
|
1159
|
+
* drain and outside the buffer, so it never delays an event and is never
|
|
1160
|
+
* counted as one. */
|
|
1161
|
+
maybeReport({ tenant_id, vendor_id, consent_token }) {
|
|
1162
|
+
const now = performance.now();
|
|
1163
|
+
if (this.reportsStopped || this.reportInFlight !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
const totals = PROCESS_DROPS.total();
|
|
1167
|
+
const sum = Object.values(totals).reduce((a, b) => a + b, 0);
|
|
1168
|
+
if (sum === this.reportedSum) return;
|
|
1169
|
+
this.lastReportAt = now;
|
|
1170
|
+
const abort = new AbortController();
|
|
1171
|
+
this.reportInFlight = abort;
|
|
1172
|
+
const envelope = { tenant_id, vendor_id, consent_token };
|
|
1173
|
+
void this.sendReport(envelope, totals, sum, abort).finally(() => {
|
|
1174
|
+
this.reportInFlight = null;
|
|
1175
|
+
});
|
|
1176
|
+
}
|
|
1177
|
+
stopReports() {
|
|
1178
|
+
this.reportsStopped = true;
|
|
1179
|
+
this.reportInFlight?.abort();
|
|
1180
|
+
}
|
|
1181
|
+
async sendReport(envelope, totals, sum, abort) {
|
|
1182
|
+
const timer = setTimeout(() => abort.abort(), this.requestTimeoutMs);
|
|
1183
|
+
try {
|
|
1184
|
+
const report = ClientReportEventSchema.parse({
|
|
1185
|
+
...envelope,
|
|
1186
|
+
session_id: PROCESS_DROPS.instanceId,
|
|
1187
|
+
sequence_number: nextClockSequence(),
|
|
1188
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1189
|
+
payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
|
|
1190
|
+
});
|
|
1191
|
+
const response = await this.fetchImpl(this.events_url(), {
|
|
1192
|
+
method: "POST",
|
|
1193
|
+
headers: this.authHeaders(),
|
|
1194
|
+
body: JSON.stringify(report),
|
|
1195
|
+
signal: abort.signal
|
|
1196
|
+
});
|
|
1197
|
+
void response.body?.cancel().catch(() => void 0);
|
|
1198
|
+
if (response.status === 400 || response.status === 422) this.reportsStopped = true;
|
|
1199
|
+
else if (_HttpSink.classifyStatus(response.status) === "success") this.reportedSum = sum;
|
|
1200
|
+
} catch {
|
|
1201
|
+
} finally {
|
|
1202
|
+
clearTimeout(timer);
|
|
1203
|
+
}
|
|
734
1204
|
}
|
|
735
1205
|
async sendWithRetry(event) {
|
|
736
|
-
const
|
|
737
|
-
|
|
738
|
-
const body = JSON.stringify(event);
|
|
1206
|
+
const body = this.encode(event);
|
|
1207
|
+
if (body === null) return "unencodable";
|
|
739
1208
|
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
const outcome = _HttpSink.classifyStatus(response.status);
|
|
743
|
-
if (outcome !== "transient_failure") return outcome;
|
|
744
|
-
} catch {
|
|
745
|
-
}
|
|
1209
|
+
const outcome = await this.postOnce(body, this.requestTimeoutMs);
|
|
1210
|
+
if (outcome !== "transient_failure") return outcome;
|
|
746
1211
|
if (attempt < this.maxRetries) {
|
|
747
1212
|
const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);
|
|
748
|
-
await
|
|
1213
|
+
await this.sleepUnlessClosed(backoff);
|
|
1214
|
+
if (this.closing.signal.aborted) return "transient_failure";
|
|
749
1215
|
}
|
|
750
1216
|
}
|
|
751
1217
|
return "transient_failure";
|
|
752
1218
|
}
|
|
1219
|
+
/** `null`, with a warning, for an event `JSON.stringify` rejects. */
|
|
1220
|
+
encode(event) {
|
|
1221
|
+
try {
|
|
1222
|
+
return JSON.stringify(event);
|
|
1223
|
+
} catch (err) {
|
|
1224
|
+
PROCESS_DROPS.add("encode_failed");
|
|
1225
|
+
warn(
|
|
1226
|
+
`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.`
|
|
1227
|
+
);
|
|
1228
|
+
return null;
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
sleepUnlessClosed(ms) {
|
|
1232
|
+
if (this.closed) return Promise.resolve();
|
|
1233
|
+
return new Promise((resolve) => {
|
|
1234
|
+
const done = () => {
|
|
1235
|
+
clearTimeout(timer);
|
|
1236
|
+
this.closing.signal.removeEventListener("abort", done);
|
|
1237
|
+
resolve();
|
|
1238
|
+
};
|
|
1239
|
+
const timer = setTimeout(done, ms);
|
|
1240
|
+
this.closing.signal.addEventListener("abort", done);
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
/** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`
|
|
1244
|
+
* is missing before Node 20.3, and on some later versions it keeps every
|
|
1245
|
+
* combined signal alive as long as the long-lived `closing` signal. */
|
|
1246
|
+
async postOnce(body, timeoutMs) {
|
|
1247
|
+
const request = new AbortController();
|
|
1248
|
+
const abort = () => request.abort();
|
|
1249
|
+
const timer = setTimeout(abort, timeoutMs);
|
|
1250
|
+
this.closing.signal.addEventListener("abort", abort);
|
|
1251
|
+
try {
|
|
1252
|
+
const response = await this.fetchImpl(this.events_url(), {
|
|
1253
|
+
method: "POST",
|
|
1254
|
+
headers: this.authHeaders(),
|
|
1255
|
+
body,
|
|
1256
|
+
signal: request.signal
|
|
1257
|
+
});
|
|
1258
|
+
const outcome = _HttpSink.classifyStatus(response.status);
|
|
1259
|
+
if (outcome === "permanent_failure") {
|
|
1260
|
+
PROCESS_DROPS.add("refused");
|
|
1261
|
+
const unlogged = this.refusalToLog(response.status);
|
|
1262
|
+
if (unlogged !== null) {
|
|
1263
|
+
await _HttpSink.logRefusal(response, unlogged);
|
|
1264
|
+
return outcome;
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
void response.body?.cancel().catch(() => void 0);
|
|
1268
|
+
return outcome;
|
|
1269
|
+
} catch {
|
|
1270
|
+
return "transient_failure";
|
|
1271
|
+
} finally {
|
|
1272
|
+
clearTimeout(timer);
|
|
1273
|
+
this.closing.signal.removeEventListener("abort", abort);
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
753
1276
|
};
|
|
754
1277
|
|
|
755
1278
|
// src/integrations/mcp/withBaton.ts
|
|
@@ -761,11 +1284,6 @@ var import_zod2 = require("zod");
|
|
|
761
1284
|
// src/metaCoordinates.ts
|
|
762
1285
|
var COORD_FIELD_NAMES = /* @__PURE__ */ new Set(["latitude", "longitude"]);
|
|
763
1286
|
var DECIMAL_STRING = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
|
|
764
|
-
function isPlainObject2(value) {
|
|
765
|
-
if (typeof value !== "object" || value === null) return false;
|
|
766
|
-
const proto = Object.getPrototypeOf(value);
|
|
767
|
-
return proto === Object.prototype || proto === null;
|
|
768
|
-
}
|
|
769
1287
|
function toOneDecimal(value) {
|
|
770
1288
|
const magnitude = Math.abs(value);
|
|
771
1289
|
if (Number.isInteger(magnitude * 4) && !Number.isInteger(magnitude * 2)) {
|
|
@@ -786,7 +1304,7 @@ function roundCoordinate(value) {
|
|
|
786
1304
|
}
|
|
787
1305
|
function walk(value, depth) {
|
|
788
1306
|
if (depth >= DEPTH_LIMIT) return value;
|
|
789
|
-
if (
|
|
1307
|
+
if (isPlainObject(value)) {
|
|
790
1308
|
const out = {};
|
|
791
1309
|
for (const [k, v] of Object.entries(value)) {
|
|
792
1310
|
const rounded = COORD_FIELD_NAMES.has(k.toLowerCase()) && depth + 1 < DEPTH_LIMIT ? roundCoordinate(v) : void 0;
|
|
@@ -803,69 +1321,6 @@ function roundMetaCoordinates(meta) {
|
|
|
803
1321
|
return walk(meta, 0);
|
|
804
1322
|
}
|
|
805
1323
|
|
|
806
|
-
// src/_text.ts
|
|
807
|
-
function exceedsCodePoints(value, max) {
|
|
808
|
-
if (value.length <= max) return false;
|
|
809
|
-
if (value.length > 2 * max) return true;
|
|
810
|
-
return [...value].length > max;
|
|
811
|
-
}
|
|
812
|
-
function capCodePoints(value, max) {
|
|
813
|
-
if (value.length <= max) return value;
|
|
814
|
-
return [...value].slice(0, max).join("");
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
// src/identity.ts
|
|
818
|
-
var PRINCIPAL_SOURCE_ASSERTED = "asserted";
|
|
819
|
-
var PRINCIPAL_FORM_HASHED = "hashed";
|
|
820
|
-
var PRINCIPAL_FORM_RAW = "raw";
|
|
821
|
-
var PRINCIPAL_ID_MAX_LEN = 128;
|
|
822
|
-
var DISPLAY_NAME_MAX_LEN = 128;
|
|
823
|
-
var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
|
|
824
|
-
function wireDisplayName(value) {
|
|
825
|
-
if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
|
|
826
|
-
if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
|
|
827
|
-
return value;
|
|
828
|
-
}
|
|
829
|
-
var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
|
|
830
|
-
var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
|
|
831
|
-
var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
|
|
832
|
-
var LONE_SURROGATE = /\p{Surrogate}/u;
|
|
833
|
-
function pythonStrip(value) {
|
|
834
|
-
return value.replace(PYTHON_STRIP, "");
|
|
835
|
-
}
|
|
836
|
-
function normalizePrincipal(result) {
|
|
837
|
-
if (result === null || typeof result !== "object") return null;
|
|
838
|
-
const candidate = result;
|
|
839
|
-
if (typeof candidate.principalId !== "string") return null;
|
|
840
|
-
if (LONE_SURROGATE.test(candidate.principalId)) return null;
|
|
841
|
-
if (candidate.principalId.includes("\0")) return null;
|
|
842
|
-
if (pythonStrip(candidate.principalId) === "") return null;
|
|
843
|
-
const principal = { principalId: candidate.principalId };
|
|
844
|
-
if (candidate.form !== void 0) principal.form = candidate.form;
|
|
845
|
-
if (typeof candidate.displayName === "string") principal.displayName = candidate.displayName;
|
|
846
|
-
return principal;
|
|
847
|
-
}
|
|
848
|
-
function principalFor(principal, onUnregisteredForm) {
|
|
849
|
-
let form = PRINCIPAL_FORM_RAW;
|
|
850
|
-
if (principal.form !== void 0) {
|
|
851
|
-
if (PRINCIPAL_FORMS.has(principal.form)) {
|
|
852
|
-
form = principal.form;
|
|
853
|
-
} else {
|
|
854
|
-
onUnregisteredForm?.(principal.form);
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
const wire = {
|
|
858
|
-
// `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
|
|
859
|
-
// an astral id cut at the boundary would ship a lone surrogate.
|
|
860
|
-
id: capCodePoints(principal.principalId, PRINCIPAL_ID_MAX_LEN),
|
|
861
|
-
source: PRINCIPAL_SOURCE_ASSERTED,
|
|
862
|
-
form
|
|
863
|
-
};
|
|
864
|
-
const displayName = wireDisplayName(principal.displayName);
|
|
865
|
-
if (displayName !== null) wire.display_name = displayName;
|
|
866
|
-
return wire;
|
|
867
|
-
}
|
|
868
|
-
|
|
869
1324
|
// src/integrations/mcp/llmText.ts
|
|
870
1325
|
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.`;
|
|
871
1326
|
var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
|
|
@@ -937,14 +1392,14 @@ var OURS_STARTS = [
|
|
|
937
1392
|
];
|
|
938
1393
|
function endsInOurs(current2, vendor) {
|
|
939
1394
|
if (typeof current2 !== "string") return false;
|
|
940
|
-
const prefix = typeof vendor === "string" && vendor
|
|
1395
|
+
const prefix = typeof vendor === "string" && !isBlank(vendor) ? `${vendor}
|
|
941
1396
|
|
|
942
1397
|
` : "";
|
|
943
1398
|
if (!current2.startsWith(prefix)) return false;
|
|
944
1399
|
const rest = current2.slice(prefix.length);
|
|
945
1400
|
return OURS_STARTS.some((start) => start.test(rest));
|
|
946
1401
|
}
|
|
947
|
-
function withVendorInstructions(server, ours,
|
|
1402
|
+
function withVendorInstructions(server, ours, warn3 = (message) => process.stderr.write(message)) {
|
|
948
1403
|
const holder = server;
|
|
949
1404
|
const current2 = holder._instructions;
|
|
950
1405
|
let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
|
|
@@ -952,12 +1407,12 @@ function withVendorInstructions(server, ours, warn4 = (message) => process.stder
|
|
|
952
1407
|
vendor = current2;
|
|
953
1408
|
holder[VENDOR_INSTRUCTIONS] = vendor;
|
|
954
1409
|
}
|
|
955
|
-
if (typeof vendor !== "string" ||
|
|
1410
|
+
if (typeof vendor !== "string" || isBlank(vendor)) return ours;
|
|
956
1411
|
const combined = `${vendor}
|
|
957
1412
|
|
|
958
1413
|
${ours}`;
|
|
959
1414
|
if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
|
|
960
|
-
|
|
1415
|
+
warn3(
|
|
961
1416
|
`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
|
|
962
1417
|
`
|
|
963
1418
|
);
|
|
@@ -971,17 +1426,17 @@ var SUFFIX = "_annotate";
|
|
|
971
1426
|
var SLUG_CAP = 30;
|
|
972
1427
|
var PLACEHOLDER_LITERALS = /* @__PURE__ */ new Set(["fastmcp", "mcp-server"]);
|
|
973
1428
|
var RANDOM_SUFFIX = /-[0-9a-f]{4}$/;
|
|
1429
|
+
var SEPARATORS = "\\x1c-\\x1f";
|
|
1430
|
+
var PYTHON_SPACE = new RegExp(`^[\\p{White_Space}${SEPARATORS}]$`, "u");
|
|
1431
|
+
function pythonStrip(value) {
|
|
1432
|
+
return stripEdges(value, PYTHON_SPACE);
|
|
1433
|
+
}
|
|
974
1434
|
function isLibraryPlaceholder(serverName, className) {
|
|
975
1435
|
const stripped = pythonStrip(serverName);
|
|
976
1436
|
if (PLACEHOLDER_LITERALS.has(stripped.toLowerCase())) return true;
|
|
977
1437
|
const stem = stripped.replace(RANDOM_SUFFIX, "");
|
|
978
1438
|
return stem !== stripped && stem === className;
|
|
979
1439
|
}
|
|
980
|
-
function warn(message) {
|
|
981
|
-
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
982
|
-
process.emitWarning(message);
|
|
983
|
-
}
|
|
984
|
-
}
|
|
985
1440
|
function usableServerName(read) {
|
|
986
1441
|
let name;
|
|
987
1442
|
let className;
|
|
@@ -1055,13 +1510,117 @@ async function emit(sink, build) {
|
|
|
1055
1510
|
try {
|
|
1056
1511
|
event = build();
|
|
1057
1512
|
} catch (err) {
|
|
1058
|
-
|
|
1513
|
+
PROCESS_DROPS.add("encode_failed");
|
|
1514
|
+
process.stderr.write(`baton: event construction failed; event dropped: ${printable(err)}
|
|
1059
1515
|
`);
|
|
1060
1516
|
return;
|
|
1061
1517
|
}
|
|
1062
1518
|
await safeWrite(sink, event);
|
|
1063
1519
|
}
|
|
1064
1520
|
|
|
1521
|
+
// src/identity.ts
|
|
1522
|
+
var PRINCIPAL_SOURCE_ASSERTED = "asserted";
|
|
1523
|
+
var PRINCIPAL_FORM_HASHED = "hashed";
|
|
1524
|
+
var PRINCIPAL_FORM_RAW = "raw";
|
|
1525
|
+
var PRINCIPAL_ID_MAX_LEN = 128;
|
|
1526
|
+
var DISPLAY_NAME_MAX_LEN = 128;
|
|
1527
|
+
function wireDisplayName(value) {
|
|
1528
|
+
if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
|
|
1529
|
+
if (LONE_SURROGATE.test(value) || value.includes("\0") || isBlank(value)) return null;
|
|
1530
|
+
return value;
|
|
1531
|
+
}
|
|
1532
|
+
var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
|
|
1533
|
+
var LONE_SURROGATE = /\p{Surrogate}/u;
|
|
1534
|
+
function usableId(id) {
|
|
1535
|
+
if (typeof id !== "string") return false;
|
|
1536
|
+
if (LONE_SURROGATE.test(id)) return false;
|
|
1537
|
+
if (id.includes("\0")) return false;
|
|
1538
|
+
return !isBlank(id);
|
|
1539
|
+
}
|
|
1540
|
+
function readIdentity(result, idKey) {
|
|
1541
|
+
if (result === null || typeof result !== "object") return null;
|
|
1542
|
+
const candidate = result;
|
|
1543
|
+
const id = candidate[idKey];
|
|
1544
|
+
if (!usableId(id)) return null;
|
|
1545
|
+
const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
|
|
1546
|
+
return { id, form: candidate.form, displayName };
|
|
1547
|
+
}
|
|
1548
|
+
var NO_CALLER = Object.freeze({ principal: null, organization: null });
|
|
1549
|
+
function callerFor(result, warn3) {
|
|
1550
|
+
try {
|
|
1551
|
+
return readCaller(result, warn3);
|
|
1552
|
+
} catch {
|
|
1553
|
+
warn3("unreadable", "could not be read \u2014 sending neither principal nor organization.");
|
|
1554
|
+
return NO_CALLER;
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
function readCaller(result, warn3) {
|
|
1558
|
+
if (result === void 0 || result === null) return NO_CALLER;
|
|
1559
|
+
if (typeof result !== "object") {
|
|
1560
|
+
warn3("not-object", `got a ${typeof result}, not an object \u2014 sending neither principal nor organization.`);
|
|
1561
|
+
return NO_CALLER;
|
|
1562
|
+
}
|
|
1563
|
+
if (!("principalId" in result) && !("organization" in result)) {
|
|
1564
|
+
if ("organizationId" in result) {
|
|
1565
|
+
return { principal: null, organization: identityFor(result, "organization", warn3) };
|
|
1566
|
+
}
|
|
1567
|
+
if (typeof result.userId === "string") {
|
|
1568
|
+
warn3(
|
|
1569
|
+
"user-id",
|
|
1570
|
+
"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."
|
|
1571
|
+
);
|
|
1572
|
+
} else {
|
|
1573
|
+
warn3("no-id", "got an object with neither principalId nor organizationId \u2014 sending neither.");
|
|
1574
|
+
}
|
|
1575
|
+
return NO_CALLER;
|
|
1576
|
+
}
|
|
1577
|
+
if ("organizationId" in result) {
|
|
1578
|
+
warn3("flat-organization-id", "got principalId and organizationId side by side; put the company in `organization`.");
|
|
1579
|
+
}
|
|
1580
|
+
const nested = result.organization;
|
|
1581
|
+
return {
|
|
1582
|
+
principal: identityFor(result, "principal", warn3),
|
|
1583
|
+
organization: nested == null ? null : identityFor(nested, "organization", warn3)
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
function identityFor(value, member, warn3) {
|
|
1587
|
+
const idKey = member === "principal" ? "principalId" : "organizationId";
|
|
1588
|
+
const identity = readIdentity(value, idKey);
|
|
1589
|
+
if (identity === null) {
|
|
1590
|
+
warn3(`${member}:id`, `${member} has no usable ${idKey} \u2014 sending no ${member}.`);
|
|
1591
|
+
return null;
|
|
1592
|
+
}
|
|
1593
|
+
return identityWire(
|
|
1594
|
+
identity.id,
|
|
1595
|
+
identity.form,
|
|
1596
|
+
identity.displayName,
|
|
1597
|
+
(form) => warn3(`${member}:form`, `${member} form ${describeForm(form)} is not registered \u2014 sending "raw".`)
|
|
1598
|
+
);
|
|
1599
|
+
}
|
|
1600
|
+
function describeForm(form) {
|
|
1601
|
+
return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
|
|
1602
|
+
}
|
|
1603
|
+
function identityWire(id, stated, displayName, onUnregisteredForm) {
|
|
1604
|
+
let form = PRINCIPAL_FORM_RAW;
|
|
1605
|
+
if (stated !== void 0) {
|
|
1606
|
+
if (PRINCIPAL_FORMS.has(stated)) {
|
|
1607
|
+
form = stated;
|
|
1608
|
+
} else {
|
|
1609
|
+
onUnregisteredForm?.(stated);
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
const wire = {
|
|
1613
|
+
// `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
|
|
1614
|
+
// an astral id cut at the boundary would ship a lone surrogate.
|
|
1615
|
+
id: capCodePoints(id, PRINCIPAL_ID_MAX_LEN),
|
|
1616
|
+
source: PRINCIPAL_SOURCE_ASSERTED,
|
|
1617
|
+
form
|
|
1618
|
+
};
|
|
1619
|
+
const name = wireDisplayName(displayName);
|
|
1620
|
+
if (name !== null) wire.display_name = name;
|
|
1621
|
+
return wire;
|
|
1622
|
+
}
|
|
1623
|
+
|
|
1065
1624
|
// src/integrations/mcp/mcpTypes.ts
|
|
1066
1625
|
function extraAuthInfo(extra) {
|
|
1067
1626
|
const found = extra.authInfo ?? extra.http?.authInfo;
|
|
@@ -1119,68 +1678,43 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
|
1119
1678
|
};
|
|
1120
1679
|
}
|
|
1121
1680
|
var HOOK_TIMEOUT_MS = 5e3;
|
|
1122
|
-
var TIMED_OUT = /* @__PURE__ */ Symbol("hookTimedOut");
|
|
1123
1681
|
async function withinHookBudget(answer) {
|
|
1124
1682
|
if (!isThenable(answer)) return answer;
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
timer = setTimeout(() => resolve(TIMED_OUT), HOOK_TIMEOUT_MS);
|
|
1128
|
-
timer.unref?.();
|
|
1129
|
-
});
|
|
1130
|
-
try {
|
|
1131
|
-
const first = await Promise.race([answer, deadline]);
|
|
1132
|
-
if (first !== TIMED_OUT) return first;
|
|
1133
|
-
warn(
|
|
1134
|
-
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
1135
|
-
);
|
|
1136
|
-
return null;
|
|
1137
|
-
} finally {
|
|
1138
|
-
clearTimeout(timer);
|
|
1139
|
-
}
|
|
1140
|
-
}
|
|
1141
|
-
var warnedPreRenameShape = false;
|
|
1142
|
-
function warnIfPreRenameShape(result) {
|
|
1143
|
-
const userId = result?.userId;
|
|
1144
|
-
if (warnedPreRenameShape || typeof userId !== "string") return;
|
|
1145
|
-
warnedPreRenameShape = true;
|
|
1683
|
+
const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);
|
|
1684
|
+
if (first !== TIMED_OUT) return first;
|
|
1146
1685
|
warn(
|
|
1147
|
-
|
|
1686
|
+
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
1148
1687
|
);
|
|
1688
|
+
return null;
|
|
1149
1689
|
}
|
|
1150
|
-
|
|
1151
|
-
|
|
1690
|
+
var warned = /* @__PURE__ */ new Set();
|
|
1691
|
+
function warnOnce(key, message) {
|
|
1692
|
+
if (warned.has(key)) return;
|
|
1693
|
+
warned.add(key);
|
|
1694
|
+
warn(`baton: resolvePrincipal ${message}`);
|
|
1695
|
+
}
|
|
1696
|
+
async function resolveCaller(hook, call) {
|
|
1697
|
+
if (hook === void 0) return NO_CALLER;
|
|
1152
1698
|
try {
|
|
1153
1699
|
const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
|
|
1154
1700
|
const result = await withinHookBudget(hook(context));
|
|
1155
|
-
|
|
1156
|
-
if (principal === null) {
|
|
1157
|
-
warnIfPreRenameShape(result);
|
|
1158
|
-
return null;
|
|
1159
|
-
}
|
|
1160
|
-
return principalFor(principal, (form) => {
|
|
1161
|
-
warn(
|
|
1162
|
-
`baton: resolvePrincipal returned form ${describeForm(form)}, expected "raw" or "hashed" \u2014 sending it as "${PRINCIPAL_FORM_RAW}".`
|
|
1163
|
-
);
|
|
1164
|
-
});
|
|
1701
|
+
return callerFor(result, warnOnce);
|
|
1165
1702
|
} catch {
|
|
1166
|
-
return
|
|
1703
|
+
return NO_CALLER;
|
|
1167
1704
|
}
|
|
1168
1705
|
}
|
|
1169
|
-
function describeForm(form) {
|
|
1170
|
-
return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
|
|
1171
|
-
}
|
|
1172
1706
|
|
|
1173
1707
|
// src/integrations/mcp/safeScrub.ts
|
|
1174
|
-
var
|
|
1708
|
+
var warned2 = /* @__PURE__ */ new Set();
|
|
1175
1709
|
function scrubOrNull(scrubber, value, field) {
|
|
1176
1710
|
if (value === null) return null;
|
|
1177
1711
|
try {
|
|
1178
1712
|
return scrubber(value);
|
|
1179
1713
|
} catch (err) {
|
|
1180
|
-
if (!
|
|
1181
|
-
|
|
1714
|
+
if (!warned2.has(field)) {
|
|
1715
|
+
warned2.add(field);
|
|
1182
1716
|
process.stderr.write(
|
|
1183
|
-
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${
|
|
1717
|
+
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}
|
|
1184
1718
|
`
|
|
1185
1719
|
);
|
|
1186
1720
|
}
|
|
@@ -1279,9 +1813,9 @@ function registeredHeaders(input) {
|
|
|
1279
1813
|
}
|
|
1280
1814
|
return out;
|
|
1281
1815
|
}
|
|
1282
|
-
function clientObservedFrom(clientInfo, headers, scrubber) {
|
|
1816
|
+
function clientObservedFrom(clientInfo, headers, scrubber, meta) {
|
|
1283
1817
|
return assemble(
|
|
1284
|
-
orNothing(() => cleanInfo(declared(clientInfo), scrubber)),
|
|
1818
|
+
orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),
|
|
1285
1819
|
orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
|
|
1286
1820
|
);
|
|
1287
1821
|
}
|
|
@@ -1289,16 +1823,19 @@ function clientObservedFrom(clientInfo, headers, scrubber) {
|
|
|
1289
1823
|
// src/integrations/mcp/sessionResolution.ts
|
|
1290
1824
|
async function resolveSessionId(fallbackSessionId, extra) {
|
|
1291
1825
|
if (typeof extra.sessionId === "string" && extra.sessionId) {
|
|
1292
|
-
return { sessionId: extra.sessionId, origin: "observed" };
|
|
1826
|
+
return { sessionId: extra.sessionId, origin: "observed", perCall: false };
|
|
1293
1827
|
}
|
|
1294
1828
|
const fromHeader = sessionIdFromHeader(extra);
|
|
1295
|
-
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed" };
|
|
1296
|
-
|
|
1829
|
+
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed", perCall: false };
|
|
1830
|
+
if (observeTransport(extra) === "http") {
|
|
1831
|
+
return { sessionId: `sdk-${uuid7()}`, origin: "minted", perCall: true };
|
|
1832
|
+
}
|
|
1833
|
+
return { sessionId: fallbackSessionId, origin: "minted", perCall: false };
|
|
1297
1834
|
}
|
|
1298
1835
|
function sessionIdFromHeader(extra) {
|
|
1299
1836
|
try {
|
|
1300
|
-
const value = extraHeaders(extra)?.get("mcp-session-id")
|
|
1301
|
-
return value ? value : null;
|
|
1837
|
+
const value = extraHeaders(extra)?.get("mcp-session-id");
|
|
1838
|
+
return value ? stripWhiteSpace(value) || null : null;
|
|
1302
1839
|
} catch {
|
|
1303
1840
|
return null;
|
|
1304
1841
|
}
|
|
@@ -1307,7 +1844,7 @@ function sessionIdFromHeader(extra) {
|
|
|
1307
1844
|
// src/integrations/mcp/annotation.ts
|
|
1308
1845
|
var TOOL_NAME_PARAM_NAME = "tool_name";
|
|
1309
1846
|
function isReport(whatHappened) {
|
|
1310
|
-
return typeof whatHappened === "string" && whatHappened
|
|
1847
|
+
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
1311
1848
|
}
|
|
1312
1849
|
function registerAnnotationTool(server, options) {
|
|
1313
1850
|
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
@@ -1350,8 +1887,8 @@ function registerAnnotationTool(server, options) {
|
|
|
1350
1887
|
meta ? roundMetaCoordinates(meta) : null,
|
|
1351
1888
|
"_meta"
|
|
1352
1889
|
);
|
|
1353
|
-
const
|
|
1354
|
-
const
|
|
1890
|
+
const session = await resolveSessionId(options.fallbackSessionId, extra);
|
|
1891
|
+
const caller = await resolveCaller(
|
|
1355
1892
|
options.resolvePrincipal,
|
|
1356
1893
|
{ extra, toolName: name, arguments: args }
|
|
1357
1894
|
);
|
|
@@ -1360,13 +1897,14 @@ function registerAnnotationTool(server, options) {
|
|
|
1360
1897
|
() => AnnotationEventSchema.parse({
|
|
1361
1898
|
tenant_id: options.tenantId,
|
|
1362
1899
|
vendor_id: options.vendorId,
|
|
1363
|
-
session_id: sessionId,
|
|
1364
|
-
sequence_number: options.counter.
|
|
1900
|
+
session_id: session.sessionId,
|
|
1901
|
+
sequence_number: options.counter.nextFor(session),
|
|
1365
1902
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1366
1903
|
consent_token: options.consentToken,
|
|
1367
|
-
principal,
|
|
1904
|
+
principal: caller.principal,
|
|
1905
|
+
organization: caller.organization,
|
|
1368
1906
|
transport_observed: observeTransport(extra),
|
|
1369
|
-
session_id_origin: origin,
|
|
1907
|
+
session_id_origin: session.origin,
|
|
1370
1908
|
client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
|
|
1371
1909
|
runtime_meta: scrubbedMeta,
|
|
1372
1910
|
payload: {
|
|
@@ -1393,7 +1931,7 @@ function registerAnnotationTool(server, options) {
|
|
|
1393
1931
|
var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
|
|
1394
1932
|
var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
|
|
1395
1933
|
var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
|
|
1396
|
-
var NOT_IN_A_KEY = /[\x00\n\r]/;
|
|
1934
|
+
var NOT_IN_A_KEY = /[\x00\t\n\r]/;
|
|
1397
1935
|
var PUBLISHABLE_PREFIX = "baton_pk_";
|
|
1398
1936
|
var SECRET_PREFIX = "baton_sk_";
|
|
1399
1937
|
var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
|
|
@@ -1404,11 +1942,6 @@ function containsKey(value) {
|
|
|
1404
1942
|
return sweep(value) !== value;
|
|
1405
1943
|
}
|
|
1406
1944
|
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";
|
|
1407
|
-
function warn2(message) {
|
|
1408
|
-
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
1409
|
-
process.emitWarning(message);
|
|
1410
|
-
}
|
|
1411
|
-
}
|
|
1412
1945
|
function splitDsn(raw) {
|
|
1413
1946
|
const schemeEnd = raw.indexOf("://");
|
|
1414
1947
|
if (schemeEnd === -1) return null;
|
|
@@ -1468,7 +2001,7 @@ function selectDsn(explicit, supplied, door) {
|
|
|
1468
2001
|
const ambient = dsnFromEnvironment();
|
|
1469
2002
|
if (ambient === void 0) return void 0;
|
|
1470
2003
|
if (conflicts.length > 0) {
|
|
1471
|
-
|
|
2004
|
+
warn(
|
|
1472
2005
|
`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.`
|
|
1473
2006
|
);
|
|
1474
2007
|
return void 0;
|
|
@@ -1476,10 +2009,8 @@ function selectDsn(explicit, supplied, door) {
|
|
|
1476
2009
|
return ambient;
|
|
1477
2010
|
}
|
|
1478
2011
|
function parseDsn(raw) {
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
}
|
|
1482
|
-
const dsn = raw.trim();
|
|
2012
|
+
const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
|
|
2013
|
+
if (dsn === "") fail("dsn must be a non-empty string");
|
|
1483
2014
|
if (looksLikeAKey(dsn)) {
|
|
1484
2015
|
fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
|
|
1485
2016
|
}
|
|
@@ -1505,7 +2036,7 @@ function parseDsn(raw) {
|
|
|
1505
2036
|
}
|
|
1506
2037
|
if (NOT_IN_A_KEY.test(key)) {
|
|
1507
2038
|
fail(
|
|
1508
|
-
`dsn ${safe} has a line break or a null inside its key \u2014
|
|
2039
|
+
`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.`
|
|
1509
2040
|
);
|
|
1510
2041
|
}
|
|
1511
2042
|
if (key.includes(":")) {
|
|
@@ -1564,7 +2095,7 @@ function parseDsn(raw) {
|
|
|
1564
2095
|
);
|
|
1565
2096
|
}
|
|
1566
2097
|
if (key.startsWith(SECRET_PREFIX)) {
|
|
1567
|
-
|
|
2098
|
+
warn(
|
|
1568
2099
|
`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.`
|
|
1569
2100
|
);
|
|
1570
2101
|
}
|
|
@@ -1596,11 +2127,14 @@ function sealKey(dsn) {
|
|
|
1596
2127
|
// src/integrations/mcp/errorResult.ts
|
|
1597
2128
|
var TOOL_ERROR_TYPE = "tool_error";
|
|
1598
2129
|
var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
|
|
2130
|
+
var REFUSED = "refused";
|
|
1599
2131
|
var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
|
|
1600
|
-
function requestSideFailureKind(entry) {
|
|
2132
|
+
function requestSideFailureKind(entry, validation) {
|
|
1601
2133
|
if (entry == null) return "unknown_tool";
|
|
1602
2134
|
if (entry.enabled === false) return "tool_disabled";
|
|
1603
|
-
|
|
2135
|
+
if (validation === "rejected") return "invalid_argument";
|
|
2136
|
+
if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
|
|
2137
|
+
return REFUSED;
|
|
1604
2138
|
}
|
|
1605
2139
|
var ERROR_BODY_MAX_CODE_POINTS = 2e3;
|
|
1606
2140
|
function isErrorResult(value) {
|
|
@@ -1619,7 +2153,7 @@ function errorText(value) {
|
|
|
1619
2153
|
for (const part of content) {
|
|
1620
2154
|
const text = part?.text;
|
|
1621
2155
|
if (typeof text !== "string") continue;
|
|
1622
|
-
const trimmed = text
|
|
2156
|
+
const trimmed = stripWhiteSpace(text);
|
|
1623
2157
|
if (trimmed) parts.push(trimmed);
|
|
1624
2158
|
}
|
|
1625
2159
|
} catch {
|
|
@@ -1651,6 +2185,9 @@ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
|
|
|
1651
2185
|
function requestSideErrorFields(text, errorBody2) {
|
|
1652
2186
|
return { error_body: errorBody2(text), result: null };
|
|
1653
2187
|
}
|
|
2188
|
+
function requestSideFailureFields(kind, mode, text, result, errorBody2, scrubber) {
|
|
2189
|
+
return kind === REFUSED ? resultDerivedFields(mode, text, result ?? null, errorBody2, scrubber) : requestSideErrorFields(text(), errorBody2);
|
|
2190
|
+
}
|
|
1654
2191
|
function errorTypeOf(err) {
|
|
1655
2192
|
return err instanceof Error ? err.constructor.name : "Error";
|
|
1656
2193
|
}
|
|
@@ -1796,7 +2333,7 @@ var SWITCH = "BATON_DISABLED";
|
|
|
1796
2333
|
var OFF_VALUES = /* @__PURE__ */ new Set(["", "0", "false", "no", "off"]);
|
|
1797
2334
|
function captureDisabled() {
|
|
1798
2335
|
const value = typeof process !== "undefined" ? process.env?.[SWITCH] : void 0;
|
|
1799
|
-
if (value !== void 0 && !OFF_VALUES.has(value
|
|
2336
|
+
if (value !== void 0 && !OFF_VALUES.has(stripWhiteSpace(value).toLowerCase())) {
|
|
1800
2337
|
return SWITCH;
|
|
1801
2338
|
}
|
|
1802
2339
|
return null;
|
|
@@ -1827,9 +2364,9 @@ var DisabledSink = class {
|
|
|
1827
2364
|
var BatonHandle = class {
|
|
1828
2365
|
sink;
|
|
1829
2366
|
vendorId;
|
|
1830
|
-
/**
|
|
1831
|
-
* when no
|
|
1832
|
-
*
|
|
2367
|
+
/** The install's own session id: what stdio and in-memory calls, and the
|
|
2368
|
+
* surface snapshot, carry when no session id resolves. A call over HTTP
|
|
2369
|
+
* with no session to read gets a per-request id instead (SPEC §3.4 rung 5). */
|
|
1833
2370
|
sessionId;
|
|
1834
2371
|
/** The resolved annotation tool name: `BatonConfig.annotationToolName` if
|
|
1835
2372
|
* set, else derived from the server's own name (`{slug}_annotate`), else
|
|
@@ -1841,19 +2378,25 @@ var BatonHandle = class {
|
|
|
1841
2378
|
this.sessionId = options.sessionId;
|
|
1842
2379
|
this.annotationToolName = options.annotationToolName;
|
|
1843
2380
|
}
|
|
1844
|
-
/** Flush any pending events held by the sink.
|
|
2381
|
+
/** Flush any pending events held by the sink. Never rejects; returns within
|
|
2382
|
+
* the shutdown budget (SPEC §11.2 rule 7). */
|
|
1845
2383
|
async flush() {
|
|
1846
|
-
await this.sink
|
|
2384
|
+
await boundedSinkCall(this.sink, "flush");
|
|
1847
2385
|
}
|
|
1848
|
-
/** Flush and release sink resources
|
|
2386
|
+
/** Flush and release sink resources, on the same terms as `flush()`. */
|
|
1849
2387
|
async aclose() {
|
|
1850
|
-
await this.sink
|
|
2388
|
+
await boundedSinkCall(this.sink, "aclose");
|
|
1851
2389
|
}
|
|
1852
2390
|
};
|
|
1853
2391
|
|
|
1854
2392
|
// src/integrations/mcp/sessionCounter.ts
|
|
1855
2393
|
var SessionCounter = class {
|
|
1856
2394
|
counters = /* @__PURE__ */ new Map();
|
|
2395
|
+
/** A per-call session is numbered by the clock: a counter would keep an
|
|
2396
|
+
* entry for every request the process serves. */
|
|
2397
|
+
nextFor(session) {
|
|
2398
|
+
return session.perCall ? nextClockSequence() : this.next(session.sessionId);
|
|
2399
|
+
}
|
|
1857
2400
|
next(sessionId) {
|
|
1858
2401
|
const current2 = this.counters.get(sessionId) ?? 0;
|
|
1859
2402
|
const next = current2 + 1;
|
|
@@ -1940,6 +2483,7 @@ function toJsonSchemaCompat(schema, opts) {
|
|
|
1940
2483
|
// src/integrations/mcp/schemaCompat.ts
|
|
1941
2484
|
var import_zod3 = require("zod");
|
|
1942
2485
|
var import_v3 = require("zod/v3");
|
|
2486
|
+
var DEFAULT_INTENT_PARAM_MODE = "required";
|
|
1943
2487
|
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
1944
2488
|
function injectGoalParams(inputSchema, intentParamMode) {
|
|
1945
2489
|
const objSchema = normalizeObjectSchema(inputSchema);
|
|
@@ -2018,9 +2562,9 @@ function surfaceHash(surface) {
|
|
|
2018
2562
|
}
|
|
2019
2563
|
function canonicalJson(value) {
|
|
2020
2564
|
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
2021
|
-
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
2565
|
+
if (Array.isArray(value)) return `[${value.map((v) => v === void 0 ? "null" : canonicalJson(v)).join(",")}]`;
|
|
2022
2566
|
const record = value;
|
|
2023
|
-
const keys = Object.keys(record).sort();
|
|
2567
|
+
const keys = Object.keys(record).filter((k) => record[k] !== void 0).sort();
|
|
2024
2568
|
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(record[k])}`).join(",")}}`;
|
|
2025
2569
|
}
|
|
2026
2570
|
function buildServerMeta(lowlevelServer) {
|
|
@@ -2042,6 +2586,25 @@ function assembleSurface(serverMeta, tools) {
|
|
|
2042
2586
|
tools
|
|
2043
2587
|
};
|
|
2044
2588
|
}
|
|
2589
|
+
var SENT_SURFACES_CAP = 256;
|
|
2590
|
+
var SentSurfaces = class {
|
|
2591
|
+
hashes = /* @__PURE__ */ new Set();
|
|
2592
|
+
wasSent(digest) {
|
|
2593
|
+
if (!this.hashes.has(digest)) return false;
|
|
2594
|
+
this.hashes.delete(digest);
|
|
2595
|
+
this.hashes.add(digest);
|
|
2596
|
+
return true;
|
|
2597
|
+
}
|
|
2598
|
+
mark(digest) {
|
|
2599
|
+
this.hashes.add(digest);
|
|
2600
|
+
if (this.hashes.size > SENT_SURFACES_CAP) {
|
|
2601
|
+
this.hashes.delete(this.hashes.values().next().value);
|
|
2602
|
+
}
|
|
2603
|
+
}
|
|
2604
|
+
unmark(digest) {
|
|
2605
|
+
this.hashes.delete(digest);
|
|
2606
|
+
}
|
|
2607
|
+
};
|
|
2045
2608
|
function buildSeamAugmentations(options) {
|
|
2046
2609
|
return {
|
|
2047
2610
|
injected_tools: [...options.injectedToolNames].sort(),
|
|
@@ -2060,12 +2623,12 @@ var wired = /* @__PURE__ */ new WeakSet();
|
|
|
2060
2623
|
var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
|
|
2061
2624
|
var callSlots = new import_node_async_hooks.AsyncLocalStorage();
|
|
2062
2625
|
var SurfaceState = class {
|
|
2063
|
-
constructor(serverMeta,
|
|
2626
|
+
constructor(serverMeta, sentSurfaces) {
|
|
2064
2627
|
this.serverMeta = serverMeta;
|
|
2065
|
-
this.
|
|
2628
|
+
this.sentSurfaces = sentSurfaces;
|
|
2066
2629
|
}
|
|
2067
2630
|
serverMeta;
|
|
2068
|
-
|
|
2631
|
+
sentSurfaces;
|
|
2069
2632
|
/** Every tool this install has seen, keyed by its CURRENT name. `disabled`
|
|
2070
2633
|
* is tracked alongside rather than pruned, so re-enabling costs nothing and
|
|
2071
2634
|
* — crucially — never needs a re-capture, which would re-read Baton's own
|
|
@@ -2122,29 +2685,30 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
2122
2685
|
}
|
|
2123
2686
|
async function openCall(ctx, toolName, extra, params, retired, registered = true) {
|
|
2124
2687
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
2125
|
-
const {
|
|
2688
|
+
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
2126
2689
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
2127
2690
|
const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
|
|
2128
2691
|
const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
|
|
2129
2692
|
const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
|
|
2130
2693
|
(name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, retired[name] ?? popText(params, name), name)
|
|
2131
2694
|
);
|
|
2132
|
-
const
|
|
2695
|
+
const caller = await resolveCaller(
|
|
2133
2696
|
ctx.resolvePrincipal,
|
|
2134
2697
|
{ extra, toolName, arguments: params }
|
|
2135
2698
|
);
|
|
2136
2699
|
const common = {
|
|
2137
2700
|
tenant_id: ctx.tenantId,
|
|
2138
2701
|
vendor_id: ctx.vendorId,
|
|
2139
|
-
session_id: sessionId,
|
|
2702
|
+
session_id: session.sessionId,
|
|
2140
2703
|
consent_token: ctx.consentToken,
|
|
2141
2704
|
// Every `...common` site is an event of this call, so `call_id` rides in
|
|
2142
2705
|
// it. `surface_snapshot` is deliberately not among them: it describes the
|
|
2143
2706
|
// SERVER and is captured outside any call, so it has no caller, transport
|
|
2144
2707
|
// or client to name.
|
|
2145
|
-
principal,
|
|
2708
|
+
principal: caller.principal,
|
|
2709
|
+
organization: caller.organization,
|
|
2146
2710
|
transport_observed: observeTransport(extra),
|
|
2147
|
-
session_id_origin: origin,
|
|
2711
|
+
session_id_origin: session.origin,
|
|
2148
2712
|
client_observed: observeClient(extra, ctx),
|
|
2149
2713
|
runtime_meta: scrubbedMeta,
|
|
2150
2714
|
call_id: uuid7()
|
|
@@ -2153,7 +2717,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2153
2717
|
ctx.sink,
|
|
2154
2718
|
() => ToolCallStartEventSchema.parse({
|
|
2155
2719
|
...common,
|
|
2156
|
-
sequence_number: ctx.counter.
|
|
2720
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2157
2721
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2158
2722
|
payload: {
|
|
2159
2723
|
tool_name: toolName,
|
|
@@ -2166,7 +2730,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2166
2730
|
}
|
|
2167
2731
|
})
|
|
2168
2732
|
);
|
|
2169
|
-
return { common,
|
|
2733
|
+
return { common, session };
|
|
2170
2734
|
}
|
|
2171
2735
|
function batonWrap(nameRef, original, ctx) {
|
|
2172
2736
|
return async (...callArgs) => {
|
|
@@ -2177,7 +2741,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2177
2741
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
2178
2742
|
const retired = slot?.retired ?? {};
|
|
2179
2743
|
if (slot) slot.retired = {};
|
|
2180
|
-
const { common,
|
|
2744
|
+
const { common, session } = await openCall(ctx, toolName, extra, params, retired);
|
|
2181
2745
|
const terminate = async (build, replacement) => {
|
|
2182
2746
|
if (!slot) {
|
|
2183
2747
|
await emit(ctx.sink, build);
|
|
@@ -2203,18 +2767,20 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2203
2767
|
await parkFailure(
|
|
2204
2768
|
() => ToolCallErrorEventSchema.parse({
|
|
2205
2769
|
...common,
|
|
2206
|
-
sequence_number: ctx.counter.
|
|
2770
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2207
2771
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2208
2772
|
payload: {
|
|
2209
2773
|
tool_name: toolName,
|
|
2210
2774
|
error_type: errorTypeOf(err),
|
|
2211
|
-
//
|
|
2212
|
-
//
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2775
|
+
// SPEC §11.4.3(1): the MCP SDK has no tool-error class to mark a
|
|
2776
|
+
// raised message public, so under "off" every one is withheld.
|
|
2777
|
+
...resultDerivedFields(
|
|
2778
|
+
ctx.resultCaptureMode,
|
|
2779
|
+
() => messageOf(err),
|
|
2780
|
+
null,
|
|
2781
|
+
(text) => errorBody(ctx, text),
|
|
2782
|
+
ctx.scrubber
|
|
2783
|
+
),
|
|
2218
2784
|
duration_ms: durationMs2,
|
|
2219
2785
|
// Explicit, though the field is `.optional()` and this is its
|
|
2220
2786
|
// absent value. The schema is deliberately not an emitter (see
|
|
@@ -2238,7 +2804,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2238
2804
|
await parkFailure(
|
|
2239
2805
|
() => ToolCallErrorEventSchema.parse({
|
|
2240
2806
|
...common,
|
|
2241
|
-
sequence_number: ctx.counter.
|
|
2807
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2242
2808
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2243
2809
|
payload: {
|
|
2244
2810
|
tool_name: toolName,
|
|
@@ -2268,7 +2834,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2268
2834
|
await parkSuccess(
|
|
2269
2835
|
() => ToolCallEndEventSchema.parse({
|
|
2270
2836
|
...common,
|
|
2271
|
-
sequence_number: ctx.counter.
|
|
2837
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2272
2838
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2273
2839
|
payload: {
|
|
2274
2840
|
tool_name: toolName,
|
|
@@ -2284,7 +2850,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2284
2850
|
// CALLER saw fail, which is a success the product invented.
|
|
2285
2851
|
(outcome) => ToolCallErrorEventSchema.parse({
|
|
2286
2852
|
...common,
|
|
2287
|
-
sequence_number: ctx.counter.
|
|
2853
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2288
2854
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2289
2855
|
payload: {
|
|
2290
2856
|
tool_name: toolName,
|
|
@@ -2351,7 +2917,7 @@ function popText(args, paramName) {
|
|
|
2351
2917
|
if (!(paramName in args)) return null;
|
|
2352
2918
|
const raw = args[paramName];
|
|
2353
2919
|
delete args[paramName];
|
|
2354
|
-
return typeof raw === "string" && raw
|
|
2920
|
+
return typeof raw === "string" && !isBlank(raw) ? raw : null;
|
|
2355
2921
|
}
|
|
2356
2922
|
function stripRetiredParams(params, ctx) {
|
|
2357
2923
|
const toolName = params?.name;
|
|
@@ -2367,7 +2933,6 @@ function stripRetiredParams(params, ctx) {
|
|
|
2367
2933
|
}
|
|
2368
2934
|
return retired;
|
|
2369
2935
|
}
|
|
2370
|
-
var MAX_REMEMBERED_SURFACES = 1024;
|
|
2371
2936
|
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
2372
2937
|
if (!ctx.surfaceState.dirty) return;
|
|
2373
2938
|
ctx.surfaceState.dirty = false;
|
|
@@ -2381,10 +2946,9 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2381
2946
|
`);
|
|
2382
2947
|
return;
|
|
2383
2948
|
}
|
|
2384
|
-
const
|
|
2385
|
-
if (
|
|
2386
|
-
|
|
2387
|
-
emitted.add(digest);
|
|
2949
|
+
const sent = ctx.surfaceState.sentSurfaces;
|
|
2950
|
+
if (sent.wasSent(digest)) return;
|
|
2951
|
+
sent.mark(digest);
|
|
2388
2952
|
const seam = buildSeamAugmentations({
|
|
2389
2953
|
injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
|
|
2390
2954
|
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
@@ -2397,7 +2961,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2397
2961
|
} catch (err) {
|
|
2398
2962
|
process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
|
|
2399
2963
|
`);
|
|
2400
|
-
|
|
2964
|
+
sent.unmark(digest);
|
|
2401
2965
|
ctx.surfaceState.dirty = true;
|
|
2402
2966
|
}
|
|
2403
2967
|
}
|
|
@@ -2492,7 +3056,7 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2492
3056
|
ctx.sink,
|
|
2493
3057
|
() => schema.parse({
|
|
2494
3058
|
...opened.common,
|
|
2495
|
-
sequence_number: ctx.counter.
|
|
3059
|
+
sequence_number: ctx.counter.nextFor(opened.session),
|
|
2496
3060
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2497
3061
|
payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload })
|
|
2498
3062
|
})
|
|
@@ -2524,25 +3088,26 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2524
3088
|
}
|
|
2525
3089
|
async function openLifecycleCall(ctx, spec, requestParams, extra) {
|
|
2526
3090
|
try {
|
|
2527
|
-
const
|
|
2528
|
-
const
|
|
3091
|
+
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
3092
|
+
const caller = await resolveCaller(ctx.resolvePrincipal, {
|
|
2529
3093
|
extra,
|
|
2530
3094
|
toolName: null,
|
|
2531
3095
|
arguments: {}
|
|
2532
3096
|
});
|
|
2533
3097
|
return {
|
|
2534
|
-
|
|
3098
|
+
session,
|
|
2535
3099
|
subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
|
|
2536
3100
|
common: {
|
|
2537
3101
|
tenant_id: ctx.tenantId,
|
|
2538
3102
|
vendor_id: ctx.vendorId,
|
|
2539
|
-
session_id:
|
|
3103
|
+
session_id: session.sessionId,
|
|
2540
3104
|
consent_token: ctx.consentToken,
|
|
2541
|
-
principal,
|
|
3105
|
+
principal: caller.principal,
|
|
3106
|
+
organization: caller.organization,
|
|
2542
3107
|
transport_observed: observeTransport(extra),
|
|
2543
|
-
session_id_origin:
|
|
3108
|
+
session_id_origin: session.origin,
|
|
2544
3109
|
client_observed: observeClient(extra, ctx),
|
|
2545
|
-
runtime_meta:
|
|
3110
|
+
runtime_meta: scrubbedMeta
|
|
2546
3111
|
}
|
|
2547
3112
|
};
|
|
2548
3113
|
} catch (err) {
|
|
@@ -2670,7 +3235,8 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
2670
3235
|
const slot = {
|
|
2671
3236
|
innerFired: false,
|
|
2672
3237
|
flushTerminal: null,
|
|
2673
|
-
retired: stripRetiredParams(request?.params, ctx)
|
|
3238
|
+
retired: stripRetiredParams(request?.params, ctx),
|
|
3239
|
+
validation: "unseen"
|
|
2674
3240
|
};
|
|
2675
3241
|
let outcome = CLEAN_OUTCOME;
|
|
2676
3242
|
try {
|
|
@@ -2686,6 +3252,25 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
2686
3252
|
}
|
|
2687
3253
|
);
|
|
2688
3254
|
}
|
|
3255
|
+
var VALIDATION_PROBE = /* @__PURE__ */ Symbol("baton.validationProbe");
|
|
3256
|
+
function installValidationProbe(server) {
|
|
3257
|
+
const target = server;
|
|
3258
|
+
const original = target.validateToolInput;
|
|
3259
|
+
if (typeof original !== "function" || original[VALIDATION_PROBE]) return;
|
|
3260
|
+
const probe = async function(...args) {
|
|
3261
|
+
const slot = callSlots.getStore();
|
|
3262
|
+
try {
|
|
3263
|
+
const parsed = await original.apply(this, args);
|
|
3264
|
+
if (slot) slot.validation = "passed";
|
|
3265
|
+
return parsed;
|
|
3266
|
+
} catch (err) {
|
|
3267
|
+
if (slot) slot.validation = "rejected";
|
|
3268
|
+
throw err;
|
|
3269
|
+
}
|
|
3270
|
+
};
|
|
3271
|
+
Object.assign(probe, { [VALIDATION_PROBE]: true });
|
|
3272
|
+
target.validateToolInput = probe;
|
|
3273
|
+
}
|
|
2689
3274
|
async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
2690
3275
|
try {
|
|
2691
3276
|
if (slot.flushTerminal !== null) {
|
|
@@ -2696,13 +3281,14 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
|
2696
3281
|
}
|
|
2697
3282
|
if (slot.innerFired) return;
|
|
2698
3283
|
if (!outcome.failed) return;
|
|
2699
|
-
await emitRequestSideFailure(outcome, args, slot
|
|
3284
|
+
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
|
|
2700
3285
|
} catch (err) {
|
|
3286
|
+
PROCESS_DROPS.add("encode_failed");
|
|
2701
3287
|
process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
|
|
2702
3288
|
`);
|
|
2703
3289
|
}
|
|
2704
3290
|
}
|
|
2705
|
-
async function emitRequestSideFailure(outcome, args,
|
|
3291
|
+
async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
2706
3292
|
const request = args[0];
|
|
2707
3293
|
const toolName = request?.params?.name;
|
|
2708
3294
|
if (typeof toolName !== "string") return;
|
|
@@ -2710,13 +3296,21 @@ async function emitRequestSideFailure(outcome, args, retired, toolEntry, ctx) {
|
|
|
2710
3296
|
const entry = toolEntry(toolName);
|
|
2711
3297
|
if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
|
|
2712
3298
|
const params = { ...request?.params?.arguments ?? {} };
|
|
2713
|
-
const { common,
|
|
2714
|
-
|
|
3299
|
+
const { common, session } = await openCall(
|
|
3300
|
+
ctx,
|
|
3301
|
+
toolName,
|
|
3302
|
+
args[1],
|
|
3303
|
+
params,
|
|
3304
|
+
slot.retired,
|
|
3305
|
+
entry != null
|
|
3306
|
+
);
|
|
3307
|
+
const failureKind = requestSideFailureKind(entry, slot.validation);
|
|
3308
|
+
const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
|
|
2715
3309
|
await emit(
|
|
2716
3310
|
ctx.sink,
|
|
2717
3311
|
() => ToolCallErrorEventSchema.parse({
|
|
2718
3312
|
...common,
|
|
2719
|
-
sequence_number: ctx.counter.
|
|
3313
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2720
3314
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2721
3315
|
payload: {
|
|
2722
3316
|
tool_name: toolName,
|
|
@@ -2732,8 +3326,8 @@ async function emitRequestSideFailure(outcome, args, retired, toolEntry, ctx) {
|
|
|
2732
3326
|
error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
|
|
2733
3327
|
// ⚠ `null`, not 0. The vendor's handler never ran, so there is no
|
|
2734
3328
|
// handler duration to report; the time this call did spend was spent
|
|
2735
|
-
//
|
|
2736
|
-
//
|
|
3329
|
+
// above the handler, which is not what any other event means by this
|
|
3330
|
+
// member. §11.4 types it nullable for cases like this one.
|
|
2737
3331
|
duration_ms: null,
|
|
2738
3332
|
// ⚠ A CONDITIONAL SPREAD, not `failure_kind: failureKind`. Zod's
|
|
2739
3333
|
// `.optional()` accepts `undefined` and keeps the KEY in its output,
|
|
@@ -2743,11 +3337,13 @@ async function emitRequestSideFailure(outcome, args, retired, toolEntry, ctx) {
|
|
|
2743
3337
|
// determine the kind MUST OMIT the member, and omitting is what this
|
|
2744
3338
|
// spells.
|
|
2745
3339
|
...failureKind === void 0 ? {} : { failure_kind: failureKind },
|
|
2746
|
-
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
3340
|
+
...requestSideFailureFields(
|
|
3341
|
+
failureKind,
|
|
3342
|
+
ctx.resultCaptureMode,
|
|
3343
|
+
text,
|
|
3344
|
+
outcome.raised ? null : outcome.result,
|
|
3345
|
+
(value) => errorBody(ctx, value),
|
|
3346
|
+
ctx.scrubber
|
|
2751
3347
|
)
|
|
2752
3348
|
}
|
|
2753
3349
|
})
|
|
@@ -2830,15 +3426,19 @@ function withBaton(server, supplied = {}) {
|
|
|
2830
3426
|
}
|
|
2831
3427
|
const resolved = resolveBatonConfig(supplied);
|
|
2832
3428
|
warnUnusedReportSettings(resolved);
|
|
2833
|
-
return install(server, supplied, resolved,
|
|
3429
|
+
return install(server, supplied, resolved, new SentSurfaces(), /* @__PURE__ */ new Set());
|
|
2834
3430
|
}
|
|
2835
3431
|
function createBaton(supplied = {}) {
|
|
2836
3432
|
const disabledBy = captureDisabled();
|
|
2837
3433
|
if (disabledBy !== null) {
|
|
2838
3434
|
logDisabled(disabledBy, "createBaton");
|
|
2839
3435
|
const unused = supplied.sink ?? new DisabledSink();
|
|
2840
|
-
return {
|
|
2841
|
-
|
|
3436
|
+
return {
|
|
3437
|
+
wrap: () => {
|
|
3438
|
+
},
|
|
3439
|
+
flush: () => boundedSinkCall(unused, "flush"),
|
|
3440
|
+
aclose: () => boundedSinkCall(unused, "aclose")
|
|
3441
|
+
};
|
|
2842
3442
|
}
|
|
2843
3443
|
const resolved = resolveBatonConfig(supplied);
|
|
2844
3444
|
warnUnusedReportSettings(resolved);
|
|
@@ -2849,17 +3449,17 @@ function createBaton(supplied = {}) {
|
|
|
2849
3449
|
sink,
|
|
2850
3450
|
tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
|
|
2851
3451
|
};
|
|
2852
|
-
const
|
|
2853
|
-
const
|
|
3452
|
+
const sentSurfaces = new SentSurfaces();
|
|
3453
|
+
const warned3 = /* @__PURE__ */ new Set();
|
|
2854
3454
|
return {
|
|
2855
3455
|
wrap: (server) => {
|
|
2856
|
-
install(server, supplied, config,
|
|
3456
|
+
install(server, supplied, config, sentSurfaces, warned3);
|
|
2857
3457
|
},
|
|
2858
|
-
flush: () => sink
|
|
2859
|
-
aclose: () => sink
|
|
3458
|
+
flush: () => boundedSinkCall(sink, "flush"),
|
|
3459
|
+
aclose: () => boundedSinkCall(sink, "aclose")
|
|
2860
3460
|
};
|
|
2861
3461
|
}
|
|
2862
|
-
function install(server, supplied, resolved,
|
|
3462
|
+
function install(server, supplied, resolved, sentSurfaces, warned3) {
|
|
2863
3463
|
const internals = server;
|
|
2864
3464
|
const serverName = usableServerName(() => ({
|
|
2865
3465
|
name: internals.server._serverInfo?.name,
|
|
@@ -2869,13 +3469,13 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
|
|
|
2869
3469
|
const sink = config.sink ?? new StdoutSink();
|
|
2870
3470
|
const reports = reportsFor(config);
|
|
2871
3471
|
const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
|
|
2872
|
-
const intentParamMode = config.intentParamMode ??
|
|
3472
|
+
const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
|
|
2873
3473
|
const counter2 = new SessionCounter();
|
|
2874
3474
|
const fallbackSessionId = `sdk-${uuid7()}`;
|
|
2875
3475
|
const tenantId = resolveTenantId(config.tenantId, config.vendorId);
|
|
2876
3476
|
const scrubber = config.scrubber ?? new Scrubber().scrub;
|
|
2877
3477
|
const serverMeta = buildServerMeta(server.server);
|
|
2878
|
-
const surfaceState = new SurfaceState(serverMeta,
|
|
3478
|
+
const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
|
|
2879
3479
|
const emitSurface = async (sessionId, digest, snapshot) => {
|
|
2880
3480
|
const event = SurfaceSnapshotEventSchema.parse({
|
|
2881
3481
|
tenant_id: tenantId,
|
|
@@ -2900,9 +3500,9 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
|
|
|
2900
3500
|
const memo = internals._toolInputSchemaJson;
|
|
2901
3501
|
if (memo && typeof memo === "object") delete memo[name];
|
|
2902
3502
|
};
|
|
2903
|
-
const
|
|
2904
|
-
if (
|
|
2905
|
-
|
|
3503
|
+
const warnOnce2 = (key, message) => {
|
|
3504
|
+
if (warned3.has(key)) return;
|
|
3505
|
+
warned3.add(key);
|
|
2906
3506
|
process.stderr.write(message);
|
|
2907
3507
|
};
|
|
2908
3508
|
const dropSubagentClause = (name) => {
|
|
@@ -2914,7 +3514,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
|
|
|
2914
3514
|
} else {
|
|
2915
3515
|
return;
|
|
2916
3516
|
}
|
|
2917
|
-
|
|
3517
|
+
warnOnce2(
|
|
2918
3518
|
"native-user-goal",
|
|
2919
3519
|
`baton: tool ${JSON.stringify(name)} declares its own user_goal, so the subagent sentence was removed from the server instructions; a session that already started keeps it
|
|
2920
3520
|
`
|
|
@@ -2941,6 +3541,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
|
|
|
2941
3541
|
return { type: "object", properties: {} };
|
|
2942
3542
|
}
|
|
2943
3543
|
};
|
|
3544
|
+
installValidationProbe(server);
|
|
2944
3545
|
const ctx = {
|
|
2945
3546
|
sink,
|
|
2946
3547
|
counter: counter2,
|
|
@@ -2966,7 +3567,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
|
|
|
2966
3567
|
internals.server._instructions = withVendorInstructions(
|
|
2967
3568
|
internals.server,
|
|
2968
3569
|
ours,
|
|
2969
|
-
(message) =>
|
|
3570
|
+
(message) => warnOnce2("instructions-length", message)
|
|
2970
3571
|
);
|
|
2971
3572
|
installToolsListSeam(internals.server, ctx);
|
|
2972
3573
|
installToolsCallSeam(
|
|
@@ -3043,7 +3644,7 @@ function claimsOf(context) {
|
|
|
3043
3644
|
}
|
|
3044
3645
|
function stringClaim(claims, name) {
|
|
3045
3646
|
const value = claims[name];
|
|
3046
|
-
return typeof value === "string" &&
|
|
3647
|
+
return typeof value === "string" && !isBlank(value) ? value : null;
|
|
3047
3648
|
}
|
|
3048
3649
|
function principalFromOAuthSub(context) {
|
|
3049
3650
|
const claims = claimsOf(context);
|
|
@@ -3073,46 +3674,48 @@ function sessionEnvelope(session) {
|
|
|
3073
3674
|
session_id_origin: session.origin,
|
|
3074
3675
|
transport_observed: TRANSPORT_LIBRARY,
|
|
3075
3676
|
principal: session.principal,
|
|
3677
|
+
organization: session.organization,
|
|
3076
3678
|
client_observed: session.clientObserved,
|
|
3077
|
-
runtime_meta: session.
|
|
3679
|
+
runtime_meta: session.runtimeMeta
|
|
3078
3680
|
};
|
|
3079
3681
|
}
|
|
3080
|
-
function
|
|
3682
|
+
function warn2(message) {
|
|
3081
3683
|
process.stderr.write(`baton: ${message}
|
|
3082
3684
|
`);
|
|
3083
3685
|
}
|
|
3084
3686
|
function vendorId(name, value) {
|
|
3085
|
-
const cleaned = typeof value === "string" ?
|
|
3687
|
+
const cleaned = typeof value === "string" ? stripWhiteSpace(value) : "";
|
|
3086
3688
|
if (cleaned !== "") return cleaned;
|
|
3087
3689
|
if (value !== void 0 && value !== null) {
|
|
3088
|
-
|
|
3690
|
+
warn2(`${name} is not a non-blank string \u2014 ignoring it.`);
|
|
3089
3691
|
}
|
|
3090
3692
|
return null;
|
|
3091
3693
|
}
|
|
3092
|
-
function
|
|
3093
|
-
return { sessionId
|
|
3694
|
+
function blank(sessionId, origin) {
|
|
3695
|
+
return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
|
|
3094
3696
|
}
|
|
3095
|
-
function
|
|
3096
|
-
if (
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
}
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
);
|
|
3697
|
+
function requestMeta(meta) {
|
|
3698
|
+
if (isRecord(meta)) return meta;
|
|
3699
|
+
if (meta !== void 0 && meta !== null) warn2("meta is not an object \u2014 ignoring it.");
|
|
3700
|
+
return null;
|
|
3701
|
+
}
|
|
3702
|
+
function runtimeMeta(meta, turnId, scrubber) {
|
|
3703
|
+
const clientKeys = Object.fromEntries(Object.entries(meta ?? {}).filter(([key]) => key !== TURN_ID_META_KEY));
|
|
3704
|
+
const cleaned = Object.keys(clientKeys).length > 0 ? scrubOrNull(scrubber, roundMetaCoordinates(clientKeys), "_meta") : null;
|
|
3705
|
+
const out = isRecord(cleaned) ? { ...cleaned } : {};
|
|
3706
|
+
if (turnId !== null) out[TURN_ID_META_KEY] = turnId;
|
|
3707
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
3106
3708
|
}
|
|
3107
3709
|
function newSession(values, scrubber, disabled) {
|
|
3108
3710
|
const id = vendorId("sessionId", values.sessionId);
|
|
3109
|
-
const base = id !== null ?
|
|
3711
|
+
const base = id !== null ? blank(id, "observed") : blank(uuid7(), "minted");
|
|
3110
3712
|
if (disabled) return base;
|
|
3713
|
+
const meta = requestMeta(values.meta);
|
|
3111
3714
|
return {
|
|
3112
3715
|
...base,
|
|
3113
|
-
|
|
3114
|
-
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber),
|
|
3115
|
-
|
|
3716
|
+
...callerFor(values.principal, (_key, message) => warn2(`principal ${message}`)),
|
|
3717
|
+
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),
|
|
3718
|
+
runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
|
|
3116
3719
|
};
|
|
3117
3720
|
}
|
|
3118
3721
|
var current = new import_node_async_hooks2.AsyncLocalStorage();
|
|
@@ -3121,13 +3724,73 @@ function runInSession(owner, session, fn) {
|
|
|
3121
3724
|
}
|
|
3122
3725
|
function sessionForCall(owner) {
|
|
3123
3726
|
const entry = current.getStore();
|
|
3124
|
-
return entry !== void 0 && entry.owner === owner ? entry.session :
|
|
3727
|
+
return entry !== void 0 && entry.owner === owner ? entry.session : blank(uuid7(), "minted");
|
|
3125
3728
|
}
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
|
|
3729
|
+
|
|
3730
|
+
// src/library/surface.ts
|
|
3731
|
+
function serveTools(tools, options) {
|
|
3732
|
+
let served;
|
|
3733
|
+
try {
|
|
3734
|
+
served = tools.map(servedEntry);
|
|
3735
|
+
} catch (err) {
|
|
3736
|
+
process.stderr.write(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}
|
|
3737
|
+
`);
|
|
3738
|
+
return { served: tools, surface: null };
|
|
3739
|
+
}
|
|
3740
|
+
try {
|
|
3741
|
+
const nameOf = (tool) => isRecord(tool) ? String(tool.name) : "";
|
|
3742
|
+
const ordered = [...tools].sort((a, b) => {
|
|
3743
|
+
const [x, y] = [nameOf(a), nameOf(b)];
|
|
3744
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
3745
|
+
});
|
|
3746
|
+
const meta = {
|
|
3747
|
+
server_info: options.serverInfo ?? null,
|
|
3748
|
+
capabilities: options.capabilities ?? null,
|
|
3749
|
+
instructions: options.instructions ?? null
|
|
3750
|
+
};
|
|
3751
|
+
const surface = JSON.parse(
|
|
3752
|
+
JSON.stringify(assembleSurface(meta, ordered))
|
|
3753
|
+
);
|
|
3754
|
+
return { served, surface: { surface, digest: surfaceHash(surface) } };
|
|
3755
|
+
} catch (err) {
|
|
3756
|
+
process.stderr.write(`baton: surface snapshot capture failed: ${printable(err)}
|
|
3757
|
+
`);
|
|
3758
|
+
return { served, surface: null };
|
|
3759
|
+
}
|
|
3760
|
+
}
|
|
3761
|
+
function snapshotPayload({ surface, digest }) {
|
|
3762
|
+
return {
|
|
3763
|
+
surface_hash: digest,
|
|
3764
|
+
...surface,
|
|
3765
|
+
seam_augmentations: buildSeamAugmentations({
|
|
3766
|
+
injectedToolNames: [],
|
|
3767
|
+
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
3768
|
+
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
3769
|
+
requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
|
|
3770
|
+
instructionsSuffix: null
|
|
3771
|
+
})
|
|
3772
|
+
};
|
|
3773
|
+
}
|
|
3774
|
+
function servedEntry(tool) {
|
|
3775
|
+
if (!isRecord(tool)) return tool;
|
|
3776
|
+
const entry = { ...tool };
|
|
3777
|
+
if (isRecord(entry.inputSchema)) {
|
|
3778
|
+
const schema = { ...entry.inputSchema };
|
|
3779
|
+
if (isRecord(schema.properties)) schema.properties = { ...schema.properties };
|
|
3780
|
+
injectGoalParam(schema);
|
|
3781
|
+
entry.inputSchema = schema;
|
|
3782
|
+
}
|
|
3783
|
+
return entry;
|
|
3784
|
+
}
|
|
3785
|
+
function injectGoalParam(schema) {
|
|
3786
|
+
if (schema.properties === void 0) schema.properties = {};
|
|
3787
|
+
if (!isRecord(schema.properties) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return;
|
|
3788
|
+
schema.properties[USER_GOAL_PARAM_NAME] = {
|
|
3789
|
+
type: "string",
|
|
3790
|
+
description: buildUserGoalParamDescription({ intentParamMode: DEFAULT_INTENT_PARAM_MODE })
|
|
3791
|
+
};
|
|
3792
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
3793
|
+
if (!required.includes(USER_GOAL_PARAM_NAME)) schema.required = [...required, USER_GOAL_PARAM_NAME];
|
|
3131
3794
|
}
|
|
3132
3795
|
|
|
3133
3796
|
// src/library/client.ts
|
|
@@ -3190,7 +3853,7 @@ function resolveClientOptions(options) {
|
|
|
3190
3853
|
resultCaptureMode
|
|
3191
3854
|
};
|
|
3192
3855
|
}
|
|
3193
|
-
var hasText2 = (value) => typeof value === "string" &&
|
|
3856
|
+
var hasText2 = (value) => typeof value === "string" && !isBlank(value);
|
|
3194
3857
|
function describeError(err) {
|
|
3195
3858
|
let type = "Error";
|
|
3196
3859
|
let body = "";
|
|
@@ -3204,19 +3867,18 @@ function describeError(err) {
|
|
|
3204
3867
|
}
|
|
3205
3868
|
return [type, body];
|
|
3206
3869
|
}
|
|
3207
|
-
function isPlainObject3(value) {
|
|
3208
|
-
if (typeof value !== "object" || value === null) return false;
|
|
3209
|
-
const proto = Object.getPrototypeOf(value);
|
|
3210
|
-
return proto === Object.prototype || proto === null;
|
|
3211
|
-
}
|
|
3212
3870
|
function paramsOf(args) {
|
|
3213
|
-
if (args.length === 1 &&
|
|
3871
|
+
if (args.length === 1 && isPlainObject(args[0])) return args[0];
|
|
3214
3872
|
return args.length === 0 ? {} : { args };
|
|
3215
3873
|
}
|
|
3216
3874
|
var Core = class {
|
|
3217
3875
|
closed = false;
|
|
3218
3876
|
pending = /* @__PURE__ */ new Set();
|
|
3219
3877
|
closedWarned = false;
|
|
3878
|
+
// A snapshot describes the server, so it takes no block's session,
|
|
3879
|
+
// principal or client: SPEC §11.5.1's join must not count it.
|
|
3880
|
+
surfaceSessionId = uuid7();
|
|
3881
|
+
sentSurfaces = new SentSurfaces();
|
|
3220
3882
|
sink;
|
|
3221
3883
|
vendorId;
|
|
3222
3884
|
tenantId;
|
|
@@ -3249,6 +3911,7 @@ var Core = class {
|
|
|
3249
3911
|
live() {
|
|
3250
3912
|
if (this.disabled) return false;
|
|
3251
3913
|
if (!this.closed) return true;
|
|
3914
|
+
PROCESS_DROPS.add("after_close");
|
|
3252
3915
|
if (!this.closedWarned) {
|
|
3253
3916
|
this.closedWarned = true;
|
|
3254
3917
|
process.stderr.write("baton: Client is closed; further events are dropped.\n");
|
|
@@ -3257,19 +3920,69 @@ var Core = class {
|
|
|
3257
3920
|
}
|
|
3258
3921
|
/** Never rejects. Tracked so `flush()` can wait for it. */
|
|
3259
3922
|
emit(build) {
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
3923
|
+
return this.track(emit(this.sink, build));
|
|
3924
|
+
}
|
|
3925
|
+
track(work) {
|
|
3926
|
+
const tracked = work.finally(() => this.pending.delete(tracked));
|
|
3927
|
+
this.pending.add(tracked);
|
|
3928
|
+
return tracked;
|
|
3929
|
+
}
|
|
3930
|
+
/** Sends `surface` unless this client already has. Never rejects; a failed
|
|
3931
|
+
* write unmarks it, so the next `listTools` tries again. A surface that does
|
|
3932
|
+
* not fit the schema stays marked: it would fail the same way every time. */
|
|
3933
|
+
sendSurface(surface) {
|
|
3934
|
+
if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
|
|
3935
|
+
this.sentSurfaces.mark(surface.digest);
|
|
3936
|
+
let event;
|
|
3937
|
+
try {
|
|
3938
|
+
event = SurfaceSnapshotEventSchema.parse({
|
|
3939
|
+
tenant_id: this.tenantId,
|
|
3940
|
+
vendor_id: this.vendorId,
|
|
3941
|
+
session_id: this.surfaceSessionId,
|
|
3942
|
+
session_id_origin: "minted",
|
|
3943
|
+
sequence_number: nextClockSequence(),
|
|
3944
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3945
|
+
consent_token: this.consentToken,
|
|
3946
|
+
payload: snapshotPayload(surface)
|
|
3947
|
+
});
|
|
3948
|
+
} catch (err) {
|
|
3949
|
+
PROCESS_DROPS.add("encode_failed");
|
|
3950
|
+
process.stderr.write(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}
|
|
3951
|
+
`);
|
|
3952
|
+
return Promise.resolve();
|
|
3953
|
+
}
|
|
3954
|
+
return this.track(
|
|
3955
|
+
(async () => {
|
|
3956
|
+
try {
|
|
3957
|
+
await this.sink.write(event);
|
|
3958
|
+
} catch (err) {
|
|
3959
|
+
process.stderr.write(`baton: surface snapshot not sent; will retry: ${printable(err)}
|
|
3960
|
+
`);
|
|
3961
|
+
this.sentSurfaces.unmark(surface.digest);
|
|
3962
|
+
}
|
|
3963
|
+
})()
|
|
3964
|
+
);
|
|
3263
3965
|
}
|
|
3264
|
-
|
|
3265
|
-
|
|
3966
|
+
/** Waits up to `ms` for pending events to reach the sink; with `untilEmpty`,
|
|
3967
|
+
* also for ones emitted while it waits. A write still pending when time runs
|
|
3968
|
+
* out is not waited on again, so one stuck write costs one wait. */
|
|
3969
|
+
async settleWithin(ms, untilEmpty) {
|
|
3970
|
+
const deadline = performance.now() + ms;
|
|
3971
|
+
do {
|
|
3972
|
+
const waiting = [...this.pending];
|
|
3973
|
+
if (await raceDeadline(Promise.allSettled(waiting), deadline - performance.now()) === TIMED_OUT) {
|
|
3974
|
+
const left = waiting.filter((write) => this.pending.delete(write));
|
|
3975
|
+
if (untilEmpty) PROCESS_DROPS.add("unsent_at_close", left.length);
|
|
3976
|
+
return;
|
|
3977
|
+
}
|
|
3978
|
+
} while (untilEmpty && this.pending.size > 0);
|
|
3266
3979
|
}
|
|
3267
3980
|
scrub(value, field) {
|
|
3268
3981
|
return scrubOrNull(this.scrubber, value, field);
|
|
3269
3982
|
}
|
|
3270
3983
|
annotate(session, consentToken, options) {
|
|
3271
3984
|
if (!this.live()) return Promise.resolve();
|
|
3272
|
-
const sequence =
|
|
3985
|
+
const sequence = nextClockSequence();
|
|
3273
3986
|
const text = (value) => value === void 0 ? null : this.scrubber(value);
|
|
3274
3987
|
return this.emit(
|
|
3275
3988
|
() => AnnotationEventSchema.parse({
|
|
@@ -3337,7 +4050,7 @@ var Trace = class _Trace {
|
|
|
3337
4050
|
try {
|
|
3338
4051
|
this.#result = this.#core.scrubber(result);
|
|
3339
4052
|
} catch (err) {
|
|
3340
|
-
process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${
|
|
4053
|
+
process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}
|
|
3341
4054
|
`);
|
|
3342
4055
|
this.#result = SCRUB_FAILED;
|
|
3343
4056
|
}
|
|
@@ -3357,7 +4070,7 @@ var Trace = class _Trace {
|
|
|
3357
4070
|
#start() {
|
|
3358
4071
|
this.#startedAt = performance.now();
|
|
3359
4072
|
if (!this.#core.live()) return;
|
|
3360
|
-
const sequence =
|
|
4073
|
+
const sequence = nextClockSequence();
|
|
3361
4074
|
const o = this.#options;
|
|
3362
4075
|
const params = o.params === void 0 ? {} : this.#core.scrub(o.params, "params") ?? {};
|
|
3363
4076
|
const textOf = (value, field) => {
|
|
@@ -3386,7 +4099,7 @@ var Trace = class _Trace {
|
|
|
3386
4099
|
const durationMs = this.#durationMs();
|
|
3387
4100
|
if (!this.#core.live()) return;
|
|
3388
4101
|
if (this.#result === UNSET && this.#error === null) this.observed(value);
|
|
3389
|
-
const sequence =
|
|
4102
|
+
const sequence = nextClockSequence();
|
|
3390
4103
|
const error = this.#error;
|
|
3391
4104
|
if (error !== null) {
|
|
3392
4105
|
this.#emitError(sequence, error.type, error.body, durationMs);
|
|
@@ -3408,7 +4121,7 @@ var Trace = class _Trace {
|
|
|
3408
4121
|
#fail(err) {
|
|
3409
4122
|
const durationMs = this.#durationMs();
|
|
3410
4123
|
if (!this.#core.live()) return;
|
|
3411
|
-
this.#emitError(
|
|
4124
|
+
this.#emitError(nextClockSequence(), ...describeError(err), durationMs);
|
|
3412
4125
|
}
|
|
3413
4126
|
#emitError(sequence, type, body, durationMs) {
|
|
3414
4127
|
void this.#core.emit(
|
|
@@ -3484,7 +4197,7 @@ var Client = class {
|
|
|
3484
4197
|
try {
|
|
3485
4198
|
block = newSession(options, this.#core.scrubber, this.#core.disabled);
|
|
3486
4199
|
} catch (err) {
|
|
3487
|
-
process.stderr.write(`baton: session values could not be read; using a minted session: ${
|
|
4200
|
+
process.stderr.write(`baton: session values could not be read; using a minted session: ${printable(err)}
|
|
3488
4201
|
`);
|
|
3489
4202
|
block = newSession({}, this.#core.scrubber, this.#core.disabled);
|
|
3490
4203
|
}
|
|
@@ -3514,30 +4227,41 @@ var Client = class {
|
|
|
3514
4227
|
const given = options ?? {};
|
|
3515
4228
|
return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
|
|
3516
4229
|
}
|
|
3517
|
-
/**
|
|
4230
|
+
/** `tools`, the vendor's own `tools/list` entries, with `user_goal` added
|
|
4231
|
+
* to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`
|
|
4232
|
+
* of `tools` as passed, sent once per distinct surface. For a vendor
|
|
4233
|
+
* serving MCP itself (SPEC §5.6).
|
|
4234
|
+
*
|
|
4235
|
+
* Pass the tools before anything of Baton's is added, so the snapshot
|
|
4236
|
+
* describes the vendor's own surface. `options` holds the vendor's own
|
|
4237
|
+
* `initialize` values. The input is not changed. Never rejects over the
|
|
4238
|
+
* tool list: one it cannot read is returned as it came. Does not wait for
|
|
4239
|
+
* the snapshot to be sent; `flush()` does. */
|
|
4240
|
+
async listTools(tools, options = {}) {
|
|
4241
|
+
if (this.#core.disabled) return tools;
|
|
4242
|
+
const { served, surface } = serveTools(tools, options);
|
|
4243
|
+
if (surface !== null) void this.#core.sendSurface(surface);
|
|
4244
|
+
return served;
|
|
4245
|
+
}
|
|
4246
|
+
/** Wait for events so far to reach the sink, then flush it. Never rejects;
|
|
4247
|
+
* returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
|
|
3518
4248
|
async flush() {
|
|
3519
|
-
await this.#
|
|
3520
|
-
try {
|
|
3521
|
-
await this.#core.sink.flush();
|
|
3522
|
-
} catch (err) {
|
|
3523
|
-
process.stderr.write(`baton: sink.flush failed: ${String(err)}
|
|
3524
|
-
`);
|
|
3525
|
-
}
|
|
4249
|
+
await this.#settleThen("flush");
|
|
3526
4250
|
}
|
|
3527
4251
|
/** Flush, then close the sink. Later events are dropped. */
|
|
3528
4252
|
aclose() {
|
|
3529
|
-
this.#closing ??= this.#
|
|
4253
|
+
this.#closing ??= this.#settleThen("aclose");
|
|
3530
4254
|
return this.#closing;
|
|
3531
4255
|
}
|
|
3532
|
-
|
|
3533
|
-
|
|
3534
|
-
|
|
3535
|
-
|
|
3536
|
-
|
|
3537
|
-
|
|
3538
|
-
|
|
3539
|
-
|
|
3540
|
-
}
|
|
4256
|
+
/** One budget: events in flight get until its end to reach the sink, then
|
|
4257
|
+
* the sink gets the time left. */
|
|
4258
|
+
async #settleThen(method) {
|
|
4259
|
+
await boundedSinkCall(this.#core.sink, method, async (budgetMs) => {
|
|
4260
|
+
const deadline = performance.now() + budgetMs;
|
|
4261
|
+
await this.#core.settleWithin(budgetMs, method === "aclose");
|
|
4262
|
+
if (method === "aclose") this.#core.closed = true;
|
|
4263
|
+
await callWithin(this.#core.sink, method, Math.max(0, deadline - performance.now()));
|
|
4264
|
+
});
|
|
3541
4265
|
}
|
|
3542
4266
|
};
|
|
3543
4267
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -3546,13 +4270,18 @@ var Client = class {
|
|
|
3546
4270
|
AnnotationPayloadSchema,
|
|
3547
4271
|
BatonHandle,
|
|
3548
4272
|
Client,
|
|
4273
|
+
ClientReportEventSchema,
|
|
4274
|
+
ClientReportPayloadSchema,
|
|
3549
4275
|
DEFAULT_CONSENT_TOKEN,
|
|
3550
4276
|
DEPTH_LIMIT,
|
|
4277
|
+
DEPTH_MARKER,
|
|
3551
4278
|
EventSchema,
|
|
3552
4279
|
EventTypeSchema,
|
|
4280
|
+
FileSink,
|
|
3553
4281
|
HttpSink,
|
|
3554
4282
|
INTENT_INSTRUCTIONS,
|
|
3555
4283
|
INTENT_PARAMS,
|
|
4284
|
+
MultiSink,
|
|
3556
4285
|
PRINCIPAL_FORM_HASHED,
|
|
3557
4286
|
PRINCIPAL_FORM_RAW,
|
|
3558
4287
|
PRINCIPAL_SOURCE_ASSERTED,
|