@goodtiming/baton-sdk 0.6.1 → 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 +13 -9
- package/dist/index.cjs +995 -340
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +232 -29
- package/dist/index.d.ts +232 -29
- package/dist/index.js +990 -340
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/version.ts
|
|
2
|
-
var SDK_VERSION = "ts-0.6.
|
|
2
|
+
var SDK_VERSION = "ts-0.6.2";
|
|
3
3
|
|
|
4
4
|
// src/events.ts
|
|
5
5
|
import { z } from "zod";
|
|
@@ -120,6 +120,10 @@ var SurfaceSnapshotPayloadSchema = z.object({
|
|
|
120
120
|
tools: z.array(z.record(z.string(), z.unknown())).default([]),
|
|
121
121
|
seam_augmentations: z.record(z.string(), z.unknown()).default({})
|
|
122
122
|
}).strict();
|
|
123
|
+
var ClientReportPayloadSchema = z.object({
|
|
124
|
+
instance_id: z.uuid(),
|
|
125
|
+
dropped: z.record(z.string(), z.number().int().nonnegative())
|
|
126
|
+
}).strict();
|
|
123
127
|
var DEFAULT_CONSENT_TOKEN = "customer-consented";
|
|
124
128
|
var ClientObservedSchema = z.object({
|
|
125
129
|
info: z.object({ name: z.string().optional(), version: z.string().optional() }).strict().optional(),
|
|
@@ -157,6 +161,7 @@ var EventTypeSchema = z.enum([
|
|
|
157
161
|
"tool_call_error",
|
|
158
162
|
"annotation",
|
|
159
163
|
"surface_snapshot",
|
|
164
|
+
"client_report",
|
|
160
165
|
// The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose
|
|
161
166
|
// shapes were set by `baton-proxy`, which has been emitting all of them in
|
|
162
167
|
// production — see the payload schemas below.
|
|
@@ -266,6 +271,11 @@ var SurfaceSnapshotEventSchema = z.object({
|
|
|
266
271
|
event_type: z.literal("surface_snapshot").default("surface_snapshot"),
|
|
267
272
|
payload: SurfaceSnapshotPayloadSchema
|
|
268
273
|
}).strict();
|
|
274
|
+
var ClientReportEventSchema = z.object({
|
|
275
|
+
...envelopeShape,
|
|
276
|
+
event_type: z.literal("client_report").default("client_report"),
|
|
277
|
+
payload: ClientReportPayloadSchema
|
|
278
|
+
}).strict();
|
|
269
279
|
var ResourceListStartEventSchema = z.object({
|
|
270
280
|
...envelopeShape,
|
|
271
281
|
event_type: z.literal("resource_list_start").default("resource_list_start"),
|
|
@@ -347,6 +357,7 @@ var EventSchema = z.discriminatedUnion("event_type", [
|
|
|
347
357
|
ToolCallErrorEventSchema,
|
|
348
358
|
AnnotationEventSchema,
|
|
349
359
|
SurfaceSnapshotEventSchema,
|
|
360
|
+
ClientReportEventSchema,
|
|
350
361
|
ResourceListStartEventSchema,
|
|
351
362
|
ResourceListEndEventSchema,
|
|
352
363
|
ResourceListErrorEventSchema,
|
|
@@ -364,8 +375,33 @@ var EventSchema = z.discriminatedUnion("event_type", [
|
|
|
364
375
|
ToolListErrorEventSchema
|
|
365
376
|
]);
|
|
366
377
|
|
|
378
|
+
// src/warn.ts
|
|
379
|
+
function warn(message) {
|
|
380
|
+
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
381
|
+
process.emitWarning(message);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
function printable(err) {
|
|
385
|
+
try {
|
|
386
|
+
return String(err);
|
|
387
|
+
} catch {
|
|
388
|
+
return "(an error that cannot be printed)";
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// src/_object.ts
|
|
393
|
+
function isPlainObject(value) {
|
|
394
|
+
if (typeof value !== "object" || value === null) return false;
|
|
395
|
+
const proto = Object.getPrototypeOf(value);
|
|
396
|
+
return proto === Object.prototype || proto === null;
|
|
397
|
+
}
|
|
398
|
+
function isRecord(value) {
|
|
399
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
400
|
+
}
|
|
401
|
+
|
|
367
402
|
// src/scrub.ts
|
|
368
403
|
var DEPTH_LIMIT = 10;
|
|
404
|
+
var DEPTH_MARKER = "[REDACTED:depth-limit]";
|
|
369
405
|
var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
370
406
|
"email",
|
|
371
407
|
"phone",
|
|
@@ -376,16 +412,21 @@ var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
|
376
412
|
"password",
|
|
377
413
|
"user_name"
|
|
378
414
|
]);
|
|
415
|
+
var WS_CHARS = String.raw` \t\n\r\f\u00a0`;
|
|
416
|
+
var PHONE_SEP = String.raw`[${WS_CHARS}\-.]`;
|
|
379
417
|
var PATTERNS = [
|
|
380
418
|
["jwt", /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g],
|
|
381
|
-
["bearer",
|
|
419
|
+
["bearer", new RegExp(String.raw`\bBearer[${WS_CHARS}]+[A-Za-z0-9_\-.+/=]{16,}`, "gi")],
|
|
382
420
|
["sk_key", /\bsk-[A-Za-z0-9_-]{20,}\b/g],
|
|
383
421
|
["aws_key", /\bAKIA[0-9A-Z]{16}\b/g],
|
|
384
422
|
["email", /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g],
|
|
385
423
|
// Phone: optional `+1`, optional area-code parens, separators
|
|
386
|
-
//
|
|
424
|
+
// `-`, `.` or `WS_CHARS`, 10 digits. Conservative — won't catch every
|
|
387
425
|
// international format, but won't trip on every 10-digit identifier.
|
|
388
|
-
[
|
|
426
|
+
[
|
|
427
|
+
"phone",
|
|
428
|
+
new RegExp(String.raw`\b(?:\+?1${PHONE_SEP}?)?\(?\d{3}\)?${PHONE_SEP}?\d{3}${PHONE_SEP}?\d{4}\b`, "g")
|
|
429
|
+
]
|
|
389
430
|
];
|
|
390
431
|
var CC_CANDIDATE = /\b\d{13,19}\b/g;
|
|
391
432
|
function luhnValid(digits) {
|
|
@@ -400,13 +441,9 @@ function luhnValid(digits) {
|
|
|
400
441
|
}
|
|
401
442
|
return total % 10 === 0;
|
|
402
443
|
}
|
|
403
|
-
function isPlainObject(value) {
|
|
404
|
-
if (typeof value !== "object" || value === null) return false;
|
|
405
|
-
const proto = Object.getPrototypeOf(value);
|
|
406
|
-
return proto === Object.prototype || proto === null;
|
|
407
|
-
}
|
|
408
444
|
var Scrubber = class {
|
|
409
445
|
counts = /* @__PURE__ */ new Map();
|
|
446
|
+
warnedDepth = false;
|
|
410
447
|
/** Bound so `new Scrubber().scrub` can be passed as a bare function
|
|
411
448
|
* reference — the closest TS gets to Python's `__call__`. */
|
|
412
449
|
scrub = (value) => this.walk(value, 0, null);
|
|
@@ -417,8 +454,20 @@ var Scrubber = class {
|
|
|
417
454
|
bump(category) {
|
|
418
455
|
this.counts.set(category, this.count(category) + 1);
|
|
419
456
|
}
|
|
457
|
+
pastTheDepthLimit() {
|
|
458
|
+
this.bump("depth_limit");
|
|
459
|
+
if (!this.warnedDepth) {
|
|
460
|
+
this.warnedDepth = true;
|
|
461
|
+
warn(
|
|
462
|
+
`baton: a payload nests deeper than ${DEPTH_LIMIT} levels; containers past that depth are sent as ${JSON.stringify(DEPTH_MARKER)}`
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
return DEPTH_MARKER;
|
|
466
|
+
}
|
|
420
467
|
walk(value, depth, forceField) {
|
|
421
|
-
if (depth >= DEPTH_LIMIT)
|
|
468
|
+
if (depth >= DEPTH_LIMIT && (isPlainObject(value) || Array.isArray(value))) {
|
|
469
|
+
return this.pastTheDepthLimit();
|
|
470
|
+
}
|
|
422
471
|
if (isPlainObject(value)) {
|
|
423
472
|
const out = {};
|
|
424
473
|
for (const [k, v] of Object.entries(value)) {
|
|
@@ -459,14 +508,155 @@ function identityScrub(value) {
|
|
|
459
508
|
}
|
|
460
509
|
|
|
461
510
|
// src/sinks.ts
|
|
511
|
+
import { closeSync, openSync, writeSync } from "fs";
|
|
512
|
+
|
|
513
|
+
// src/_text.ts
|
|
514
|
+
var WHITE_SPACE = /^\p{White_Space}$/u;
|
|
515
|
+
var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
|
|
516
|
+
function stripEdges(value, space) {
|
|
517
|
+
let start = 0;
|
|
518
|
+
let end = value.length;
|
|
519
|
+
while (start < end && space.test(value[start])) start++;
|
|
520
|
+
while (end > start && space.test(value[end - 1])) end--;
|
|
521
|
+
return value.slice(start, end);
|
|
522
|
+
}
|
|
523
|
+
function stripWhiteSpace(value) {
|
|
524
|
+
return stripEdges(value, WHITE_SPACE);
|
|
525
|
+
}
|
|
526
|
+
function isBlank(value) {
|
|
527
|
+
return ALL_WHITE_SPACE.test(value);
|
|
528
|
+
}
|
|
529
|
+
function exceedsCodePoints(value, max) {
|
|
530
|
+
if (value.length <= max) return false;
|
|
531
|
+
if (value.length > 2 * max) return true;
|
|
532
|
+
return [...value].length > max;
|
|
533
|
+
}
|
|
534
|
+
function capCodePoints(value, max) {
|
|
535
|
+
if (value.length <= max) return value;
|
|
536
|
+
return [...value].slice(0, max).join("");
|
|
537
|
+
}
|
|
538
|
+
function escapeForLog(value) {
|
|
539
|
+
return value.replace(/[\\\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (c) => `\\u{${c.codePointAt(0).toString(16)}}`);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// src/deadline.ts
|
|
543
|
+
var TIMED_OUT = /* @__PURE__ */ Symbol("timedOut");
|
|
544
|
+
var MAX_TIMER_MS = 2 ** 31 - 1;
|
|
545
|
+
async function raceDeadline(work, ms) {
|
|
546
|
+
let timer;
|
|
547
|
+
const deadline = new Promise((resolve) => {
|
|
548
|
+
timer = setTimeout(() => resolve(TIMED_OUT), Math.min(ms, MAX_TIMER_MS));
|
|
549
|
+
timer.unref?.();
|
|
550
|
+
});
|
|
551
|
+
try {
|
|
552
|
+
return await Promise.race([work, deadline]);
|
|
553
|
+
} finally {
|
|
554
|
+
clearTimeout(timer);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
var SHUTDOWN_FLUSH_TIMEOUT_MS = 3e3;
|
|
558
|
+
|
|
559
|
+
// src/drops.ts
|
|
560
|
+
var RECOVERY_LOG_MS = 6e4;
|
|
561
|
+
var DropCounts = class {
|
|
562
|
+
#instanceId = uuid7();
|
|
563
|
+
#total = /* @__PURE__ */ new Map();
|
|
564
|
+
#sinceDelivery = /* @__PURE__ */ new Map();
|
|
565
|
+
#lastRecoveryLog = -RECOVERY_LOG_MS;
|
|
566
|
+
add(reason, n = 1) {
|
|
567
|
+
if (n <= 0) return;
|
|
568
|
+
this.#total.set(reason, (this.#total.get(reason) ?? 0) + n);
|
|
569
|
+
this.#sinceDelivery.set(reason, (this.#sinceDelivery.get(reason) ?? 0) + n);
|
|
570
|
+
}
|
|
571
|
+
total() {
|
|
572
|
+
return Object.fromEntries(this.#total);
|
|
573
|
+
}
|
|
574
|
+
/** Called on each delivery: names what was lost before it, the other half of
|
|
575
|
+
* a drop's own warning, which says only that loss started. */
|
|
576
|
+
logRecovery() {
|
|
577
|
+
if (this.#sinceDelivery.size === 0) return;
|
|
578
|
+
const now = performance.now();
|
|
579
|
+
if (now - this.#lastRecoveryLog < RECOVERY_LOG_MS) return;
|
|
580
|
+
const lost = [...this.#sinceDelivery].sort(([a], [b]) => a.localeCompare(b));
|
|
581
|
+
this.#sinceDelivery.clear();
|
|
582
|
+
this.#lastRecoveryLog = now;
|
|
583
|
+
const total = lost.reduce((sum, [, n]) => sum + n, 0);
|
|
584
|
+
warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
|
|
585
|
+
}
|
|
586
|
+
/** For tests: the counts are one per process. */
|
|
587
|
+
/** Names this process in its loss reports (SPEC §11.4.7). */
|
|
588
|
+
get instanceId() {
|
|
589
|
+
return this.#instanceId;
|
|
590
|
+
}
|
|
591
|
+
clear() {
|
|
592
|
+
this.#instanceId = uuid7();
|
|
593
|
+
this.#total.clear();
|
|
594
|
+
this.#sinceDelivery.clear();
|
|
595
|
+
this.#lastRecoveryLog = -RECOVERY_LOG_MS;
|
|
596
|
+
}
|
|
597
|
+
};
|
|
598
|
+
var PROCESS_DROPS = new DropCounts();
|
|
599
|
+
|
|
600
|
+
// src/sequence.ts
|
|
601
|
+
var lastSequence = 0;
|
|
602
|
+
function nextClockSequence() {
|
|
603
|
+
const nowMicros = Math.floor((performance.timeOrigin + performance.now()) * 1e3);
|
|
604
|
+
lastSequence = Math.max(lastSequence + 1, nowMicros);
|
|
605
|
+
return lastSequence;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// src/sinks.ts
|
|
609
|
+
var REFUSAL_BODY_MAX_LEN = 500;
|
|
610
|
+
var REFUSAL_LOG_MS = 6e4;
|
|
462
611
|
async function safeWrite(sink, event) {
|
|
463
612
|
try {
|
|
464
613
|
await sink.write(event);
|
|
465
614
|
} catch (err) {
|
|
466
|
-
|
|
615
|
+
PROCESS_DROPS.add("write_failed");
|
|
616
|
+
process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
|
|
467
617
|
`);
|
|
468
618
|
}
|
|
469
619
|
}
|
|
620
|
+
function stderrLine(message) {
|
|
621
|
+
process.stderr.write(`${message}
|
|
622
|
+
`);
|
|
623
|
+
}
|
|
624
|
+
function isTimerMs(value) {
|
|
625
|
+
return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
|
|
626
|
+
}
|
|
627
|
+
function shutdownFlushTimeoutOption(given) {
|
|
628
|
+
if (isTimerMs(given)) return given;
|
|
629
|
+
if (given !== void 0) {
|
|
630
|
+
warn(`baton: shutdownFlushTimeoutMs must be from 0 to ${MAX_TIMER_MS} ms; using ${SHUTDOWN_FLUSH_TIMEOUT_MS}.`);
|
|
631
|
+
}
|
|
632
|
+
return SHUTDOWN_FLUSH_TIMEOUT_MS;
|
|
633
|
+
}
|
|
634
|
+
function shutdownBudgetMs(sink) {
|
|
635
|
+
try {
|
|
636
|
+
if (sink instanceof MultiSink) return Math.max(...sink["sinks"].map(shutdownBudgetMs));
|
|
637
|
+
const budget = sink instanceof HttpSink ? sink["shutdownFlushTimeoutMs"] : void 0;
|
|
638
|
+
if (isTimerMs(budget)) return budget;
|
|
639
|
+
} catch {
|
|
640
|
+
}
|
|
641
|
+
return SHUTDOWN_FLUSH_TIMEOUT_MS;
|
|
642
|
+
}
|
|
643
|
+
function callWithin(sink, method, ms) {
|
|
644
|
+
if (sink[method] === HttpSink.prototype[method]) return sink[`${method}Within`](ms);
|
|
645
|
+
if (sink[method] === MultiSink.prototype[method]) return sink[`${method}Within`](ms);
|
|
646
|
+
return sink[method]();
|
|
647
|
+
}
|
|
648
|
+
async function boundedSinkCall(sink, method, work = () => sink[method]()) {
|
|
649
|
+
const what = `${method}()`;
|
|
650
|
+
const budget = shutdownBudgetMs(sink);
|
|
651
|
+
const ms = budget + 250;
|
|
652
|
+
const settled = Promise.resolve().then(() => work(budget)).then(
|
|
653
|
+
() => void 0,
|
|
654
|
+
(err) => warn(`baton: ${what} failed: ${printable(err)}`)
|
|
655
|
+
);
|
|
656
|
+
if (await raceDeadline(settled, ms) === TIMED_OUT) {
|
|
657
|
+
warn(`baton: ${what} took over ${String(ms)} ms and was left unfinished.`);
|
|
658
|
+
}
|
|
659
|
+
}
|
|
470
660
|
var StdoutSink = class {
|
|
471
661
|
stream;
|
|
472
662
|
closed = false;
|
|
@@ -483,6 +673,57 @@ var StdoutSink = class {
|
|
|
483
673
|
this.closed = true;
|
|
484
674
|
}
|
|
485
675
|
};
|
|
676
|
+
var FileSink = class {
|
|
677
|
+
constructor(path) {
|
|
678
|
+
this.path = path;
|
|
679
|
+
}
|
|
680
|
+
path;
|
|
681
|
+
fd = null;
|
|
682
|
+
closed = false;
|
|
683
|
+
async write(event) {
|
|
684
|
+
if (this.closed) throw new Error("FileSink is closed");
|
|
685
|
+
this.fd ??= openSync(this.path, "a");
|
|
686
|
+
writeSync(this.fd, JSON.stringify(event) + "\n");
|
|
687
|
+
}
|
|
688
|
+
async flush() {
|
|
689
|
+
}
|
|
690
|
+
async aclose() {
|
|
691
|
+
if (this.closed) return;
|
|
692
|
+
this.closed = true;
|
|
693
|
+
if (this.fd !== null) {
|
|
694
|
+
closeSync(this.fd);
|
|
695
|
+
this.fd = null;
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
var MultiSink = class {
|
|
700
|
+
sinks;
|
|
701
|
+
constructor(sinks) {
|
|
702
|
+
if (sinks.length === 0) throw new Error("MultiSink requires at least one sink");
|
|
703
|
+
this.sinks = [...sinks];
|
|
704
|
+
}
|
|
705
|
+
write(event) {
|
|
706
|
+
return this.fanOut((sink) => sink.write(event));
|
|
707
|
+
}
|
|
708
|
+
flush() {
|
|
709
|
+
return this.flushWithin(Infinity);
|
|
710
|
+
}
|
|
711
|
+
aclose() {
|
|
712
|
+
return this.acloseWithin(Infinity);
|
|
713
|
+
}
|
|
714
|
+
flushWithin(ms) {
|
|
715
|
+
return this.fanOut((sink) => callWithin(sink, "flush", ms));
|
|
716
|
+
}
|
|
717
|
+
acloseWithin(ms) {
|
|
718
|
+
return this.fanOut((sink) => callWithin(sink, "aclose", ms));
|
|
719
|
+
}
|
|
720
|
+
async fanOut(op) {
|
|
721
|
+
const results = await Promise.allSettled(this.sinks.map(async (sink) => op(sink)));
|
|
722
|
+
const errors = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
|
|
723
|
+
if (errors.length === 1) throw errors[0];
|
|
724
|
+
if (errors.length > 1) throw new AggregateError(errors, "MultiSink fan-out failures");
|
|
725
|
+
}
|
|
726
|
+
};
|
|
486
727
|
var CircuitBreaker = class {
|
|
487
728
|
constructor(threshold, resetMs) {
|
|
488
729
|
this.threshold = threshold;
|
|
@@ -512,19 +753,43 @@ var HttpSink = class _HttpSink {
|
|
|
512
753
|
apiKey;
|
|
513
754
|
buffer = [];
|
|
514
755
|
bufferSize;
|
|
756
|
+
requestTimeoutMs;
|
|
757
|
+
shutdownFlushTimeoutMs;
|
|
758
|
+
/** Set when an exit pass ends; cleared once a normal drain empties the
|
|
759
|
+
* buffer, which means the process went on. */
|
|
760
|
+
exitPassRan = false;
|
|
761
|
+
/** Whether the exit pass warned about every event now buffered. */
|
|
762
|
+
unsentWarned = false;
|
|
515
763
|
maxRetries;
|
|
516
764
|
backoffBaseMs;
|
|
517
765
|
backoffMaxMs;
|
|
518
766
|
circuit;
|
|
519
767
|
fetchImpl;
|
|
520
768
|
overflowWarned = false;
|
|
521
|
-
|
|
769
|
+
/** Per status, so a new kind of refusal, such as a 401 after a 422, still warns. */
|
|
770
|
+
refusals = /* @__PURE__ */ new Map();
|
|
771
|
+
/** Aborted once `aclose()` returns: nothing Baton started may keep the
|
|
772
|
+
* process alive after the vendor closed it. */
|
|
773
|
+
closing = new AbortController();
|
|
774
|
+
/** The drain chain's tail when a flush() or aclose() gave up waiting, until it settles. */
|
|
775
|
+
stalledDrain = null;
|
|
776
|
+
skipWarnedFor = null;
|
|
777
|
+
closeOnce;
|
|
522
778
|
drainChain = Promise.resolve();
|
|
523
|
-
|
|
779
|
+
exitHooks = null;
|
|
780
|
+
/** The least time between two of this sink's loss reports. */
|
|
781
|
+
static reportIntervalMs = 6e4;
|
|
782
|
+
/** Totals only grow, so their sum tells whether they changed. */
|
|
783
|
+
reportedSum = 0;
|
|
784
|
+
lastReportAt = -Infinity;
|
|
785
|
+
reportsStopped = false;
|
|
786
|
+
reportInFlight = null;
|
|
524
787
|
constructor(url, options) {
|
|
525
788
|
this.url = url.replace(/\/+$/, "");
|
|
526
789
|
this.apiKey = options.apiKey;
|
|
527
790
|
this.bufferSize = options.bufferSize ?? 1e3;
|
|
791
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
|
|
792
|
+
this.shutdownFlushTimeoutMs = shutdownFlushTimeoutOption(options.shutdownFlushTimeoutMs);
|
|
528
793
|
this.maxRetries = options.maxRetries ?? 3;
|
|
529
794
|
this.backoffBaseMs = options.backoffBaseMs ?? 100;
|
|
530
795
|
this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
|
|
@@ -540,9 +805,7 @@ var HttpSink = class _HttpSink {
|
|
|
540
805
|
* ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it
|
|
541
806
|
* hangs off `BatonHandle.sink` and off the resolved config, so
|
|
542
807
|
* `console.log(handle.sink)` or a structured logger serialising either one
|
|
543
|
-
*
|
|
544
|
-
* asserts the DSN's own string does not survive resolution: it does not, and
|
|
545
|
-
* the key was one field further down. Same treatment as the parsed DSN —
|
|
808
|
+
* would write a publishable key into the vendor's logs. Same treatment as the parsed DSN —
|
|
546
809
|
* `toJSON` for serialisers, the inspect symbol for `console.log`, and
|
|
547
810
|
* `Symbol.for` rather than importing `node:util`, since this package runs on
|
|
548
811
|
* runtimes that have no such module.
|
|
@@ -553,29 +816,84 @@ var HttpSink = class _HttpSink {
|
|
|
553
816
|
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
554
817
|
return this.toJSON();
|
|
555
818
|
}
|
|
819
|
+
get closed() {
|
|
820
|
+
return this.closing.signal.aborted;
|
|
821
|
+
}
|
|
556
822
|
async write(event) {
|
|
557
823
|
if (this.closed) throw new Error("HttpSink is closed");
|
|
558
824
|
this.enqueue(event);
|
|
825
|
+
this.unsentWarned = false;
|
|
559
826
|
void this.scheduleDrain();
|
|
560
|
-
this.
|
|
827
|
+
this.ensureExitHooksRegistered();
|
|
561
828
|
}
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
await this.scheduleDrain();
|
|
829
|
+
flush() {
|
|
830
|
+
return this.flushWithin(Infinity);
|
|
565
831
|
}
|
|
566
|
-
|
|
832
|
+
/** A second call waits for the first (SPEC §11.2 rule 7). */
|
|
833
|
+
aclose() {
|
|
834
|
+
return this.acloseWithin(Infinity);
|
|
835
|
+
}
|
|
836
|
+
async flushWithin(ms) {
|
|
567
837
|
if (this.closed) return;
|
|
568
|
-
await this.flush();
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
838
|
+
await this.drainWithinBudget("flush()", Math.min(ms, this.shutdownFlushTimeoutMs));
|
|
839
|
+
}
|
|
840
|
+
acloseWithin(ms) {
|
|
841
|
+
this.closeOnce ??= this.close(Math.min(ms, this.shutdownFlushTimeoutMs));
|
|
842
|
+
return this.closeOnce;
|
|
843
|
+
}
|
|
844
|
+
async close(ms) {
|
|
845
|
+
this.stopReports();
|
|
846
|
+
await this.drainWithinBudget("aclose()", ms);
|
|
847
|
+
this.closing.abort();
|
|
848
|
+
if (this.buffer.length > 0) {
|
|
849
|
+
PROCESS_DROPS.add("unsent_at_close", this.buffer.length);
|
|
850
|
+
warn(`baton: the sink closed with ${this.buffer.length} event(s) unsent.`);
|
|
851
|
+
}
|
|
852
|
+
this.warnUnloggedRefusals("the sink closed");
|
|
853
|
+
if (this.exitHooks) {
|
|
854
|
+
process.off("beforeExit", this.exitHooks.beforeExit);
|
|
855
|
+
process.off("exit", this.exitHooks.exit);
|
|
856
|
+
this.exitHooks = null;
|
|
573
857
|
}
|
|
574
858
|
}
|
|
859
|
+
/** SPEC §11.2 rule 7: an explicit flush or close returns within `ms` and
|
|
860
|
+
* never rejects. While an earlier wait's drain is still stuck, a flush
|
|
861
|
+
* returns at once, without queuing a pass, and a close gives it `ms`. The
|
|
862
|
+
* drain is not cancelled here, so after `flush()` it goes on sending;
|
|
863
|
+
* `aclose()` stops it. */
|
|
864
|
+
async drainWithinBudget(what, ms) {
|
|
865
|
+
if (this.stalledDrain) {
|
|
866
|
+
if (what === "aclose()") {
|
|
867
|
+
await raceDeadline(this.stalledDrain, ms);
|
|
868
|
+
return;
|
|
869
|
+
}
|
|
870
|
+
if (this.skipWarnedFor !== this.stalledDrain) {
|
|
871
|
+
this.skipWarnedFor = this.stalledDrain;
|
|
872
|
+
warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.buffer.length} event(s) wait to be sent.`);
|
|
873
|
+
}
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
const settled = this.scheduleDrain().catch(() => void 0);
|
|
877
|
+
if (await raceDeadline(settled, ms) !== TIMED_OUT) return;
|
|
878
|
+
if (ms < this.shutdownFlushTimeoutMs) return;
|
|
879
|
+
const stalled = this.drainChain.catch(() => void 0);
|
|
880
|
+
this.stalledDrain = stalled;
|
|
881
|
+
void stalled.then(() => {
|
|
882
|
+
if (this.stalledDrain === stalled) this.stalledDrain = null;
|
|
883
|
+
});
|
|
884
|
+
if (what === "flush()") {
|
|
885
|
+
warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
/** A full buffer may already have pushed `event` out while it was being sent. */
|
|
889
|
+
dequeue(event) {
|
|
890
|
+
if (this.buffer[0] === event) this.buffer.shift();
|
|
891
|
+
}
|
|
575
892
|
enqueue(event) {
|
|
576
893
|
if (this.buffer.length >= this.bufferSize) {
|
|
894
|
+
PROCESS_DROPS.add("buffer_full");
|
|
577
895
|
if (!this.overflowWarned) {
|
|
578
|
-
|
|
896
|
+
warn(
|
|
579
897
|
`Baton HTTP sink buffer full (${this.bufferSize}); oldest events dropped. Further overflows will be silent.`
|
|
580
898
|
);
|
|
581
899
|
this.overflowWarned = true;
|
|
@@ -597,18 +915,58 @@ var HttpSink = class _HttpSink {
|
|
|
597
915
|
return this.drainChain;
|
|
598
916
|
}
|
|
599
917
|
/** Best-effort flush when the process is about to exit without an
|
|
600
|
-
* explicit `aclose()`.
|
|
601
|
-
*
|
|
602
|
-
*
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
918
|
+
* explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip
|
|
919
|
+
* both hooks: a vendor needing that guarantee must call `aclose()` from
|
|
920
|
+
* their own handler. */
|
|
921
|
+
ensureExitHooksRegistered() {
|
|
922
|
+
if (this.exitHooks) return;
|
|
923
|
+
const beforeExit = () => {
|
|
924
|
+
if (this.buffer.length === 0 || this.exitPassRan) {
|
|
925
|
+
this.warnUnloggedRefusals("process exiting");
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
this.drainChain = this.drainChain.then(
|
|
929
|
+
() => this.exitPass(),
|
|
930
|
+
() => this.exitPass()
|
|
931
|
+
);
|
|
610
932
|
};
|
|
611
|
-
|
|
933
|
+
const exit = () => {
|
|
934
|
+
try {
|
|
935
|
+
if (this.buffer.length > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
|
|
936
|
+
this.warnUnloggedRefusals("process exiting", stderrLine);
|
|
937
|
+
} catch {
|
|
938
|
+
}
|
|
939
|
+
};
|
|
940
|
+
this.exitHooks = { beforeExit, exit };
|
|
941
|
+
process.on("beforeExit", beforeExit);
|
|
942
|
+
process.on("exit", exit);
|
|
943
|
+
}
|
|
944
|
+
/** One attempt per event, no retry, within `shutdownFlushTimeoutMs` in
|
|
945
|
+
* total (SPEC §11.2); what is left is reported, not sent. */
|
|
946
|
+
async exitPass() {
|
|
947
|
+
const deadline = Date.now() + this.shutdownFlushTimeoutMs;
|
|
948
|
+
while (this.buffer.length > 0 && this.circuit.canRequest()) {
|
|
949
|
+
const timeLeft = deadline - Date.now();
|
|
950
|
+
if (timeLeft <= 0) break;
|
|
951
|
+
const event = this.buffer[0];
|
|
952
|
+
const body = this.encode(event);
|
|
953
|
+
if (body !== null) {
|
|
954
|
+
const outcome = await this.postOnce(body, Math.min(this.requestTimeoutMs, timeLeft));
|
|
955
|
+
if (outcome === "transient_failure") {
|
|
956
|
+
this.circuit.recordFailure();
|
|
957
|
+
break;
|
|
958
|
+
}
|
|
959
|
+
this.circuit.recordSuccess();
|
|
960
|
+
}
|
|
961
|
+
this.dequeue(event);
|
|
962
|
+
}
|
|
963
|
+
this.exitPassRan = true;
|
|
964
|
+
this.unsentWarned = true;
|
|
965
|
+
if (this.buffer.length > 0) warn(this.unsentAtExit());
|
|
966
|
+
this.warnUnloggedRefusals("process exiting");
|
|
967
|
+
}
|
|
968
|
+
unsentAtExit() {
|
|
969
|
+
return `baton: process exiting with ${this.buffer.length} unsent event(s).`;
|
|
612
970
|
}
|
|
613
971
|
events_url() {
|
|
614
972
|
return `${this.url}/v0/events`;
|
|
@@ -621,38 +979,197 @@ var HttpSink = class _HttpSink {
|
|
|
621
979
|
if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
|
|
622
980
|
return "transient_failure";
|
|
623
981
|
}
|
|
982
|
+
/** A refused event is otherwise dropped silently, which looks the same from
|
|
983
|
+
* the vendor's process as an accepted one. The collector's own message is
|
|
984
|
+
* logged because it names the field at fault; it is capped and escaped
|
|
985
|
+
* because it is a remote server's text landing in the vendor's log. */
|
|
986
|
+
static async logRefusal(response, unlogged) {
|
|
987
|
+
const detail = await _HttpSink.readHead(response).then(
|
|
988
|
+
(text) => escapeForLog(capCodePoints(text, REFUSAL_BODY_MAX_LEN)),
|
|
989
|
+
() => "<unreadable>"
|
|
990
|
+
);
|
|
991
|
+
warn(
|
|
992
|
+
`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.` : "")
|
|
993
|
+
);
|
|
994
|
+
}
|
|
995
|
+
warnUnloggedRefusals(when, emit2 = warn) {
|
|
996
|
+
let total = 0;
|
|
997
|
+
for (const seen of this.refusals.values()) {
|
|
998
|
+
total += seen.unlogged;
|
|
999
|
+
seen.unlogged = 0;
|
|
1000
|
+
}
|
|
1001
|
+
if (total > 0) emit2(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);
|
|
1002
|
+
}
|
|
1003
|
+
/** How many refusals with `status` went unlogged before this one, or `null`
|
|
1004
|
+
* when this one goes unlogged too. */
|
|
1005
|
+
refusalToLog(status) {
|
|
1006
|
+
const now = performance.now();
|
|
1007
|
+
const seen = this.refusals.get(status);
|
|
1008
|
+
if (seen !== void 0 && now - seen.loggedAt < REFUSAL_LOG_MS) {
|
|
1009
|
+
seen.unlogged++;
|
|
1010
|
+
return null;
|
|
1011
|
+
}
|
|
1012
|
+
this.refusals.set(status, { loggedAt: now, unlogged: 0 });
|
|
1013
|
+
return seen?.unlogged ?? 0;
|
|
1014
|
+
}
|
|
1015
|
+
/** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is
|
|
1016
|
+
* cancelled unread, so a large error page does not hold the drain. */
|
|
1017
|
+
static async readHead(response) {
|
|
1018
|
+
const reader = response.body?.getReader();
|
|
1019
|
+
if (reader === void 0) return "";
|
|
1020
|
+
const decoder = new TextDecoder();
|
|
1021
|
+
let text = "";
|
|
1022
|
+
try {
|
|
1023
|
+
while (text.length < REFUSAL_BODY_MAX_LEN * 2) {
|
|
1024
|
+
const { done, value } = await reader.read();
|
|
1025
|
+
if (done) return text + decoder.decode();
|
|
1026
|
+
text += decoder.decode(value, { stream: true });
|
|
1027
|
+
}
|
|
1028
|
+
return text;
|
|
1029
|
+
} finally {
|
|
1030
|
+
void reader.cancel().catch(() => {
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
624
1034
|
async drainLocked() {
|
|
625
1035
|
while (this.buffer.length > 0) {
|
|
626
|
-
if (!this.circuit.canRequest()) return;
|
|
1036
|
+
if (!this.circuit.canRequest() || this.closing.signal.aborted) return;
|
|
627
1037
|
const event = this.buffer[0];
|
|
628
1038
|
const outcome = await this.sendWithRetry(event);
|
|
629
1039
|
if (outcome === "success" || outcome === "permanent_failure") {
|
|
630
|
-
this.
|
|
1040
|
+
this.dequeue(event);
|
|
631
1041
|
this.circuit.recordSuccess();
|
|
1042
|
+
if (outcome === "success") {
|
|
1043
|
+
PROCESS_DROPS.logRecovery();
|
|
1044
|
+
this.maybeReport(event);
|
|
1045
|
+
}
|
|
1046
|
+
} else if (outcome === "unencodable") {
|
|
1047
|
+
this.dequeue(event);
|
|
632
1048
|
} else {
|
|
633
1049
|
this.circuit.recordFailure();
|
|
634
1050
|
return;
|
|
635
1051
|
}
|
|
636
1052
|
}
|
|
1053
|
+
this.exitPassRan = false;
|
|
1054
|
+
}
|
|
1055
|
+
/** Starts a report of this process's loss totals (SPEC §11.4.7) beside the
|
|
1056
|
+
* drain and outside the buffer, so it never delays an event and is never
|
|
1057
|
+
* counted as one. */
|
|
1058
|
+
maybeReport({ tenant_id, vendor_id, consent_token }) {
|
|
1059
|
+
const now = performance.now();
|
|
1060
|
+
if (this.reportsStopped || this.reportInFlight !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
const totals = PROCESS_DROPS.total();
|
|
1064
|
+
const sum = Object.values(totals).reduce((a, b) => a + b, 0);
|
|
1065
|
+
if (sum === this.reportedSum) return;
|
|
1066
|
+
this.lastReportAt = now;
|
|
1067
|
+
const abort = new AbortController();
|
|
1068
|
+
this.reportInFlight = abort;
|
|
1069
|
+
const envelope = { tenant_id, vendor_id, consent_token };
|
|
1070
|
+
void this.sendReport(envelope, totals, sum, abort).finally(() => {
|
|
1071
|
+
this.reportInFlight = null;
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
stopReports() {
|
|
1075
|
+
this.reportsStopped = true;
|
|
1076
|
+
this.reportInFlight?.abort();
|
|
1077
|
+
}
|
|
1078
|
+
async sendReport(envelope, totals, sum, abort) {
|
|
1079
|
+
const timer = setTimeout(() => abort.abort(), this.requestTimeoutMs);
|
|
1080
|
+
try {
|
|
1081
|
+
const report = ClientReportEventSchema.parse({
|
|
1082
|
+
...envelope,
|
|
1083
|
+
session_id: PROCESS_DROPS.instanceId,
|
|
1084
|
+
sequence_number: nextClockSequence(),
|
|
1085
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1086
|
+
payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
|
|
1087
|
+
});
|
|
1088
|
+
const response = await this.fetchImpl(this.events_url(), {
|
|
1089
|
+
method: "POST",
|
|
1090
|
+
headers: this.authHeaders(),
|
|
1091
|
+
body: JSON.stringify(report),
|
|
1092
|
+
signal: abort.signal
|
|
1093
|
+
});
|
|
1094
|
+
void response.body?.cancel().catch(() => void 0);
|
|
1095
|
+
if (response.status === 400 || response.status === 422) this.reportsStopped = true;
|
|
1096
|
+
else if (_HttpSink.classifyStatus(response.status) === "success") this.reportedSum = sum;
|
|
1097
|
+
} catch {
|
|
1098
|
+
} finally {
|
|
1099
|
+
clearTimeout(timer);
|
|
1100
|
+
}
|
|
637
1101
|
}
|
|
638
1102
|
async sendWithRetry(event) {
|
|
639
|
-
const
|
|
640
|
-
|
|
641
|
-
const body = JSON.stringify(event);
|
|
1103
|
+
const body = this.encode(event);
|
|
1104
|
+
if (body === null) return "unencodable";
|
|
642
1105
|
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
const outcome = _HttpSink.classifyStatus(response.status);
|
|
646
|
-
if (outcome !== "transient_failure") return outcome;
|
|
647
|
-
} catch {
|
|
648
|
-
}
|
|
1106
|
+
const outcome = await this.postOnce(body, this.requestTimeoutMs);
|
|
1107
|
+
if (outcome !== "transient_failure") return outcome;
|
|
649
1108
|
if (attempt < this.maxRetries) {
|
|
650
1109
|
const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);
|
|
651
|
-
await
|
|
1110
|
+
await this.sleepUnlessClosed(backoff);
|
|
1111
|
+
if (this.closing.signal.aborted) return "transient_failure";
|
|
652
1112
|
}
|
|
653
1113
|
}
|
|
654
1114
|
return "transient_failure";
|
|
655
1115
|
}
|
|
1116
|
+
/** `null`, with a warning, for an event `JSON.stringify` rejects. */
|
|
1117
|
+
encode(event) {
|
|
1118
|
+
try {
|
|
1119
|
+
return JSON.stringify(event);
|
|
1120
|
+
} catch (err) {
|
|
1121
|
+
PROCESS_DROPS.add("encode_failed");
|
|
1122
|
+
warn(
|
|
1123
|
+
`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.`
|
|
1124
|
+
);
|
|
1125
|
+
return null;
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
sleepUnlessClosed(ms) {
|
|
1129
|
+
if (this.closed) return Promise.resolve();
|
|
1130
|
+
return new Promise((resolve) => {
|
|
1131
|
+
const done = () => {
|
|
1132
|
+
clearTimeout(timer);
|
|
1133
|
+
this.closing.signal.removeEventListener("abort", done);
|
|
1134
|
+
resolve();
|
|
1135
|
+
};
|
|
1136
|
+
const timer = setTimeout(done, ms);
|
|
1137
|
+
this.closing.signal.addEventListener("abort", done);
|
|
1138
|
+
});
|
|
1139
|
+
}
|
|
1140
|
+
/** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`
|
|
1141
|
+
* is missing before Node 20.3, and on some later versions it keeps every
|
|
1142
|
+
* combined signal alive as long as the long-lived `closing` signal. */
|
|
1143
|
+
async postOnce(body, timeoutMs) {
|
|
1144
|
+
const request = new AbortController();
|
|
1145
|
+
const abort = () => request.abort();
|
|
1146
|
+
const timer = setTimeout(abort, timeoutMs);
|
|
1147
|
+
this.closing.signal.addEventListener("abort", abort);
|
|
1148
|
+
try {
|
|
1149
|
+
const response = await this.fetchImpl(this.events_url(), {
|
|
1150
|
+
method: "POST",
|
|
1151
|
+
headers: this.authHeaders(),
|
|
1152
|
+
body,
|
|
1153
|
+
signal: request.signal
|
|
1154
|
+
});
|
|
1155
|
+
const outcome = _HttpSink.classifyStatus(response.status);
|
|
1156
|
+
if (outcome === "permanent_failure") {
|
|
1157
|
+
PROCESS_DROPS.add("refused");
|
|
1158
|
+
const unlogged = this.refusalToLog(response.status);
|
|
1159
|
+
if (unlogged !== null) {
|
|
1160
|
+
await _HttpSink.logRefusal(response, unlogged);
|
|
1161
|
+
return outcome;
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
void response.body?.cancel().catch(() => void 0);
|
|
1165
|
+
return outcome;
|
|
1166
|
+
} catch {
|
|
1167
|
+
return "transient_failure";
|
|
1168
|
+
} finally {
|
|
1169
|
+
clearTimeout(timer);
|
|
1170
|
+
this.closing.signal.removeEventListener("abort", abort);
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
656
1173
|
};
|
|
657
1174
|
|
|
658
1175
|
// src/integrations/mcp/withBaton.ts
|
|
@@ -664,11 +1181,6 @@ import { z as z2 } from "zod";
|
|
|
664
1181
|
// src/metaCoordinates.ts
|
|
665
1182
|
var COORD_FIELD_NAMES = /* @__PURE__ */ new Set(["latitude", "longitude"]);
|
|
666
1183
|
var DECIMAL_STRING = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
|
|
667
|
-
function isPlainObject2(value) {
|
|
668
|
-
if (typeof value !== "object" || value === null) return false;
|
|
669
|
-
const proto = Object.getPrototypeOf(value);
|
|
670
|
-
return proto === Object.prototype || proto === null;
|
|
671
|
-
}
|
|
672
1184
|
function toOneDecimal(value) {
|
|
673
1185
|
const magnitude = Math.abs(value);
|
|
674
1186
|
if (Number.isInteger(magnitude * 4) && !Number.isInteger(magnitude * 2)) {
|
|
@@ -689,7 +1201,7 @@ function roundCoordinate(value) {
|
|
|
689
1201
|
}
|
|
690
1202
|
function walk(value, depth) {
|
|
691
1203
|
if (depth >= DEPTH_LIMIT) return value;
|
|
692
|
-
if (
|
|
1204
|
+
if (isPlainObject(value)) {
|
|
693
1205
|
const out = {};
|
|
694
1206
|
for (const [k, v] of Object.entries(value)) {
|
|
695
1207
|
const rounded = COORD_FIELD_NAMES.has(k.toLowerCase()) && depth + 1 < DEPTH_LIMIT ? roundCoordinate(v) : void 0;
|
|
@@ -706,126 +1218,6 @@ function roundMetaCoordinates(meta) {
|
|
|
706
1218
|
return walk(meta, 0);
|
|
707
1219
|
}
|
|
708
1220
|
|
|
709
|
-
// src/_text.ts
|
|
710
|
-
function exceedsCodePoints(value, max) {
|
|
711
|
-
if (value.length <= max) return false;
|
|
712
|
-
if (value.length > 2 * max) return true;
|
|
713
|
-
return [...value].length > max;
|
|
714
|
-
}
|
|
715
|
-
function capCodePoints(value, max) {
|
|
716
|
-
if (value.length <= max) return value;
|
|
717
|
-
return [...value].slice(0, max).join("");
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
// src/identity.ts
|
|
721
|
-
var PRINCIPAL_SOURCE_ASSERTED = "asserted";
|
|
722
|
-
var PRINCIPAL_FORM_HASHED = "hashed";
|
|
723
|
-
var PRINCIPAL_FORM_RAW = "raw";
|
|
724
|
-
var PRINCIPAL_ID_MAX_LEN = 128;
|
|
725
|
-
var DISPLAY_NAME_MAX_LEN = 128;
|
|
726
|
-
var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
|
|
727
|
-
function wireDisplayName(value) {
|
|
728
|
-
if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
|
|
729
|
-
if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
|
|
730
|
-
return value;
|
|
731
|
-
}
|
|
732
|
-
var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
|
|
733
|
-
var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
|
|
734
|
-
var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
|
|
735
|
-
var LONE_SURROGATE = /\p{Surrogate}/u;
|
|
736
|
-
function pythonStrip(value) {
|
|
737
|
-
return value.replace(PYTHON_STRIP, "");
|
|
738
|
-
}
|
|
739
|
-
function usableId(id) {
|
|
740
|
-
if (typeof id !== "string") return false;
|
|
741
|
-
if (LONE_SURROGATE.test(id)) return false;
|
|
742
|
-
if (id.includes("\0")) return false;
|
|
743
|
-
return pythonStrip(id) !== "";
|
|
744
|
-
}
|
|
745
|
-
function readIdentity(result, idKey) {
|
|
746
|
-
if (result === null || typeof result !== "object") return null;
|
|
747
|
-
const candidate = result;
|
|
748
|
-
const id = candidate[idKey];
|
|
749
|
-
if (!usableId(id)) return null;
|
|
750
|
-
const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
|
|
751
|
-
return { id, form: candidate.form, displayName };
|
|
752
|
-
}
|
|
753
|
-
var NO_CALLER = Object.freeze({ principal: null, organization: null });
|
|
754
|
-
function callerFor(result, warn4) {
|
|
755
|
-
try {
|
|
756
|
-
return readCaller(result, warn4);
|
|
757
|
-
} catch {
|
|
758
|
-
warn4("unreadable", "could not be read \u2014 sending neither principal nor organization.");
|
|
759
|
-
return NO_CALLER;
|
|
760
|
-
}
|
|
761
|
-
}
|
|
762
|
-
function readCaller(result, warn4) {
|
|
763
|
-
if (result === void 0 || result === null) return NO_CALLER;
|
|
764
|
-
if (typeof result !== "object") {
|
|
765
|
-
warn4("not-object", `got a ${typeof result}, not an object \u2014 sending neither principal nor organization.`);
|
|
766
|
-
return NO_CALLER;
|
|
767
|
-
}
|
|
768
|
-
if (!("principalId" in result) && !("organization" in result)) {
|
|
769
|
-
if ("organizationId" in result) {
|
|
770
|
-
return { principal: null, organization: identityFor(result, "organization", warn4) };
|
|
771
|
-
}
|
|
772
|
-
if (typeof result.userId === "string") {
|
|
773
|
-
warn4(
|
|
774
|
-
"user-id",
|
|
775
|
-
"returned { userId }, which was renamed to { principalId } in 0.3.5, so the principal is dropped from every event until it returns the new key."
|
|
776
|
-
);
|
|
777
|
-
} else {
|
|
778
|
-
warn4("no-id", "got an object with neither principalId nor organizationId \u2014 sending neither.");
|
|
779
|
-
}
|
|
780
|
-
return NO_CALLER;
|
|
781
|
-
}
|
|
782
|
-
if ("organizationId" in result) {
|
|
783
|
-
warn4("flat-organization-id", "got principalId and organizationId side by side; put the company in `organization`.");
|
|
784
|
-
}
|
|
785
|
-
const nested = result.organization;
|
|
786
|
-
return {
|
|
787
|
-
principal: identityFor(result, "principal", warn4),
|
|
788
|
-
organization: nested == null ? null : identityFor(nested, "organization", warn4)
|
|
789
|
-
};
|
|
790
|
-
}
|
|
791
|
-
function identityFor(value, member, warn4) {
|
|
792
|
-
const idKey = member === "principal" ? "principalId" : "organizationId";
|
|
793
|
-
const identity = readIdentity(value, idKey);
|
|
794
|
-
if (identity === null) {
|
|
795
|
-
warn4(`${member}:id`, `${member} has no usable ${idKey} \u2014 sending no ${member}.`);
|
|
796
|
-
return null;
|
|
797
|
-
}
|
|
798
|
-
return identityWire(
|
|
799
|
-
identity.id,
|
|
800
|
-
identity.form,
|
|
801
|
-
identity.displayName,
|
|
802
|
-
(form) => warn4(`${member}:form`, `${member} form ${describeForm(form)} is not registered \u2014 sending "raw".`)
|
|
803
|
-
);
|
|
804
|
-
}
|
|
805
|
-
function describeForm(form) {
|
|
806
|
-
return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
|
|
807
|
-
}
|
|
808
|
-
function identityWire(id, stated, displayName, onUnregisteredForm) {
|
|
809
|
-
let form = PRINCIPAL_FORM_RAW;
|
|
810
|
-
if (stated !== void 0) {
|
|
811
|
-
if (PRINCIPAL_FORMS.has(stated)) {
|
|
812
|
-
form = stated;
|
|
813
|
-
} else {
|
|
814
|
-
onUnregisteredForm?.(stated);
|
|
815
|
-
}
|
|
816
|
-
}
|
|
817
|
-
const wire = {
|
|
818
|
-
// `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
|
|
819
|
-
// an astral id cut at the boundary would ship a lone surrogate.
|
|
820
|
-
id: capCodePoints(id, PRINCIPAL_ID_MAX_LEN),
|
|
821
|
-
source: PRINCIPAL_SOURCE_ASSERTED,
|
|
822
|
-
form
|
|
823
|
-
};
|
|
824
|
-
const name = wireDisplayName(displayName);
|
|
825
|
-
if (name !== null) wire.display_name = name;
|
|
826
|
-
return wire;
|
|
827
|
-
}
|
|
828
|
-
|
|
829
1221
|
// src/integrations/mcp/llmText.ts
|
|
830
1222
|
var REPORT_POINTER_TEMPLATE = (vendorDisplayName, annotationToolName) => `Use \`${annotationToolName}\` to report a ${vendorDisplayName} tool call that went wrong, or a request no tool covers; its description says when and how.`;
|
|
831
1223
|
var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
|
|
@@ -897,14 +1289,14 @@ var OURS_STARTS = [
|
|
|
897
1289
|
];
|
|
898
1290
|
function endsInOurs(current2, vendor) {
|
|
899
1291
|
if (typeof current2 !== "string") return false;
|
|
900
|
-
const prefix = typeof vendor === "string" && vendor
|
|
1292
|
+
const prefix = typeof vendor === "string" && !isBlank(vendor) ? `${vendor}
|
|
901
1293
|
|
|
902
1294
|
` : "";
|
|
903
1295
|
if (!current2.startsWith(prefix)) return false;
|
|
904
1296
|
const rest = current2.slice(prefix.length);
|
|
905
1297
|
return OURS_STARTS.some((start) => start.test(rest));
|
|
906
1298
|
}
|
|
907
|
-
function withVendorInstructions(server, ours,
|
|
1299
|
+
function withVendorInstructions(server, ours, warn3 = (message) => process.stderr.write(message)) {
|
|
908
1300
|
const holder = server;
|
|
909
1301
|
const current2 = holder._instructions;
|
|
910
1302
|
let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
|
|
@@ -912,12 +1304,12 @@ function withVendorInstructions(server, ours, warn4 = (message) => process.stder
|
|
|
912
1304
|
vendor = current2;
|
|
913
1305
|
holder[VENDOR_INSTRUCTIONS] = vendor;
|
|
914
1306
|
}
|
|
915
|
-
if (typeof vendor !== "string" ||
|
|
1307
|
+
if (typeof vendor !== "string" || isBlank(vendor)) return ours;
|
|
916
1308
|
const combined = `${vendor}
|
|
917
1309
|
|
|
918
1310
|
${ours}`;
|
|
919
1311
|
if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
|
|
920
|
-
|
|
1312
|
+
warn3(
|
|
921
1313
|
`baton: the server instructions are ${combined.length} chars (yours ${vendor.length}, Baton's ${ours.length}); Claude Code cuts them at ~${CLAUDE_CODE_TRUNCATION_CAP}, so the end of Baton's text is lost there
|
|
922
1314
|
`
|
|
923
1315
|
);
|
|
@@ -931,17 +1323,17 @@ var SUFFIX = "_annotate";
|
|
|
931
1323
|
var SLUG_CAP = 30;
|
|
932
1324
|
var PLACEHOLDER_LITERALS = /* @__PURE__ */ new Set(["fastmcp", "mcp-server"]);
|
|
933
1325
|
var RANDOM_SUFFIX = /-[0-9a-f]{4}$/;
|
|
1326
|
+
var SEPARATORS = "\\x1c-\\x1f";
|
|
1327
|
+
var PYTHON_SPACE = new RegExp(`^[\\p{White_Space}${SEPARATORS}]$`, "u");
|
|
1328
|
+
function pythonStrip(value) {
|
|
1329
|
+
return stripEdges(value, PYTHON_SPACE);
|
|
1330
|
+
}
|
|
934
1331
|
function isLibraryPlaceholder(serverName, className) {
|
|
935
1332
|
const stripped = pythonStrip(serverName);
|
|
936
1333
|
if (PLACEHOLDER_LITERALS.has(stripped.toLowerCase())) return true;
|
|
937
1334
|
const stem = stripped.replace(RANDOM_SUFFIX, "");
|
|
938
1335
|
return stem !== stripped && stem === className;
|
|
939
1336
|
}
|
|
940
|
-
function warn(message) {
|
|
941
|
-
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
942
|
-
process.emitWarning(message);
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
1337
|
function usableServerName(read) {
|
|
946
1338
|
let name;
|
|
947
1339
|
let className;
|
|
@@ -1015,13 +1407,117 @@ async function emit(sink, build) {
|
|
|
1015
1407
|
try {
|
|
1016
1408
|
event = build();
|
|
1017
1409
|
} catch (err) {
|
|
1018
|
-
|
|
1410
|
+
PROCESS_DROPS.add("encode_failed");
|
|
1411
|
+
process.stderr.write(`baton: event construction failed; event dropped: ${printable(err)}
|
|
1019
1412
|
`);
|
|
1020
1413
|
return;
|
|
1021
1414
|
}
|
|
1022
1415
|
await safeWrite(sink, event);
|
|
1023
1416
|
}
|
|
1024
1417
|
|
|
1418
|
+
// src/identity.ts
|
|
1419
|
+
var PRINCIPAL_SOURCE_ASSERTED = "asserted";
|
|
1420
|
+
var PRINCIPAL_FORM_HASHED = "hashed";
|
|
1421
|
+
var PRINCIPAL_FORM_RAW = "raw";
|
|
1422
|
+
var PRINCIPAL_ID_MAX_LEN = 128;
|
|
1423
|
+
var DISPLAY_NAME_MAX_LEN = 128;
|
|
1424
|
+
function wireDisplayName(value) {
|
|
1425
|
+
if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
|
|
1426
|
+
if (LONE_SURROGATE.test(value) || value.includes("\0") || isBlank(value)) return null;
|
|
1427
|
+
return value;
|
|
1428
|
+
}
|
|
1429
|
+
var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
|
|
1430
|
+
var LONE_SURROGATE = /\p{Surrogate}/u;
|
|
1431
|
+
function usableId(id) {
|
|
1432
|
+
if (typeof id !== "string") return false;
|
|
1433
|
+
if (LONE_SURROGATE.test(id)) return false;
|
|
1434
|
+
if (id.includes("\0")) return false;
|
|
1435
|
+
return !isBlank(id);
|
|
1436
|
+
}
|
|
1437
|
+
function readIdentity(result, idKey) {
|
|
1438
|
+
if (result === null || typeof result !== "object") return null;
|
|
1439
|
+
const candidate = result;
|
|
1440
|
+
const id = candidate[idKey];
|
|
1441
|
+
if (!usableId(id)) return null;
|
|
1442
|
+
const displayName = typeof candidate.displayName === "string" ? candidate.displayName : void 0;
|
|
1443
|
+
return { id, form: candidate.form, displayName };
|
|
1444
|
+
}
|
|
1445
|
+
var NO_CALLER = Object.freeze({ principal: null, organization: null });
|
|
1446
|
+
function callerFor(result, warn3) {
|
|
1447
|
+
try {
|
|
1448
|
+
return readCaller(result, warn3);
|
|
1449
|
+
} catch {
|
|
1450
|
+
warn3("unreadable", "could not be read \u2014 sending neither principal nor organization.");
|
|
1451
|
+
return NO_CALLER;
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
function readCaller(result, warn3) {
|
|
1455
|
+
if (result === void 0 || result === null) return NO_CALLER;
|
|
1456
|
+
if (typeof result !== "object") {
|
|
1457
|
+
warn3("not-object", `got a ${typeof result}, not an object \u2014 sending neither principal nor organization.`);
|
|
1458
|
+
return NO_CALLER;
|
|
1459
|
+
}
|
|
1460
|
+
if (!("principalId" in result) && !("organization" in result)) {
|
|
1461
|
+
if ("organizationId" in result) {
|
|
1462
|
+
return { principal: null, organization: identityFor(result, "organization", warn3) };
|
|
1463
|
+
}
|
|
1464
|
+
if (typeof result.userId === "string") {
|
|
1465
|
+
warn3(
|
|
1466
|
+
"user-id",
|
|
1467
|
+
"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."
|
|
1468
|
+
);
|
|
1469
|
+
} else {
|
|
1470
|
+
warn3("no-id", "got an object with neither principalId nor organizationId \u2014 sending neither.");
|
|
1471
|
+
}
|
|
1472
|
+
return NO_CALLER;
|
|
1473
|
+
}
|
|
1474
|
+
if ("organizationId" in result) {
|
|
1475
|
+
warn3("flat-organization-id", "got principalId and organizationId side by side; put the company in `organization`.");
|
|
1476
|
+
}
|
|
1477
|
+
const nested = result.organization;
|
|
1478
|
+
return {
|
|
1479
|
+
principal: identityFor(result, "principal", warn3),
|
|
1480
|
+
organization: nested == null ? null : identityFor(nested, "organization", warn3)
|
|
1481
|
+
};
|
|
1482
|
+
}
|
|
1483
|
+
function identityFor(value, member, warn3) {
|
|
1484
|
+
const idKey = member === "principal" ? "principalId" : "organizationId";
|
|
1485
|
+
const identity = readIdentity(value, idKey);
|
|
1486
|
+
if (identity === null) {
|
|
1487
|
+
warn3(`${member}:id`, `${member} has no usable ${idKey} \u2014 sending no ${member}.`);
|
|
1488
|
+
return null;
|
|
1489
|
+
}
|
|
1490
|
+
return identityWire(
|
|
1491
|
+
identity.id,
|
|
1492
|
+
identity.form,
|
|
1493
|
+
identity.displayName,
|
|
1494
|
+
(form) => warn3(`${member}:form`, `${member} form ${describeForm(form)} is not registered \u2014 sending "raw".`)
|
|
1495
|
+
);
|
|
1496
|
+
}
|
|
1497
|
+
function describeForm(form) {
|
|
1498
|
+
return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
|
|
1499
|
+
}
|
|
1500
|
+
function identityWire(id, stated, displayName, onUnregisteredForm) {
|
|
1501
|
+
let form = PRINCIPAL_FORM_RAW;
|
|
1502
|
+
if (stated !== void 0) {
|
|
1503
|
+
if (PRINCIPAL_FORMS.has(stated)) {
|
|
1504
|
+
form = stated;
|
|
1505
|
+
} else {
|
|
1506
|
+
onUnregisteredForm?.(stated);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
const wire = {
|
|
1510
|
+
// `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
|
|
1511
|
+
// an astral id cut at the boundary would ship a lone surrogate.
|
|
1512
|
+
id: capCodePoints(id, PRINCIPAL_ID_MAX_LEN),
|
|
1513
|
+
source: PRINCIPAL_SOURCE_ASSERTED,
|
|
1514
|
+
form
|
|
1515
|
+
};
|
|
1516
|
+
const name = wireDisplayName(displayName);
|
|
1517
|
+
if (name !== null) wire.display_name = name;
|
|
1518
|
+
return wire;
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1025
1521
|
// src/integrations/mcp/mcpTypes.ts
|
|
1026
1522
|
function extraAuthInfo(extra) {
|
|
1027
1523
|
const found = extra.authInfo ?? extra.http?.authInfo;
|
|
@@ -1079,24 +1575,14 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
|
1079
1575
|
};
|
|
1080
1576
|
}
|
|
1081
1577
|
var HOOK_TIMEOUT_MS = 5e3;
|
|
1082
|
-
var TIMED_OUT = /* @__PURE__ */ Symbol("hookTimedOut");
|
|
1083
1578
|
async function withinHookBudget(answer) {
|
|
1084
1579
|
if (!isThenable(answer)) return answer;
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
const first = await Promise.race([answer, deadline]);
|
|
1092
|
-
if (first !== TIMED_OUT) return first;
|
|
1093
|
-
warn(
|
|
1094
|
-
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
1095
|
-
);
|
|
1096
|
-
return null;
|
|
1097
|
-
} finally {
|
|
1098
|
-
clearTimeout(timer);
|
|
1099
|
-
}
|
|
1580
|
+
const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);
|
|
1581
|
+
if (first !== TIMED_OUT) return first;
|
|
1582
|
+
warn(
|
|
1583
|
+
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
1584
|
+
);
|
|
1585
|
+
return null;
|
|
1100
1586
|
}
|
|
1101
1587
|
var warned = /* @__PURE__ */ new Set();
|
|
1102
1588
|
function warnOnce(key, message) {
|
|
@@ -1125,7 +1611,7 @@ function scrubOrNull(scrubber, value, field) {
|
|
|
1125
1611
|
if (!warned2.has(field)) {
|
|
1126
1612
|
warned2.add(field);
|
|
1127
1613
|
process.stderr.write(
|
|
1128
|
-
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${
|
|
1614
|
+
`baton: scrubber threw on ${field}; that field is dropped, tool call continues. Further failures on this field will be silent: ${printable(err)}
|
|
1129
1615
|
`
|
|
1130
1616
|
);
|
|
1131
1617
|
}
|
|
@@ -1224,9 +1710,9 @@ function registeredHeaders(input) {
|
|
|
1224
1710
|
}
|
|
1225
1711
|
return out;
|
|
1226
1712
|
}
|
|
1227
|
-
function clientObservedFrom(clientInfo, headers, scrubber) {
|
|
1713
|
+
function clientObservedFrom(clientInfo, headers, scrubber, meta) {
|
|
1228
1714
|
return assemble(
|
|
1229
|
-
orNothing(() => cleanInfo(declared(clientInfo), scrubber)),
|
|
1715
|
+
orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),
|
|
1230
1716
|
orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
|
|
1231
1717
|
);
|
|
1232
1718
|
}
|
|
@@ -1234,16 +1720,19 @@ function clientObservedFrom(clientInfo, headers, scrubber) {
|
|
|
1234
1720
|
// src/integrations/mcp/sessionResolution.ts
|
|
1235
1721
|
async function resolveSessionId(fallbackSessionId, extra) {
|
|
1236
1722
|
if (typeof extra.sessionId === "string" && extra.sessionId) {
|
|
1237
|
-
return { sessionId: extra.sessionId, origin: "observed" };
|
|
1723
|
+
return { sessionId: extra.sessionId, origin: "observed", perCall: false };
|
|
1238
1724
|
}
|
|
1239
1725
|
const fromHeader = sessionIdFromHeader(extra);
|
|
1240
|
-
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed" };
|
|
1241
|
-
|
|
1726
|
+
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed", perCall: false };
|
|
1727
|
+
if (observeTransport(extra) === "http") {
|
|
1728
|
+
return { sessionId: `sdk-${uuid7()}`, origin: "minted", perCall: true };
|
|
1729
|
+
}
|
|
1730
|
+
return { sessionId: fallbackSessionId, origin: "minted", perCall: false };
|
|
1242
1731
|
}
|
|
1243
1732
|
function sessionIdFromHeader(extra) {
|
|
1244
1733
|
try {
|
|
1245
|
-
const value = extraHeaders(extra)?.get("mcp-session-id")
|
|
1246
|
-
return value ? value : null;
|
|
1734
|
+
const value = extraHeaders(extra)?.get("mcp-session-id");
|
|
1735
|
+
return value ? stripWhiteSpace(value) || null : null;
|
|
1247
1736
|
} catch {
|
|
1248
1737
|
return null;
|
|
1249
1738
|
}
|
|
@@ -1252,7 +1741,7 @@ function sessionIdFromHeader(extra) {
|
|
|
1252
1741
|
// src/integrations/mcp/annotation.ts
|
|
1253
1742
|
var TOOL_NAME_PARAM_NAME = "tool_name";
|
|
1254
1743
|
function isReport(whatHappened) {
|
|
1255
|
-
return typeof whatHappened === "string" && whatHappened
|
|
1744
|
+
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
1256
1745
|
}
|
|
1257
1746
|
function registerAnnotationTool(server, options) {
|
|
1258
1747
|
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
@@ -1295,7 +1784,7 @@ function registerAnnotationTool(server, options) {
|
|
|
1295
1784
|
meta ? roundMetaCoordinates(meta) : null,
|
|
1296
1785
|
"_meta"
|
|
1297
1786
|
);
|
|
1298
|
-
const
|
|
1787
|
+
const session = await resolveSessionId(options.fallbackSessionId, extra);
|
|
1299
1788
|
const caller = await resolveCaller(
|
|
1300
1789
|
options.resolvePrincipal,
|
|
1301
1790
|
{ extra, toolName: name, arguments: args }
|
|
@@ -1305,14 +1794,14 @@ function registerAnnotationTool(server, options) {
|
|
|
1305
1794
|
() => AnnotationEventSchema.parse({
|
|
1306
1795
|
tenant_id: options.tenantId,
|
|
1307
1796
|
vendor_id: options.vendorId,
|
|
1308
|
-
session_id: sessionId,
|
|
1309
|
-
sequence_number: options.counter.
|
|
1797
|
+
session_id: session.sessionId,
|
|
1798
|
+
sequence_number: options.counter.nextFor(session),
|
|
1310
1799
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1311
1800
|
consent_token: options.consentToken,
|
|
1312
1801
|
principal: caller.principal,
|
|
1313
1802
|
organization: caller.organization,
|
|
1314
1803
|
transport_observed: observeTransport(extra),
|
|
1315
|
-
session_id_origin: origin,
|
|
1804
|
+
session_id_origin: session.origin,
|
|
1316
1805
|
client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
|
|
1317
1806
|
runtime_meta: scrubbedMeta,
|
|
1318
1807
|
payload: {
|
|
@@ -1339,7 +1828,7 @@ function registerAnnotationTool(server, options) {
|
|
|
1339
1828
|
var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
|
|
1340
1829
|
var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
|
|
1341
1830
|
var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
|
|
1342
|
-
var NOT_IN_A_KEY = /[\x00\n\r]/;
|
|
1831
|
+
var NOT_IN_A_KEY = /[\x00\t\n\r]/;
|
|
1343
1832
|
var PUBLISHABLE_PREFIX = "baton_pk_";
|
|
1344
1833
|
var SECRET_PREFIX = "baton_sk_";
|
|
1345
1834
|
var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
|
|
@@ -1350,11 +1839,6 @@ function containsKey(value) {
|
|
|
1350
1839
|
return sweep(value) !== value;
|
|
1351
1840
|
}
|
|
1352
1841
|
var BARE_KEY_HINT = "this looks like a bare key, not a DSN \u2014 copy the full value from /account, which starts with https:// and ends with your server's name";
|
|
1353
|
-
function warn2(message) {
|
|
1354
|
-
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
1355
|
-
process.emitWarning(message);
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
1842
|
function splitDsn(raw) {
|
|
1359
1843
|
const schemeEnd = raw.indexOf("://");
|
|
1360
1844
|
if (schemeEnd === -1) return null;
|
|
@@ -1414,7 +1898,7 @@ function selectDsn(explicit, supplied, door) {
|
|
|
1414
1898
|
const ambient = dsnFromEnvironment();
|
|
1415
1899
|
if (ambient === void 0) return void 0;
|
|
1416
1900
|
if (conflicts.length > 0) {
|
|
1417
|
-
|
|
1901
|
+
warn(
|
|
1418
1902
|
`baton: BATON_DSN is set, but this ${door} supplies ${conflicts.join(", ")} directly, so BATON_DSN is being IGNORED and these events are NOT going to the collector it names. Remove the explicit value to use it, or unset BATON_DSN if it was meant for a different server.`
|
|
1419
1903
|
);
|
|
1420
1904
|
return void 0;
|
|
@@ -1422,10 +1906,8 @@ function selectDsn(explicit, supplied, door) {
|
|
|
1422
1906
|
return ambient;
|
|
1423
1907
|
}
|
|
1424
1908
|
function parseDsn(raw) {
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
}
|
|
1428
|
-
const dsn = raw.trim();
|
|
1909
|
+
const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
|
|
1910
|
+
if (dsn === "") fail("dsn must be a non-empty string");
|
|
1429
1911
|
if (looksLikeAKey(dsn)) {
|
|
1430
1912
|
fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
|
|
1431
1913
|
}
|
|
@@ -1451,7 +1933,7 @@ function parseDsn(raw) {
|
|
|
1451
1933
|
}
|
|
1452
1934
|
if (NOT_IN_A_KEY.test(key)) {
|
|
1453
1935
|
fail(
|
|
1454
|
-
`dsn ${safe} has a line break or a null inside its key \u2014
|
|
1936
|
+
`dsn ${safe} has a tab, a line break or a null inside its key \u2014 no key from /account contains one, so this DSN could not have worked. Check for a line wrap where the value was copied.`
|
|
1455
1937
|
);
|
|
1456
1938
|
}
|
|
1457
1939
|
if (key.includes(":")) {
|
|
@@ -1510,7 +1992,7 @@ function parseDsn(raw) {
|
|
|
1510
1992
|
);
|
|
1511
1993
|
}
|
|
1512
1994
|
if (key.startsWith(SECRET_PREFIX)) {
|
|
1513
|
-
|
|
1995
|
+
warn(
|
|
1514
1996
|
`baton: this DSN carries a ${SECRET_PREFIX} key (a workspace SECRET) where a ${PUBLISHABLE_PREFIX} key belongs. It will work. But if this server ships to anyone else, that key reads and writes everything the workspace holds \u2014 mint a publishable key at /account instead.`
|
|
1515
1997
|
);
|
|
1516
1998
|
}
|
|
@@ -1549,7 +2031,7 @@ function requestSideFailureKind(entry, validation) {
|
|
|
1549
2031
|
if (entry.enabled === false) return "tool_disabled";
|
|
1550
2032
|
if (validation === "rejected") return "invalid_argument";
|
|
1551
2033
|
if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
|
|
1552
|
-
return
|
|
2034
|
+
return REFUSED;
|
|
1553
2035
|
}
|
|
1554
2036
|
var ERROR_BODY_MAX_CODE_POINTS = 2e3;
|
|
1555
2037
|
function isErrorResult(value) {
|
|
@@ -1568,7 +2050,7 @@ function errorText(value) {
|
|
|
1568
2050
|
for (const part of content) {
|
|
1569
2051
|
const text = part?.text;
|
|
1570
2052
|
if (typeof text !== "string") continue;
|
|
1571
|
-
const trimmed = text
|
|
2053
|
+
const trimmed = stripWhiteSpace(text);
|
|
1572
2054
|
if (trimmed) parts.push(trimmed);
|
|
1573
2055
|
}
|
|
1574
2056
|
} catch {
|
|
@@ -1748,7 +2230,7 @@ var SWITCH = "BATON_DISABLED";
|
|
|
1748
2230
|
var OFF_VALUES = /* @__PURE__ */ new Set(["", "0", "false", "no", "off"]);
|
|
1749
2231
|
function captureDisabled() {
|
|
1750
2232
|
const value = typeof process !== "undefined" ? process.env?.[SWITCH] : void 0;
|
|
1751
|
-
if (value !== void 0 && !OFF_VALUES.has(value
|
|
2233
|
+
if (value !== void 0 && !OFF_VALUES.has(stripWhiteSpace(value).toLowerCase())) {
|
|
1752
2234
|
return SWITCH;
|
|
1753
2235
|
}
|
|
1754
2236
|
return null;
|
|
@@ -1779,9 +2261,9 @@ var DisabledSink = class {
|
|
|
1779
2261
|
var BatonHandle = class {
|
|
1780
2262
|
sink;
|
|
1781
2263
|
vendorId;
|
|
1782
|
-
/**
|
|
1783
|
-
* when no
|
|
1784
|
-
*
|
|
2264
|
+
/** The install's own session id: what stdio and in-memory calls, and the
|
|
2265
|
+
* surface snapshot, carry when no session id resolves. A call over HTTP
|
|
2266
|
+
* with no session to read gets a per-request id instead (SPEC §3.4 rung 5). */
|
|
1785
2267
|
sessionId;
|
|
1786
2268
|
/** The resolved annotation tool name: `BatonConfig.annotationToolName` if
|
|
1787
2269
|
* set, else derived from the server's own name (`{slug}_annotate`), else
|
|
@@ -1793,19 +2275,25 @@ var BatonHandle = class {
|
|
|
1793
2275
|
this.sessionId = options.sessionId;
|
|
1794
2276
|
this.annotationToolName = options.annotationToolName;
|
|
1795
2277
|
}
|
|
1796
|
-
/** Flush any pending events held by the sink.
|
|
2278
|
+
/** Flush any pending events held by the sink. Never rejects; returns within
|
|
2279
|
+
* the shutdown budget (SPEC §11.2 rule 7). */
|
|
1797
2280
|
async flush() {
|
|
1798
|
-
await this.sink
|
|
2281
|
+
await boundedSinkCall(this.sink, "flush");
|
|
1799
2282
|
}
|
|
1800
|
-
/** Flush and release sink resources
|
|
2283
|
+
/** Flush and release sink resources, on the same terms as `flush()`. */
|
|
1801
2284
|
async aclose() {
|
|
1802
|
-
await this.sink
|
|
2285
|
+
await boundedSinkCall(this.sink, "aclose");
|
|
1803
2286
|
}
|
|
1804
2287
|
};
|
|
1805
2288
|
|
|
1806
2289
|
// src/integrations/mcp/sessionCounter.ts
|
|
1807
2290
|
var SessionCounter = class {
|
|
1808
2291
|
counters = /* @__PURE__ */ new Map();
|
|
2292
|
+
/** A per-call session is numbered by the clock: a counter would keep an
|
|
2293
|
+
* entry for every request the process serves. */
|
|
2294
|
+
nextFor(session) {
|
|
2295
|
+
return session.perCall ? nextClockSequence() : this.next(session.sessionId);
|
|
2296
|
+
}
|
|
1809
2297
|
next(sessionId) {
|
|
1810
2298
|
const current2 = this.counters.get(sessionId) ?? 0;
|
|
1811
2299
|
const next = current2 + 1;
|
|
@@ -1892,6 +2380,7 @@ function toJsonSchemaCompat(schema, opts) {
|
|
|
1892
2380
|
// src/integrations/mcp/schemaCompat.ts
|
|
1893
2381
|
import { z as zV4 } from "zod";
|
|
1894
2382
|
import { z as zV3 } from "zod/v3";
|
|
2383
|
+
var DEFAULT_INTENT_PARAM_MODE = "required";
|
|
1895
2384
|
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
1896
2385
|
function injectGoalParams(inputSchema, intentParamMode) {
|
|
1897
2386
|
const objSchema = normalizeObjectSchema(inputSchema);
|
|
@@ -1970,9 +2459,9 @@ function surfaceHash(surface) {
|
|
|
1970
2459
|
}
|
|
1971
2460
|
function canonicalJson(value) {
|
|
1972
2461
|
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1973
|
-
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
2462
|
+
if (Array.isArray(value)) return `[${value.map((v) => v === void 0 ? "null" : canonicalJson(v)).join(",")}]`;
|
|
1974
2463
|
const record = value;
|
|
1975
|
-
const keys = Object.keys(record).sort();
|
|
2464
|
+
const keys = Object.keys(record).filter((k) => record[k] !== void 0).sort();
|
|
1976
2465
|
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(record[k])}`).join(",")}}`;
|
|
1977
2466
|
}
|
|
1978
2467
|
function buildServerMeta(lowlevelServer) {
|
|
@@ -1994,6 +2483,25 @@ function assembleSurface(serverMeta, tools) {
|
|
|
1994
2483
|
tools
|
|
1995
2484
|
};
|
|
1996
2485
|
}
|
|
2486
|
+
var SENT_SURFACES_CAP = 256;
|
|
2487
|
+
var SentSurfaces = class {
|
|
2488
|
+
hashes = /* @__PURE__ */ new Set();
|
|
2489
|
+
wasSent(digest) {
|
|
2490
|
+
if (!this.hashes.has(digest)) return false;
|
|
2491
|
+
this.hashes.delete(digest);
|
|
2492
|
+
this.hashes.add(digest);
|
|
2493
|
+
return true;
|
|
2494
|
+
}
|
|
2495
|
+
mark(digest) {
|
|
2496
|
+
this.hashes.add(digest);
|
|
2497
|
+
if (this.hashes.size > SENT_SURFACES_CAP) {
|
|
2498
|
+
this.hashes.delete(this.hashes.values().next().value);
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
unmark(digest) {
|
|
2502
|
+
this.hashes.delete(digest);
|
|
2503
|
+
}
|
|
2504
|
+
};
|
|
1997
2505
|
function buildSeamAugmentations(options) {
|
|
1998
2506
|
return {
|
|
1999
2507
|
injected_tools: [...options.injectedToolNames].sort(),
|
|
@@ -2012,12 +2520,12 @@ var wired = /* @__PURE__ */ new WeakSet();
|
|
|
2012
2520
|
var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
|
|
2013
2521
|
var callSlots = new AsyncLocalStorage();
|
|
2014
2522
|
var SurfaceState = class {
|
|
2015
|
-
constructor(serverMeta,
|
|
2523
|
+
constructor(serverMeta, sentSurfaces) {
|
|
2016
2524
|
this.serverMeta = serverMeta;
|
|
2017
|
-
this.
|
|
2525
|
+
this.sentSurfaces = sentSurfaces;
|
|
2018
2526
|
}
|
|
2019
2527
|
serverMeta;
|
|
2020
|
-
|
|
2528
|
+
sentSurfaces;
|
|
2021
2529
|
/** Every tool this install has seen, keyed by its CURRENT name. `disabled`
|
|
2022
2530
|
* is tracked alongside rather than pruned, so re-enabling costs nothing and
|
|
2023
2531
|
* — crucially — never needs a re-capture, which would re-read Baton's own
|
|
@@ -2074,7 +2582,7 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
2074
2582
|
}
|
|
2075
2583
|
async function openCall(ctx, toolName, extra, params, retired, registered = true) {
|
|
2076
2584
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
2077
|
-
const {
|
|
2585
|
+
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
2078
2586
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
2079
2587
|
const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
|
|
2080
2588
|
const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
|
|
@@ -2088,7 +2596,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2088
2596
|
const common = {
|
|
2089
2597
|
tenant_id: ctx.tenantId,
|
|
2090
2598
|
vendor_id: ctx.vendorId,
|
|
2091
|
-
session_id: sessionId,
|
|
2599
|
+
session_id: session.sessionId,
|
|
2092
2600
|
consent_token: ctx.consentToken,
|
|
2093
2601
|
// Every `...common` site is an event of this call, so `call_id` rides in
|
|
2094
2602
|
// it. `surface_snapshot` is deliberately not among them: it describes the
|
|
@@ -2097,7 +2605,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2097
2605
|
principal: caller.principal,
|
|
2098
2606
|
organization: caller.organization,
|
|
2099
2607
|
transport_observed: observeTransport(extra),
|
|
2100
|
-
session_id_origin: origin,
|
|
2608
|
+
session_id_origin: session.origin,
|
|
2101
2609
|
client_observed: observeClient(extra, ctx),
|
|
2102
2610
|
runtime_meta: scrubbedMeta,
|
|
2103
2611
|
call_id: uuid7()
|
|
@@ -2106,7 +2614,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2106
2614
|
ctx.sink,
|
|
2107
2615
|
() => ToolCallStartEventSchema.parse({
|
|
2108
2616
|
...common,
|
|
2109
|
-
sequence_number: ctx.counter.
|
|
2617
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2110
2618
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2111
2619
|
payload: {
|
|
2112
2620
|
tool_name: toolName,
|
|
@@ -2119,7 +2627,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2119
2627
|
}
|
|
2120
2628
|
})
|
|
2121
2629
|
);
|
|
2122
|
-
return { common,
|
|
2630
|
+
return { common, session };
|
|
2123
2631
|
}
|
|
2124
2632
|
function batonWrap(nameRef, original, ctx) {
|
|
2125
2633
|
return async (...callArgs) => {
|
|
@@ -2130,7 +2638,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2130
2638
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
2131
2639
|
const retired = slot?.retired ?? {};
|
|
2132
2640
|
if (slot) slot.retired = {};
|
|
2133
|
-
const { common,
|
|
2641
|
+
const { common, session } = await openCall(ctx, toolName, extra, params, retired);
|
|
2134
2642
|
const terminate = async (build, replacement) => {
|
|
2135
2643
|
if (!slot) {
|
|
2136
2644
|
await emit(ctx.sink, build);
|
|
@@ -2156,18 +2664,20 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2156
2664
|
await parkFailure(
|
|
2157
2665
|
() => ToolCallErrorEventSchema.parse({
|
|
2158
2666
|
...common,
|
|
2159
|
-
sequence_number: ctx.counter.
|
|
2667
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2160
2668
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2161
2669
|
payload: {
|
|
2162
2670
|
tool_name: toolName,
|
|
2163
2671
|
error_type: errorTypeOf(err),
|
|
2164
|
-
//
|
|
2165
|
-
//
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2672
|
+
// SPEC §11.4.3(1): the MCP SDK has no tool-error class to mark a
|
|
2673
|
+
// raised message public, so under "off" every one is withheld.
|
|
2674
|
+
...resultDerivedFields(
|
|
2675
|
+
ctx.resultCaptureMode,
|
|
2676
|
+
() => messageOf(err),
|
|
2677
|
+
null,
|
|
2678
|
+
(text) => errorBody(ctx, text),
|
|
2679
|
+
ctx.scrubber
|
|
2680
|
+
),
|
|
2171
2681
|
duration_ms: durationMs2,
|
|
2172
2682
|
// Explicit, though the field is `.optional()` and this is its
|
|
2173
2683
|
// absent value. The schema is deliberately not an emitter (see
|
|
@@ -2191,7 +2701,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2191
2701
|
await parkFailure(
|
|
2192
2702
|
() => ToolCallErrorEventSchema.parse({
|
|
2193
2703
|
...common,
|
|
2194
|
-
sequence_number: ctx.counter.
|
|
2704
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2195
2705
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2196
2706
|
payload: {
|
|
2197
2707
|
tool_name: toolName,
|
|
@@ -2221,7 +2731,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2221
2731
|
await parkSuccess(
|
|
2222
2732
|
() => ToolCallEndEventSchema.parse({
|
|
2223
2733
|
...common,
|
|
2224
|
-
sequence_number: ctx.counter.
|
|
2734
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2225
2735
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2226
2736
|
payload: {
|
|
2227
2737
|
tool_name: toolName,
|
|
@@ -2237,7 +2747,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2237
2747
|
// CALLER saw fail, which is a success the product invented.
|
|
2238
2748
|
(outcome) => ToolCallErrorEventSchema.parse({
|
|
2239
2749
|
...common,
|
|
2240
|
-
sequence_number: ctx.counter.
|
|
2750
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2241
2751
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2242
2752
|
payload: {
|
|
2243
2753
|
tool_name: toolName,
|
|
@@ -2304,7 +2814,7 @@ function popText(args, paramName) {
|
|
|
2304
2814
|
if (!(paramName in args)) return null;
|
|
2305
2815
|
const raw = args[paramName];
|
|
2306
2816
|
delete args[paramName];
|
|
2307
|
-
return typeof raw === "string" && raw
|
|
2817
|
+
return typeof raw === "string" && !isBlank(raw) ? raw : null;
|
|
2308
2818
|
}
|
|
2309
2819
|
function stripRetiredParams(params, ctx) {
|
|
2310
2820
|
const toolName = params?.name;
|
|
@@ -2320,7 +2830,6 @@ function stripRetiredParams(params, ctx) {
|
|
|
2320
2830
|
}
|
|
2321
2831
|
return retired;
|
|
2322
2832
|
}
|
|
2323
|
-
var MAX_REMEMBERED_SURFACES = 1024;
|
|
2324
2833
|
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
2325
2834
|
if (!ctx.surfaceState.dirty) return;
|
|
2326
2835
|
ctx.surfaceState.dirty = false;
|
|
@@ -2334,10 +2843,9 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2334
2843
|
`);
|
|
2335
2844
|
return;
|
|
2336
2845
|
}
|
|
2337
|
-
const
|
|
2338
|
-
if (
|
|
2339
|
-
|
|
2340
|
-
emitted.add(digest);
|
|
2846
|
+
const sent = ctx.surfaceState.sentSurfaces;
|
|
2847
|
+
if (sent.wasSent(digest)) return;
|
|
2848
|
+
sent.mark(digest);
|
|
2341
2849
|
const seam = buildSeamAugmentations({
|
|
2342
2850
|
injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
|
|
2343
2851
|
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
@@ -2350,7 +2858,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2350
2858
|
} catch (err) {
|
|
2351
2859
|
process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
|
|
2352
2860
|
`);
|
|
2353
|
-
|
|
2861
|
+
sent.unmark(digest);
|
|
2354
2862
|
ctx.surfaceState.dirty = true;
|
|
2355
2863
|
}
|
|
2356
2864
|
}
|
|
@@ -2445,7 +2953,7 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2445
2953
|
ctx.sink,
|
|
2446
2954
|
() => schema.parse({
|
|
2447
2955
|
...opened.common,
|
|
2448
|
-
sequence_number: ctx.counter.
|
|
2956
|
+
sequence_number: ctx.counter.nextFor(opened.session),
|
|
2449
2957
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2450
2958
|
payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload })
|
|
2451
2959
|
})
|
|
@@ -2477,26 +2985,26 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2477
2985
|
}
|
|
2478
2986
|
async function openLifecycleCall(ctx, spec, requestParams, extra) {
|
|
2479
2987
|
try {
|
|
2480
|
-
const
|
|
2988
|
+
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
2481
2989
|
const caller = await resolveCaller(ctx.resolvePrincipal, {
|
|
2482
2990
|
extra,
|
|
2483
2991
|
toolName: null,
|
|
2484
2992
|
arguments: {}
|
|
2485
2993
|
});
|
|
2486
2994
|
return {
|
|
2487
|
-
|
|
2995
|
+
session,
|
|
2488
2996
|
subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
|
|
2489
2997
|
common: {
|
|
2490
2998
|
tenant_id: ctx.tenantId,
|
|
2491
2999
|
vendor_id: ctx.vendorId,
|
|
2492
|
-
session_id:
|
|
3000
|
+
session_id: session.sessionId,
|
|
2493
3001
|
consent_token: ctx.consentToken,
|
|
2494
3002
|
principal: caller.principal,
|
|
2495
3003
|
organization: caller.organization,
|
|
2496
3004
|
transport_observed: observeTransport(extra),
|
|
2497
|
-
session_id_origin:
|
|
3005
|
+
session_id_origin: session.origin,
|
|
2498
3006
|
client_observed: observeClient(extra, ctx),
|
|
2499
|
-
runtime_meta:
|
|
3007
|
+
runtime_meta: scrubbedMeta
|
|
2500
3008
|
}
|
|
2501
3009
|
};
|
|
2502
3010
|
} catch (err) {
|
|
@@ -2625,7 +3133,7 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
2625
3133
|
innerFired: false,
|
|
2626
3134
|
flushTerminal: null,
|
|
2627
3135
|
retired: stripRetiredParams(request?.params, ctx),
|
|
2628
|
-
validation:
|
|
3136
|
+
validation: "unseen"
|
|
2629
3137
|
};
|
|
2630
3138
|
let outcome = CLEAN_OUTCOME;
|
|
2631
3139
|
try {
|
|
@@ -2645,8 +3153,7 @@ var VALIDATION_PROBE = /* @__PURE__ */ Symbol("baton.validationProbe");
|
|
|
2645
3153
|
function installValidationProbe(server) {
|
|
2646
3154
|
const target = server;
|
|
2647
3155
|
const original = target.validateToolInput;
|
|
2648
|
-
if (typeof original !== "function"
|
|
2649
|
-
if (original[VALIDATION_PROBE]) return () => target.validateToolInput === original;
|
|
3156
|
+
if (typeof original !== "function" || original[VALIDATION_PROBE]) return;
|
|
2650
3157
|
const probe = async function(...args) {
|
|
2651
3158
|
const slot = callSlots.getStore();
|
|
2652
3159
|
try {
|
|
@@ -2660,7 +3167,6 @@ function installValidationProbe(server) {
|
|
|
2660
3167
|
};
|
|
2661
3168
|
Object.assign(probe, { [VALIDATION_PROBE]: true });
|
|
2662
3169
|
target.validateToolInput = probe;
|
|
2663
|
-
return () => target.validateToolInput === probe;
|
|
2664
3170
|
}
|
|
2665
3171
|
async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
2666
3172
|
try {
|
|
@@ -2674,6 +3180,7 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
|
2674
3180
|
if (!outcome.failed) return;
|
|
2675
3181
|
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
|
|
2676
3182
|
} catch (err) {
|
|
3183
|
+
PROCESS_DROPS.add("encode_failed");
|
|
2677
3184
|
process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
|
|
2678
3185
|
`);
|
|
2679
3186
|
}
|
|
@@ -2686,7 +3193,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
2686
3193
|
const entry = toolEntry(toolName);
|
|
2687
3194
|
if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
|
|
2688
3195
|
const params = { ...request?.params?.arguments ?? {} };
|
|
2689
|
-
const { common,
|
|
3196
|
+
const { common, session } = await openCall(
|
|
2690
3197
|
ctx,
|
|
2691
3198
|
toolName,
|
|
2692
3199
|
args[1],
|
|
@@ -2700,7 +3207,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
2700
3207
|
ctx.sink,
|
|
2701
3208
|
() => ToolCallErrorEventSchema.parse({
|
|
2702
3209
|
...common,
|
|
2703
|
-
sequence_number: ctx.counter.
|
|
3210
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2704
3211
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2705
3212
|
payload: {
|
|
2706
3213
|
tool_name: toolName,
|
|
@@ -2816,15 +3323,19 @@ function withBaton(server, supplied = {}) {
|
|
|
2816
3323
|
}
|
|
2817
3324
|
const resolved = resolveBatonConfig(supplied);
|
|
2818
3325
|
warnUnusedReportSettings(resolved);
|
|
2819
|
-
return install(server, supplied, resolved,
|
|
3326
|
+
return install(server, supplied, resolved, new SentSurfaces(), /* @__PURE__ */ new Set());
|
|
2820
3327
|
}
|
|
2821
3328
|
function createBaton(supplied = {}) {
|
|
2822
3329
|
const disabledBy = captureDisabled();
|
|
2823
3330
|
if (disabledBy !== null) {
|
|
2824
3331
|
logDisabled(disabledBy, "createBaton");
|
|
2825
3332
|
const unused = supplied.sink ?? new DisabledSink();
|
|
2826
|
-
return {
|
|
2827
|
-
|
|
3333
|
+
return {
|
|
3334
|
+
wrap: () => {
|
|
3335
|
+
},
|
|
3336
|
+
flush: () => boundedSinkCall(unused, "flush"),
|
|
3337
|
+
aclose: () => boundedSinkCall(unused, "aclose")
|
|
3338
|
+
};
|
|
2828
3339
|
}
|
|
2829
3340
|
const resolved = resolveBatonConfig(supplied);
|
|
2830
3341
|
warnUnusedReportSettings(resolved);
|
|
@@ -2835,17 +3346,17 @@ function createBaton(supplied = {}) {
|
|
|
2835
3346
|
sink,
|
|
2836
3347
|
tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
|
|
2837
3348
|
};
|
|
2838
|
-
const
|
|
3349
|
+
const sentSurfaces = new SentSurfaces();
|
|
2839
3350
|
const warned3 = /* @__PURE__ */ new Set();
|
|
2840
3351
|
return {
|
|
2841
3352
|
wrap: (server) => {
|
|
2842
|
-
install(server, supplied, config,
|
|
3353
|
+
install(server, supplied, config, sentSurfaces, warned3);
|
|
2843
3354
|
},
|
|
2844
|
-
flush: () => sink
|
|
2845
|
-
aclose: () => sink
|
|
3355
|
+
flush: () => boundedSinkCall(sink, "flush"),
|
|
3356
|
+
aclose: () => boundedSinkCall(sink, "aclose")
|
|
2846
3357
|
};
|
|
2847
3358
|
}
|
|
2848
|
-
function install(server, supplied, resolved,
|
|
3359
|
+
function install(server, supplied, resolved, sentSurfaces, warned3) {
|
|
2849
3360
|
const internals = server;
|
|
2850
3361
|
const serverName = usableServerName(() => ({
|
|
2851
3362
|
name: internals.server._serverInfo?.name,
|
|
@@ -2855,13 +3366,13 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
|
|
|
2855
3366
|
const sink = config.sink ?? new StdoutSink();
|
|
2856
3367
|
const reports = reportsFor(config);
|
|
2857
3368
|
const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
|
|
2858
|
-
const intentParamMode = config.intentParamMode ??
|
|
3369
|
+
const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
|
|
2859
3370
|
const counter2 = new SessionCounter();
|
|
2860
3371
|
const fallbackSessionId = `sdk-${uuid7()}`;
|
|
2861
3372
|
const tenantId = resolveTenantId(config.tenantId, config.vendorId);
|
|
2862
3373
|
const scrubber = config.scrubber ?? new Scrubber().scrub;
|
|
2863
3374
|
const serverMeta = buildServerMeta(server.server);
|
|
2864
|
-
const surfaceState = new SurfaceState(serverMeta,
|
|
3375
|
+
const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
|
|
2865
3376
|
const emitSurface = async (sessionId, digest, snapshot) => {
|
|
2866
3377
|
const event = SurfaceSnapshotEventSchema.parse({
|
|
2867
3378
|
tenant_id: tenantId,
|
|
@@ -2927,6 +3438,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
|
|
|
2927
3438
|
return { type: "object", properties: {} };
|
|
2928
3439
|
}
|
|
2929
3440
|
};
|
|
3441
|
+
installValidationProbe(server);
|
|
2930
3442
|
const ctx = {
|
|
2931
3443
|
sink,
|
|
2932
3444
|
counter: counter2,
|
|
@@ -2939,7 +3451,6 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned3) {
|
|
|
2939
3451
|
annotationToolName,
|
|
2940
3452
|
intentParamMode,
|
|
2941
3453
|
resultCaptureMode: config.resultCaptureMode ?? "full",
|
|
2942
|
-
validationProbeLive: installValidationProbe(server),
|
|
2943
3454
|
paramRegistry: /* @__PURE__ */ new Map(),
|
|
2944
3455
|
resolvePrincipal: config.resolvePrincipal,
|
|
2945
3456
|
vendorToolJsonSchema,
|
|
@@ -3030,7 +3541,7 @@ function claimsOf(context) {
|
|
|
3030
3541
|
}
|
|
3031
3542
|
function stringClaim(claims, name) {
|
|
3032
3543
|
const value = claims[name];
|
|
3033
|
-
return typeof value === "string" &&
|
|
3544
|
+
return typeof value === "string" && !isBlank(value) ? value : null;
|
|
3034
3545
|
}
|
|
3035
3546
|
function principalFromOAuthSub(context) {
|
|
3036
3547
|
const claims = claimsOf(context);
|
|
@@ -3062,33 +3573,46 @@ function sessionEnvelope(session) {
|
|
|
3062
3573
|
principal: session.principal,
|
|
3063
3574
|
organization: session.organization,
|
|
3064
3575
|
client_observed: session.clientObserved,
|
|
3065
|
-
runtime_meta: session.
|
|
3576
|
+
runtime_meta: session.runtimeMeta
|
|
3066
3577
|
};
|
|
3067
3578
|
}
|
|
3068
|
-
function
|
|
3579
|
+
function warn2(message) {
|
|
3069
3580
|
process.stderr.write(`baton: ${message}
|
|
3070
3581
|
`);
|
|
3071
3582
|
}
|
|
3072
3583
|
function vendorId(name, value) {
|
|
3073
|
-
const cleaned = typeof value === "string" ?
|
|
3584
|
+
const cleaned = typeof value === "string" ? stripWhiteSpace(value) : "";
|
|
3074
3585
|
if (cleaned !== "") return cleaned;
|
|
3075
3586
|
if (value !== void 0 && value !== null) {
|
|
3076
|
-
|
|
3587
|
+
warn2(`${name} is not a non-blank string \u2014 ignoring it.`);
|
|
3077
3588
|
}
|
|
3078
3589
|
return null;
|
|
3079
3590
|
}
|
|
3080
3591
|
function blank(sessionId, origin) {
|
|
3081
|
-
return { sessionId, origin, ...NO_CALLER, clientObserved: null,
|
|
3592
|
+
return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
|
|
3593
|
+
}
|
|
3594
|
+
function requestMeta(meta) {
|
|
3595
|
+
if (isRecord(meta)) return meta;
|
|
3596
|
+
if (meta !== void 0 && meta !== null) warn2("meta is not an object \u2014 ignoring it.");
|
|
3597
|
+
return null;
|
|
3598
|
+
}
|
|
3599
|
+
function runtimeMeta(meta, turnId, scrubber) {
|
|
3600
|
+
const clientKeys = Object.fromEntries(Object.entries(meta ?? {}).filter(([key]) => key !== TURN_ID_META_KEY));
|
|
3601
|
+
const cleaned = Object.keys(clientKeys).length > 0 ? scrubOrNull(scrubber, roundMetaCoordinates(clientKeys), "_meta") : null;
|
|
3602
|
+
const out = isRecord(cleaned) ? { ...cleaned } : {};
|
|
3603
|
+
if (turnId !== null) out[TURN_ID_META_KEY] = turnId;
|
|
3604
|
+
return Object.keys(out).length > 0 ? out : null;
|
|
3082
3605
|
}
|
|
3083
3606
|
function newSession(values, scrubber, disabled) {
|
|
3084
3607
|
const id = vendorId("sessionId", values.sessionId);
|
|
3085
3608
|
const base = id !== null ? blank(id, "observed") : blank(uuid7(), "minted");
|
|
3086
3609
|
if (disabled) return base;
|
|
3610
|
+
const meta = requestMeta(values.meta);
|
|
3087
3611
|
return {
|
|
3088
3612
|
...base,
|
|
3089
|
-
...callerFor(values.principal, (_key, message) =>
|
|
3090
|
-
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber),
|
|
3091
|
-
|
|
3613
|
+
...callerFor(values.principal, (_key, message) => warn2(`principal ${message}`)),
|
|
3614
|
+
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber, meta),
|
|
3615
|
+
runtimeMeta: runtimeMeta(meta, vendorId("turnId", values.turnId), scrubber)
|
|
3092
3616
|
};
|
|
3093
3617
|
}
|
|
3094
3618
|
var current = new AsyncLocalStorage2();
|
|
@@ -3099,11 +3623,71 @@ function sessionForCall(owner) {
|
|
|
3099
3623
|
const entry = current.getStore();
|
|
3100
3624
|
return entry !== void 0 && entry.owner === owner ? entry.session : blank(uuid7(), "minted");
|
|
3101
3625
|
}
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3626
|
+
|
|
3627
|
+
// src/library/surface.ts
|
|
3628
|
+
function serveTools(tools, options) {
|
|
3629
|
+
let served;
|
|
3630
|
+
try {
|
|
3631
|
+
served = tools.map(servedEntry);
|
|
3632
|
+
} catch (err) {
|
|
3633
|
+
process.stderr.write(`baton: could not add user_goal to the tool list; serving it unchanged: ${printable(err)}
|
|
3634
|
+
`);
|
|
3635
|
+
return { served: tools, surface: null };
|
|
3636
|
+
}
|
|
3637
|
+
try {
|
|
3638
|
+
const nameOf = (tool) => isRecord(tool) ? String(tool.name) : "";
|
|
3639
|
+
const ordered = [...tools].sort((a, b) => {
|
|
3640
|
+
const [x, y] = [nameOf(a), nameOf(b)];
|
|
3641
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
3642
|
+
});
|
|
3643
|
+
const meta = {
|
|
3644
|
+
server_info: options.serverInfo ?? null,
|
|
3645
|
+
capabilities: options.capabilities ?? null,
|
|
3646
|
+
instructions: options.instructions ?? null
|
|
3647
|
+
};
|
|
3648
|
+
const surface = JSON.parse(
|
|
3649
|
+
JSON.stringify(assembleSurface(meta, ordered))
|
|
3650
|
+
);
|
|
3651
|
+
return { served, surface: { surface, digest: surfaceHash(surface) } };
|
|
3652
|
+
} catch (err) {
|
|
3653
|
+
process.stderr.write(`baton: surface snapshot capture failed: ${printable(err)}
|
|
3654
|
+
`);
|
|
3655
|
+
return { served, surface: null };
|
|
3656
|
+
}
|
|
3657
|
+
}
|
|
3658
|
+
function snapshotPayload({ surface, digest }) {
|
|
3659
|
+
return {
|
|
3660
|
+
surface_hash: digest,
|
|
3661
|
+
...surface,
|
|
3662
|
+
seam_augmentations: buildSeamAugmentations({
|
|
3663
|
+
injectedToolNames: [],
|
|
3664
|
+
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
3665
|
+
intentParamMode: DEFAULT_INTENT_PARAM_MODE,
|
|
3666
|
+
requiredParamNames: requiredParamNames(DEFAULT_INTENT_PARAM_MODE),
|
|
3667
|
+
instructionsSuffix: null
|
|
3668
|
+
})
|
|
3669
|
+
};
|
|
3670
|
+
}
|
|
3671
|
+
function servedEntry(tool) {
|
|
3672
|
+
if (!isRecord(tool)) return tool;
|
|
3673
|
+
const entry = { ...tool };
|
|
3674
|
+
if (isRecord(entry.inputSchema)) {
|
|
3675
|
+
const schema = { ...entry.inputSchema };
|
|
3676
|
+
if (isRecord(schema.properties)) schema.properties = { ...schema.properties };
|
|
3677
|
+
injectGoalParam(schema);
|
|
3678
|
+
entry.inputSchema = schema;
|
|
3679
|
+
}
|
|
3680
|
+
return entry;
|
|
3681
|
+
}
|
|
3682
|
+
function injectGoalParam(schema) {
|
|
3683
|
+
if (schema.properties === void 0) schema.properties = {};
|
|
3684
|
+
if (!isRecord(schema.properties) || declaresParam(schema, USER_GOAL_PARAM_NAME)) return;
|
|
3685
|
+
schema.properties[USER_GOAL_PARAM_NAME] = {
|
|
3686
|
+
type: "string",
|
|
3687
|
+
description: buildUserGoalParamDescription({ intentParamMode: DEFAULT_INTENT_PARAM_MODE })
|
|
3688
|
+
};
|
|
3689
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
3690
|
+
if (!required.includes(USER_GOAL_PARAM_NAME)) schema.required = [...required, USER_GOAL_PARAM_NAME];
|
|
3107
3691
|
}
|
|
3108
3692
|
|
|
3109
3693
|
// src/library/client.ts
|
|
@@ -3166,7 +3750,7 @@ function resolveClientOptions(options) {
|
|
|
3166
3750
|
resultCaptureMode
|
|
3167
3751
|
};
|
|
3168
3752
|
}
|
|
3169
|
-
var hasText2 = (value) => typeof value === "string" &&
|
|
3753
|
+
var hasText2 = (value) => typeof value === "string" && !isBlank(value);
|
|
3170
3754
|
function describeError(err) {
|
|
3171
3755
|
let type = "Error";
|
|
3172
3756
|
let body = "";
|
|
@@ -3180,19 +3764,18 @@ function describeError(err) {
|
|
|
3180
3764
|
}
|
|
3181
3765
|
return [type, body];
|
|
3182
3766
|
}
|
|
3183
|
-
function isPlainObject3(value) {
|
|
3184
|
-
if (typeof value !== "object" || value === null) return false;
|
|
3185
|
-
const proto = Object.getPrototypeOf(value);
|
|
3186
|
-
return proto === Object.prototype || proto === null;
|
|
3187
|
-
}
|
|
3188
3767
|
function paramsOf(args) {
|
|
3189
|
-
if (args.length === 1 &&
|
|
3768
|
+
if (args.length === 1 && isPlainObject(args[0])) return args[0];
|
|
3190
3769
|
return args.length === 0 ? {} : { args };
|
|
3191
3770
|
}
|
|
3192
3771
|
var Core = class {
|
|
3193
3772
|
closed = false;
|
|
3194
3773
|
pending = /* @__PURE__ */ new Set();
|
|
3195
3774
|
closedWarned = false;
|
|
3775
|
+
// A snapshot describes the server, so it takes no block's session,
|
|
3776
|
+
// principal or client: SPEC §11.5.1's join must not count it.
|
|
3777
|
+
surfaceSessionId = uuid7();
|
|
3778
|
+
sentSurfaces = new SentSurfaces();
|
|
3196
3779
|
sink;
|
|
3197
3780
|
vendorId;
|
|
3198
3781
|
tenantId;
|
|
@@ -3225,6 +3808,7 @@ var Core = class {
|
|
|
3225
3808
|
live() {
|
|
3226
3809
|
if (this.disabled) return false;
|
|
3227
3810
|
if (!this.closed) return true;
|
|
3811
|
+
PROCESS_DROPS.add("after_close");
|
|
3228
3812
|
if (!this.closedWarned) {
|
|
3229
3813
|
this.closedWarned = true;
|
|
3230
3814
|
process.stderr.write("baton: Client is closed; further events are dropped.\n");
|
|
@@ -3233,19 +3817,69 @@ var Core = class {
|
|
|
3233
3817
|
}
|
|
3234
3818
|
/** Never rejects. Tracked so `flush()` can wait for it. */
|
|
3235
3819
|
emit(build) {
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3820
|
+
return this.track(emit(this.sink, build));
|
|
3821
|
+
}
|
|
3822
|
+
track(work) {
|
|
3823
|
+
const tracked = work.finally(() => this.pending.delete(tracked));
|
|
3824
|
+
this.pending.add(tracked);
|
|
3825
|
+
return tracked;
|
|
3826
|
+
}
|
|
3827
|
+
/** Sends `surface` unless this client already has. Never rejects; a failed
|
|
3828
|
+
* write unmarks it, so the next `listTools` tries again. A surface that does
|
|
3829
|
+
* not fit the schema stays marked: it would fail the same way every time. */
|
|
3830
|
+
sendSurface(surface) {
|
|
3831
|
+
if (this.sentSurfaces.wasSent(surface.digest) || !this.live()) return Promise.resolve();
|
|
3832
|
+
this.sentSurfaces.mark(surface.digest);
|
|
3833
|
+
let event;
|
|
3834
|
+
try {
|
|
3835
|
+
event = SurfaceSnapshotEventSchema.parse({
|
|
3836
|
+
tenant_id: this.tenantId,
|
|
3837
|
+
vendor_id: this.vendorId,
|
|
3838
|
+
session_id: this.surfaceSessionId,
|
|
3839
|
+
session_id_origin: "minted",
|
|
3840
|
+
sequence_number: nextClockSequence(),
|
|
3841
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3842
|
+
consent_token: this.consentToken,
|
|
3843
|
+
payload: snapshotPayload(surface)
|
|
3844
|
+
});
|
|
3845
|
+
} catch (err) {
|
|
3846
|
+
PROCESS_DROPS.add("encode_failed");
|
|
3847
|
+
process.stderr.write(`baton: surface snapshot dropped; it does not fit the schema: ${printable(err)}
|
|
3848
|
+
`);
|
|
3849
|
+
return Promise.resolve();
|
|
3850
|
+
}
|
|
3851
|
+
return this.track(
|
|
3852
|
+
(async () => {
|
|
3853
|
+
try {
|
|
3854
|
+
await this.sink.write(event);
|
|
3855
|
+
} catch (err) {
|
|
3856
|
+
process.stderr.write(`baton: surface snapshot not sent; will retry: ${printable(err)}
|
|
3857
|
+
`);
|
|
3858
|
+
this.sentSurfaces.unmark(surface.digest);
|
|
3859
|
+
}
|
|
3860
|
+
})()
|
|
3861
|
+
);
|
|
3239
3862
|
}
|
|
3240
|
-
|
|
3241
|
-
|
|
3863
|
+
/** Waits up to `ms` for pending events to reach the sink; with `untilEmpty`,
|
|
3864
|
+
* also for ones emitted while it waits. A write still pending when time runs
|
|
3865
|
+
* out is not waited on again, so one stuck write costs one wait. */
|
|
3866
|
+
async settleWithin(ms, untilEmpty) {
|
|
3867
|
+
const deadline = performance.now() + ms;
|
|
3868
|
+
do {
|
|
3869
|
+
const waiting = [...this.pending];
|
|
3870
|
+
if (await raceDeadline(Promise.allSettled(waiting), deadline - performance.now()) === TIMED_OUT) {
|
|
3871
|
+
const left = waiting.filter((write) => this.pending.delete(write));
|
|
3872
|
+
if (untilEmpty) PROCESS_DROPS.add("unsent_at_close", left.length);
|
|
3873
|
+
return;
|
|
3874
|
+
}
|
|
3875
|
+
} while (untilEmpty && this.pending.size > 0);
|
|
3242
3876
|
}
|
|
3243
3877
|
scrub(value, field) {
|
|
3244
3878
|
return scrubOrNull(this.scrubber, value, field);
|
|
3245
3879
|
}
|
|
3246
3880
|
annotate(session, consentToken, options) {
|
|
3247
3881
|
if (!this.live()) return Promise.resolve();
|
|
3248
|
-
const sequence =
|
|
3882
|
+
const sequence = nextClockSequence();
|
|
3249
3883
|
const text = (value) => value === void 0 ? null : this.scrubber(value);
|
|
3250
3884
|
return this.emit(
|
|
3251
3885
|
() => AnnotationEventSchema.parse({
|
|
@@ -3313,7 +3947,7 @@ var Trace = class _Trace {
|
|
|
3313
3947
|
try {
|
|
3314
3948
|
this.#result = this.#core.scrubber(result);
|
|
3315
3949
|
} catch (err) {
|
|
3316
|
-
process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${
|
|
3950
|
+
process.stderr.write(`baton: scrubber threw on a result; that call's end event is dropped: ${printable(err)}
|
|
3317
3951
|
`);
|
|
3318
3952
|
this.#result = SCRUB_FAILED;
|
|
3319
3953
|
}
|
|
@@ -3333,7 +3967,7 @@ var Trace = class _Trace {
|
|
|
3333
3967
|
#start() {
|
|
3334
3968
|
this.#startedAt = performance.now();
|
|
3335
3969
|
if (!this.#core.live()) return;
|
|
3336
|
-
const sequence =
|
|
3970
|
+
const sequence = nextClockSequence();
|
|
3337
3971
|
const o = this.#options;
|
|
3338
3972
|
const params = o.params === void 0 ? {} : this.#core.scrub(o.params, "params") ?? {};
|
|
3339
3973
|
const textOf = (value, field) => {
|
|
@@ -3362,7 +3996,7 @@ var Trace = class _Trace {
|
|
|
3362
3996
|
const durationMs = this.#durationMs();
|
|
3363
3997
|
if (!this.#core.live()) return;
|
|
3364
3998
|
if (this.#result === UNSET && this.#error === null) this.observed(value);
|
|
3365
|
-
const sequence =
|
|
3999
|
+
const sequence = nextClockSequence();
|
|
3366
4000
|
const error = this.#error;
|
|
3367
4001
|
if (error !== null) {
|
|
3368
4002
|
this.#emitError(sequence, error.type, error.body, durationMs);
|
|
@@ -3384,7 +4018,7 @@ var Trace = class _Trace {
|
|
|
3384
4018
|
#fail(err) {
|
|
3385
4019
|
const durationMs = this.#durationMs();
|
|
3386
4020
|
if (!this.#core.live()) return;
|
|
3387
|
-
this.#emitError(
|
|
4021
|
+
this.#emitError(nextClockSequence(), ...describeError(err), durationMs);
|
|
3388
4022
|
}
|
|
3389
4023
|
#emitError(sequence, type, body, durationMs) {
|
|
3390
4024
|
void this.#core.emit(
|
|
@@ -3460,7 +4094,7 @@ var Client = class {
|
|
|
3460
4094
|
try {
|
|
3461
4095
|
block = newSession(options, this.#core.scrubber, this.#core.disabled);
|
|
3462
4096
|
} catch (err) {
|
|
3463
|
-
process.stderr.write(`baton: session values could not be read; using a minted session: ${
|
|
4097
|
+
process.stderr.write(`baton: session values could not be read; using a minted session: ${printable(err)}
|
|
3464
4098
|
`);
|
|
3465
4099
|
block = newSession({}, this.#core.scrubber, this.#core.disabled);
|
|
3466
4100
|
}
|
|
@@ -3490,30 +4124,41 @@ var Client = class {
|
|
|
3490
4124
|
const given = options ?? {};
|
|
3491
4125
|
return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
|
|
3492
4126
|
}
|
|
3493
|
-
/**
|
|
4127
|
+
/** `tools`, the vendor's own `tools/list` entries, with `user_goal` added
|
|
4128
|
+
* to each `inputSchema` as `withBaton` adds it, and a `surface_snapshot`
|
|
4129
|
+
* of `tools` as passed, sent once per distinct surface. For a vendor
|
|
4130
|
+
* serving MCP itself (SPEC §5.6).
|
|
4131
|
+
*
|
|
4132
|
+
* Pass the tools before anything of Baton's is added, so the snapshot
|
|
4133
|
+
* describes the vendor's own surface. `options` holds the vendor's own
|
|
4134
|
+
* `initialize` values. The input is not changed. Never rejects over the
|
|
4135
|
+
* tool list: one it cannot read is returned as it came. Does not wait for
|
|
4136
|
+
* the snapshot to be sent; `flush()` does. */
|
|
4137
|
+
async listTools(tools, options = {}) {
|
|
4138
|
+
if (this.#core.disabled) return tools;
|
|
4139
|
+
const { served, surface } = serveTools(tools, options);
|
|
4140
|
+
if (surface !== null) void this.#core.sendSurface(surface);
|
|
4141
|
+
return served;
|
|
4142
|
+
}
|
|
4143
|
+
/** Wait for events so far to reach the sink, then flush it. Never rejects;
|
|
4144
|
+
* returns within the sink's shutdown budget plus 250 ms (SPEC §11.2 rule 7). */
|
|
3494
4145
|
async flush() {
|
|
3495
|
-
await this.#
|
|
3496
|
-
try {
|
|
3497
|
-
await this.#core.sink.flush();
|
|
3498
|
-
} catch (err) {
|
|
3499
|
-
process.stderr.write(`baton: sink.flush failed: ${String(err)}
|
|
3500
|
-
`);
|
|
3501
|
-
}
|
|
4146
|
+
await this.#settleThen("flush");
|
|
3502
4147
|
}
|
|
3503
4148
|
/** Flush, then close the sink. Later events are dropped. */
|
|
3504
4149
|
aclose() {
|
|
3505
|
-
this.#closing ??= this.#
|
|
4150
|
+
this.#closing ??= this.#settleThen("aclose");
|
|
3506
4151
|
return this.#closing;
|
|
3507
4152
|
}
|
|
3508
|
-
|
|
3509
|
-
|
|
3510
|
-
|
|
3511
|
-
|
|
3512
|
-
|
|
3513
|
-
|
|
3514
|
-
|
|
3515
|
-
|
|
3516
|
-
}
|
|
4153
|
+
/** One budget: events in flight get until its end to reach the sink, then
|
|
4154
|
+
* the sink gets the time left. */
|
|
4155
|
+
async #settleThen(method) {
|
|
4156
|
+
await boundedSinkCall(this.#core.sink, method, async (budgetMs) => {
|
|
4157
|
+
const deadline = performance.now() + budgetMs;
|
|
4158
|
+
await this.#core.settleWithin(budgetMs, method === "aclose");
|
|
4159
|
+
if (method === "aclose") this.#core.closed = true;
|
|
4160
|
+
await callWithin(this.#core.sink, method, Math.max(0, deadline - performance.now()));
|
|
4161
|
+
});
|
|
3517
4162
|
}
|
|
3518
4163
|
};
|
|
3519
4164
|
export {
|
|
@@ -3521,13 +4166,18 @@ export {
|
|
|
3521
4166
|
AnnotationPayloadSchema,
|
|
3522
4167
|
BatonHandle,
|
|
3523
4168
|
Client,
|
|
4169
|
+
ClientReportEventSchema,
|
|
4170
|
+
ClientReportPayloadSchema,
|
|
3524
4171
|
DEFAULT_CONSENT_TOKEN,
|
|
3525
4172
|
DEPTH_LIMIT,
|
|
4173
|
+
DEPTH_MARKER,
|
|
3526
4174
|
EventSchema,
|
|
3527
4175
|
EventTypeSchema,
|
|
4176
|
+
FileSink,
|
|
3528
4177
|
HttpSink,
|
|
3529
4178
|
INTENT_INSTRUCTIONS,
|
|
3530
4179
|
INTENT_PARAMS,
|
|
4180
|
+
MultiSink,
|
|
3531
4181
|
PRINCIPAL_FORM_HASHED,
|
|
3532
4182
|
PRINCIPAL_FORM_RAW,
|
|
3533
4183
|
PRINCIPAL_SOURCE_ASSERTED,
|