@goodtiming/baton-sdk 0.5.8 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -11
- package/dist/index.cjs +1071 -342
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +490 -34
- package/dist/index.d.ts +490 -34
- package/dist/index.js +1066 -342
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/version.ts
|
|
2
|
-
var SDK_VERSION = "ts-0.
|
|
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(),
|
|
@@ -144,6 +148,7 @@ var envelopeShape = {
|
|
|
144
148
|
// consumer names the client from `client_observed`.
|
|
145
149
|
agent_runtime: z.string().default("unknown"),
|
|
146
150
|
principal: PrincipalWireSchema.nullable().default(null),
|
|
151
|
+
organization: PrincipalWireSchema.nullable().default(null),
|
|
147
152
|
transport_observed: z.string().nullable().default(null),
|
|
148
153
|
session_id_origin: z.string().nullable().default(null),
|
|
149
154
|
client_observed: ClientObservedSchema.nullable().default(null),
|
|
@@ -156,6 +161,7 @@ var EventTypeSchema = z.enum([
|
|
|
156
161
|
"tool_call_error",
|
|
157
162
|
"annotation",
|
|
158
163
|
"surface_snapshot",
|
|
164
|
+
"client_report",
|
|
159
165
|
// The RESOURCE and PROMPT lifecycles (SPEC §11.4.4). Twelve types whose
|
|
160
166
|
// shapes were set by `baton-proxy`, which has been emitting all of them in
|
|
161
167
|
// production — see the payload schemas below.
|
|
@@ -265,6 +271,11 @@ var SurfaceSnapshotEventSchema = z.object({
|
|
|
265
271
|
event_type: z.literal("surface_snapshot").default("surface_snapshot"),
|
|
266
272
|
payload: SurfaceSnapshotPayloadSchema
|
|
267
273
|
}).strict();
|
|
274
|
+
var ClientReportEventSchema = z.object({
|
|
275
|
+
...envelopeShape,
|
|
276
|
+
event_type: z.literal("client_report").default("client_report"),
|
|
277
|
+
payload: ClientReportPayloadSchema
|
|
278
|
+
}).strict();
|
|
268
279
|
var ResourceListStartEventSchema = z.object({
|
|
269
280
|
...envelopeShape,
|
|
270
281
|
event_type: z.literal("resource_list_start").default("resource_list_start"),
|
|
@@ -346,6 +357,7 @@ var EventSchema = z.discriminatedUnion("event_type", [
|
|
|
346
357
|
ToolCallErrorEventSchema,
|
|
347
358
|
AnnotationEventSchema,
|
|
348
359
|
SurfaceSnapshotEventSchema,
|
|
360
|
+
ClientReportEventSchema,
|
|
349
361
|
ResourceListStartEventSchema,
|
|
350
362
|
ResourceListEndEventSchema,
|
|
351
363
|
ResourceListErrorEventSchema,
|
|
@@ -363,8 +375,33 @@ var EventSchema = z.discriminatedUnion("event_type", [
|
|
|
363
375
|
ToolListErrorEventSchema
|
|
364
376
|
]);
|
|
365
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
|
+
|
|
366
402
|
// src/scrub.ts
|
|
367
403
|
var DEPTH_LIMIT = 10;
|
|
404
|
+
var DEPTH_MARKER = "[REDACTED:depth-limit]";
|
|
368
405
|
var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
369
406
|
"email",
|
|
370
407
|
"phone",
|
|
@@ -375,16 +412,21 @@ var REDACT_FIELD_NAMES = /* @__PURE__ */ new Set([
|
|
|
375
412
|
"password",
|
|
376
413
|
"user_name"
|
|
377
414
|
]);
|
|
415
|
+
var WS_CHARS = String.raw` \t\n\r\f\u00a0`;
|
|
416
|
+
var PHONE_SEP = String.raw`[${WS_CHARS}\-.]`;
|
|
378
417
|
var PATTERNS = [
|
|
379
418
|
["jwt", /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g],
|
|
380
|
-
["bearer",
|
|
419
|
+
["bearer", new RegExp(String.raw`\bBearer[${WS_CHARS}]+[A-Za-z0-9_\-.+/=]{16,}`, "gi")],
|
|
381
420
|
["sk_key", /\bsk-[A-Za-z0-9_-]{20,}\b/g],
|
|
382
421
|
["aws_key", /\bAKIA[0-9A-Z]{16}\b/g],
|
|
383
422
|
["email", /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g],
|
|
384
423
|
// Phone: optional `+1`, optional area-code parens, separators
|
|
385
|
-
//
|
|
424
|
+
// `-`, `.` or `WS_CHARS`, 10 digits. Conservative — won't catch every
|
|
386
425
|
// international format, but won't trip on every 10-digit identifier.
|
|
387
|
-
[
|
|
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
|
+
]
|
|
388
430
|
];
|
|
389
431
|
var CC_CANDIDATE = /\b\d{13,19}\b/g;
|
|
390
432
|
function luhnValid(digits) {
|
|
@@ -399,13 +441,9 @@ function luhnValid(digits) {
|
|
|
399
441
|
}
|
|
400
442
|
return total % 10 === 0;
|
|
401
443
|
}
|
|
402
|
-
function isPlainObject(value) {
|
|
403
|
-
if (typeof value !== "object" || value === null) return false;
|
|
404
|
-
const proto = Object.getPrototypeOf(value);
|
|
405
|
-
return proto === Object.prototype || proto === null;
|
|
406
|
-
}
|
|
407
444
|
var Scrubber = class {
|
|
408
445
|
counts = /* @__PURE__ */ new Map();
|
|
446
|
+
warnedDepth = false;
|
|
409
447
|
/** Bound so `new Scrubber().scrub` can be passed as a bare function
|
|
410
448
|
* reference — the closest TS gets to Python's `__call__`. */
|
|
411
449
|
scrub = (value) => this.walk(value, 0, null);
|
|
@@ -416,8 +454,20 @@ var Scrubber = class {
|
|
|
416
454
|
bump(category) {
|
|
417
455
|
this.counts.set(category, this.count(category) + 1);
|
|
418
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
|
+
}
|
|
419
467
|
walk(value, depth, forceField) {
|
|
420
|
-
if (depth >= DEPTH_LIMIT)
|
|
468
|
+
if (depth >= DEPTH_LIMIT && (isPlainObject(value) || Array.isArray(value))) {
|
|
469
|
+
return this.pastTheDepthLimit();
|
|
470
|
+
}
|
|
421
471
|
if (isPlainObject(value)) {
|
|
422
472
|
const out = {};
|
|
423
473
|
for (const [k, v] of Object.entries(value)) {
|
|
@@ -458,14 +508,155 @@ function identityScrub(value) {
|
|
|
458
508
|
}
|
|
459
509
|
|
|
460
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;
|
|
461
611
|
async function safeWrite(sink, event) {
|
|
462
612
|
try {
|
|
463
613
|
await sink.write(event);
|
|
464
614
|
} catch (err) {
|
|
465
|
-
|
|
615
|
+
PROCESS_DROPS.add("write_failed");
|
|
616
|
+
process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
|
|
466
617
|
`);
|
|
467
618
|
}
|
|
468
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
|
+
}
|
|
469
660
|
var StdoutSink = class {
|
|
470
661
|
stream;
|
|
471
662
|
closed = false;
|
|
@@ -482,6 +673,57 @@ var StdoutSink = class {
|
|
|
482
673
|
this.closed = true;
|
|
483
674
|
}
|
|
484
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
|
+
};
|
|
485
727
|
var CircuitBreaker = class {
|
|
486
728
|
constructor(threshold, resetMs) {
|
|
487
729
|
this.threshold = threshold;
|
|
@@ -511,19 +753,43 @@ var HttpSink = class _HttpSink {
|
|
|
511
753
|
apiKey;
|
|
512
754
|
buffer = [];
|
|
513
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;
|
|
514
763
|
maxRetries;
|
|
515
764
|
backoffBaseMs;
|
|
516
765
|
backoffMaxMs;
|
|
517
766
|
circuit;
|
|
518
767
|
fetchImpl;
|
|
519
768
|
overflowWarned = false;
|
|
520
|
-
|
|
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;
|
|
521
778
|
drainChain = Promise.resolve();
|
|
522
|
-
|
|
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;
|
|
523
787
|
constructor(url, options) {
|
|
524
788
|
this.url = url.replace(/\/+$/, "");
|
|
525
789
|
this.apiKey = options.apiKey;
|
|
526
790
|
this.bufferSize = options.bufferSize ?? 1e3;
|
|
791
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
|
|
792
|
+
this.shutdownFlushTimeoutMs = shutdownFlushTimeoutOption(options.shutdownFlushTimeoutMs);
|
|
527
793
|
this.maxRetries = options.maxRetries ?? 3;
|
|
528
794
|
this.backoffBaseMs = options.backoffBaseMs ?? 100;
|
|
529
795
|
this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
|
|
@@ -539,9 +805,7 @@ var HttpSink = class _HttpSink {
|
|
|
539
805
|
* ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it
|
|
540
806
|
* hangs off `BatonHandle.sink` and off the resolved config, so
|
|
541
807
|
* `console.log(handle.sink)` or a structured logger serialising either one
|
|
542
|
-
*
|
|
543
|
-
* asserts the DSN's own string does not survive resolution: it does not, and
|
|
544
|
-
* 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 —
|
|
545
809
|
* `toJSON` for serialisers, the inspect symbol for `console.log`, and
|
|
546
810
|
* `Symbol.for` rather than importing `node:util`, since this package runs on
|
|
547
811
|
* runtimes that have no such module.
|
|
@@ -552,29 +816,84 @@ var HttpSink = class _HttpSink {
|
|
|
552
816
|
[/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
|
|
553
817
|
return this.toJSON();
|
|
554
818
|
}
|
|
819
|
+
get closed() {
|
|
820
|
+
return this.closing.signal.aborted;
|
|
821
|
+
}
|
|
555
822
|
async write(event) {
|
|
556
823
|
if (this.closed) throw new Error("HttpSink is closed");
|
|
557
824
|
this.enqueue(event);
|
|
825
|
+
this.unsentWarned = false;
|
|
558
826
|
void this.scheduleDrain();
|
|
559
|
-
this.
|
|
827
|
+
this.ensureExitHooksRegistered();
|
|
560
828
|
}
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
await this.scheduleDrain();
|
|
829
|
+
flush() {
|
|
830
|
+
return this.flushWithin(Infinity);
|
|
564
831
|
}
|
|
565
|
-
|
|
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) {
|
|
566
837
|
if (this.closed) return;
|
|
567
|
-
await this.flush();
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
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;
|
|
572
857
|
}
|
|
573
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
|
+
}
|
|
574
892
|
enqueue(event) {
|
|
575
893
|
if (this.buffer.length >= this.bufferSize) {
|
|
894
|
+
PROCESS_DROPS.add("buffer_full");
|
|
576
895
|
if (!this.overflowWarned) {
|
|
577
|
-
|
|
896
|
+
warn(
|
|
578
897
|
`Baton HTTP sink buffer full (${this.bufferSize}); oldest events dropped. Further overflows will be silent.`
|
|
579
898
|
);
|
|
580
899
|
this.overflowWarned = true;
|
|
@@ -596,18 +915,58 @@ var HttpSink = class _HttpSink {
|
|
|
596
915
|
return this.drainChain;
|
|
597
916
|
}
|
|
598
917
|
/** Best-effort flush when the process is about to exit without an
|
|
599
|
-
* explicit `aclose()`.
|
|
600
|
-
*
|
|
601
|
-
*
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
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
|
+
);
|
|
609
932
|
};
|
|
610
|
-
|
|
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).`;
|
|
611
970
|
}
|
|
612
971
|
events_url() {
|
|
613
972
|
return `${this.url}/v0/events`;
|
|
@@ -620,38 +979,197 @@ var HttpSink = class _HttpSink {
|
|
|
620
979
|
if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
|
|
621
980
|
return "transient_failure";
|
|
622
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
|
+
}
|
|
623
1034
|
async drainLocked() {
|
|
624
1035
|
while (this.buffer.length > 0) {
|
|
625
|
-
if (!this.circuit.canRequest()) return;
|
|
1036
|
+
if (!this.circuit.canRequest() || this.closing.signal.aborted) return;
|
|
626
1037
|
const event = this.buffer[0];
|
|
627
1038
|
const outcome = await this.sendWithRetry(event);
|
|
628
1039
|
if (outcome === "success" || outcome === "permanent_failure") {
|
|
629
|
-
this.
|
|
1040
|
+
this.dequeue(event);
|
|
630
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);
|
|
631
1048
|
} else {
|
|
632
1049
|
this.circuit.recordFailure();
|
|
633
1050
|
return;
|
|
634
1051
|
}
|
|
635
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
|
+
}
|
|
636
1101
|
}
|
|
637
1102
|
async sendWithRetry(event) {
|
|
638
|
-
const
|
|
639
|
-
|
|
640
|
-
const body = JSON.stringify(event);
|
|
1103
|
+
const body = this.encode(event);
|
|
1104
|
+
if (body === null) return "unencodable";
|
|
641
1105
|
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
const outcome = _HttpSink.classifyStatus(response.status);
|
|
645
|
-
if (outcome !== "transient_failure") return outcome;
|
|
646
|
-
} catch {
|
|
647
|
-
}
|
|
1106
|
+
const outcome = await this.postOnce(body, this.requestTimeoutMs);
|
|
1107
|
+
if (outcome !== "transient_failure") return outcome;
|
|
648
1108
|
if (attempt < this.maxRetries) {
|
|
649
1109
|
const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);
|
|
650
|
-
await
|
|
1110
|
+
await this.sleepUnlessClosed(backoff);
|
|
1111
|
+
if (this.closing.signal.aborted) return "transient_failure";
|
|
651
1112
|
}
|
|
652
1113
|
}
|
|
653
1114
|
return "transient_failure";
|
|
654
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
|
+
}
|
|
655
1173
|
};
|
|
656
1174
|
|
|
657
1175
|
// src/integrations/mcp/withBaton.ts
|
|
@@ -663,11 +1181,6 @@ import { z as z2 } from "zod";
|
|
|
663
1181
|
// src/metaCoordinates.ts
|
|
664
1182
|
var COORD_FIELD_NAMES = /* @__PURE__ */ new Set(["latitude", "longitude"]);
|
|
665
1183
|
var DECIMAL_STRING = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/;
|
|
666
|
-
function isPlainObject2(value) {
|
|
667
|
-
if (typeof value !== "object" || value === null) return false;
|
|
668
|
-
const proto = Object.getPrototypeOf(value);
|
|
669
|
-
return proto === Object.prototype || proto === null;
|
|
670
|
-
}
|
|
671
1184
|
function toOneDecimal(value) {
|
|
672
1185
|
const magnitude = Math.abs(value);
|
|
673
1186
|
if (Number.isInteger(magnitude * 4) && !Number.isInteger(magnitude * 2)) {
|
|
@@ -688,7 +1201,7 @@ function roundCoordinate(value) {
|
|
|
688
1201
|
}
|
|
689
1202
|
function walk(value, depth) {
|
|
690
1203
|
if (depth >= DEPTH_LIMIT) return value;
|
|
691
|
-
if (
|
|
1204
|
+
if (isPlainObject(value)) {
|
|
692
1205
|
const out = {};
|
|
693
1206
|
for (const [k, v] of Object.entries(value)) {
|
|
694
1207
|
const rounded = COORD_FIELD_NAMES.has(k.toLowerCase()) && depth + 1 < DEPTH_LIMIT ? roundCoordinate(v) : void 0;
|
|
@@ -705,69 +1218,6 @@ function roundMetaCoordinates(meta) {
|
|
|
705
1218
|
return walk(meta, 0);
|
|
706
1219
|
}
|
|
707
1220
|
|
|
708
|
-
// src/_text.ts
|
|
709
|
-
function exceedsCodePoints(value, max) {
|
|
710
|
-
if (value.length <= max) return false;
|
|
711
|
-
if (value.length > 2 * max) return true;
|
|
712
|
-
return [...value].length > max;
|
|
713
|
-
}
|
|
714
|
-
function capCodePoints(value, max) {
|
|
715
|
-
if (value.length <= max) return value;
|
|
716
|
-
return [...value].slice(0, max).join("");
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
// src/identity.ts
|
|
720
|
-
var PRINCIPAL_SOURCE_ASSERTED = "asserted";
|
|
721
|
-
var PRINCIPAL_FORM_HASHED = "hashed";
|
|
722
|
-
var PRINCIPAL_FORM_RAW = "raw";
|
|
723
|
-
var PRINCIPAL_ID_MAX_LEN = 128;
|
|
724
|
-
var DISPLAY_NAME_MAX_LEN = 128;
|
|
725
|
-
var ALL_WHITE_SPACE = /^\p{White_Space}*$/u;
|
|
726
|
-
function wireDisplayName(value) {
|
|
727
|
-
if (typeof value !== "string" || exceedsCodePoints(value, DISPLAY_NAME_MAX_LEN)) return null;
|
|
728
|
-
if (LONE_SURROGATE.test(value) || value.includes("\0") || ALL_WHITE_SPACE.test(value)) return null;
|
|
729
|
-
return value;
|
|
730
|
-
}
|
|
731
|
-
var PRINCIPAL_FORMS = /* @__PURE__ */ new Set([PRINCIPAL_FORM_RAW, PRINCIPAL_FORM_HASHED]);
|
|
732
|
-
var PYTHON_WHITESPACE = "\\t\\n\\v\\f\\r\\x1c-\\x1f \\x85\\xa0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000";
|
|
733
|
-
var PYTHON_STRIP = new RegExp(`^[${PYTHON_WHITESPACE}]+|[${PYTHON_WHITESPACE}]+$`, "gu");
|
|
734
|
-
var LONE_SURROGATE = /\p{Surrogate}/u;
|
|
735
|
-
function pythonStrip(value) {
|
|
736
|
-
return value.replace(PYTHON_STRIP, "");
|
|
737
|
-
}
|
|
738
|
-
function normalizePrincipal(result) {
|
|
739
|
-
if (result === null || typeof result !== "object") return null;
|
|
740
|
-
const candidate = result;
|
|
741
|
-
if (typeof candidate.principalId !== "string") return null;
|
|
742
|
-
if (LONE_SURROGATE.test(candidate.principalId)) return null;
|
|
743
|
-
if (candidate.principalId.includes("\0")) return null;
|
|
744
|
-
if (pythonStrip(candidate.principalId) === "") return null;
|
|
745
|
-
const principal = { principalId: candidate.principalId };
|
|
746
|
-
if (candidate.form !== void 0) principal.form = candidate.form;
|
|
747
|
-
if (typeof candidate.displayName === "string") principal.displayName = candidate.displayName;
|
|
748
|
-
return principal;
|
|
749
|
-
}
|
|
750
|
-
function principalFor(principal, onUnregisteredForm) {
|
|
751
|
-
let form = PRINCIPAL_FORM_RAW;
|
|
752
|
-
if (principal.form !== void 0) {
|
|
753
|
-
if (PRINCIPAL_FORMS.has(principal.form)) {
|
|
754
|
-
form = principal.form;
|
|
755
|
-
} else {
|
|
756
|
-
onUnregisteredForm?.(principal.form);
|
|
757
|
-
}
|
|
758
|
-
}
|
|
759
|
-
const wire = {
|
|
760
|
-
// `capCodePoints`, not `.slice()`: a plain slice counts UTF-16 units, so
|
|
761
|
-
// an astral id cut at the boundary would ship a lone surrogate.
|
|
762
|
-
id: capCodePoints(principal.principalId, PRINCIPAL_ID_MAX_LEN),
|
|
763
|
-
source: PRINCIPAL_SOURCE_ASSERTED,
|
|
764
|
-
form
|
|
765
|
-
};
|
|
766
|
-
const displayName = wireDisplayName(principal.displayName);
|
|
767
|
-
if (displayName !== null) wire.display_name = displayName;
|
|
768
|
-
return wire;
|
|
769
|
-
}
|
|
770
|
-
|
|
771
1221
|
// src/integrations/mcp/llmText.ts
|
|
772
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.`;
|
|
773
1223
|
var USER_GOAL_FORMAT = "'<n>: <what this call is for>; success is <what its result should show>'";
|
|
@@ -839,14 +1289,14 @@ var OURS_STARTS = [
|
|
|
839
1289
|
];
|
|
840
1290
|
function endsInOurs(current2, vendor) {
|
|
841
1291
|
if (typeof current2 !== "string") return false;
|
|
842
|
-
const prefix = typeof vendor === "string" && vendor
|
|
1292
|
+
const prefix = typeof vendor === "string" && !isBlank(vendor) ? `${vendor}
|
|
843
1293
|
|
|
844
1294
|
` : "";
|
|
845
1295
|
if (!current2.startsWith(prefix)) return false;
|
|
846
1296
|
const rest = current2.slice(prefix.length);
|
|
847
1297
|
return OURS_STARTS.some((start) => start.test(rest));
|
|
848
1298
|
}
|
|
849
|
-
function withVendorInstructions(server, ours,
|
|
1299
|
+
function withVendorInstructions(server, ours, warn3 = (message) => process.stderr.write(message)) {
|
|
850
1300
|
const holder = server;
|
|
851
1301
|
const current2 = holder._instructions;
|
|
852
1302
|
let vendor = VENDOR_INSTRUCTIONS in holder ? holder[VENDOR_INSTRUCTIONS] : current2;
|
|
@@ -854,12 +1304,12 @@ function withVendorInstructions(server, ours, warn4 = (message) => process.stder
|
|
|
854
1304
|
vendor = current2;
|
|
855
1305
|
holder[VENDOR_INSTRUCTIONS] = vendor;
|
|
856
1306
|
}
|
|
857
|
-
if (typeof vendor !== "string" ||
|
|
1307
|
+
if (typeof vendor !== "string" || isBlank(vendor)) return ours;
|
|
858
1308
|
const combined = `${vendor}
|
|
859
1309
|
|
|
860
1310
|
${ours}`;
|
|
861
1311
|
if (combined.length > CLAUDE_CODE_TRUNCATION_CAP) {
|
|
862
|
-
|
|
1312
|
+
warn3(
|
|
863
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
|
|
864
1314
|
`
|
|
865
1315
|
);
|
|
@@ -873,17 +1323,17 @@ var SUFFIX = "_annotate";
|
|
|
873
1323
|
var SLUG_CAP = 30;
|
|
874
1324
|
var PLACEHOLDER_LITERALS = /* @__PURE__ */ new Set(["fastmcp", "mcp-server"]);
|
|
875
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
|
+
}
|
|
876
1331
|
function isLibraryPlaceholder(serverName, className) {
|
|
877
1332
|
const stripped = pythonStrip(serverName);
|
|
878
1333
|
if (PLACEHOLDER_LITERALS.has(stripped.toLowerCase())) return true;
|
|
879
1334
|
const stem = stripped.replace(RANDOM_SUFFIX, "");
|
|
880
1335
|
return stem !== stripped && stem === className;
|
|
881
1336
|
}
|
|
882
|
-
function warn(message) {
|
|
883
|
-
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
884
|
-
process.emitWarning(message);
|
|
885
|
-
}
|
|
886
|
-
}
|
|
887
1337
|
function usableServerName(read) {
|
|
888
1338
|
let name;
|
|
889
1339
|
let className;
|
|
@@ -957,13 +1407,117 @@ async function emit(sink, build) {
|
|
|
957
1407
|
try {
|
|
958
1408
|
event = build();
|
|
959
1409
|
} catch (err) {
|
|
960
|
-
|
|
1410
|
+
PROCESS_DROPS.add("encode_failed");
|
|
1411
|
+
process.stderr.write(`baton: event construction failed; event dropped: ${printable(err)}
|
|
961
1412
|
`);
|
|
962
1413
|
return;
|
|
963
1414
|
}
|
|
964
1415
|
await safeWrite(sink, event);
|
|
965
1416
|
}
|
|
966
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
|
+
|
|
967
1521
|
// src/integrations/mcp/mcpTypes.ts
|
|
968
1522
|
function extraAuthInfo(extra) {
|
|
969
1523
|
const found = extra.authInfo ?? extra.http?.authInfo;
|
|
@@ -1021,68 +1575,43 @@ function buildPrincipalResolutionContext(extra, toolName, args) {
|
|
|
1021
1575
|
};
|
|
1022
1576
|
}
|
|
1023
1577
|
var HOOK_TIMEOUT_MS = 5e3;
|
|
1024
|
-
var TIMED_OUT = /* @__PURE__ */ Symbol("hookTimedOut");
|
|
1025
1578
|
async function withinHookBudget(answer) {
|
|
1026
1579
|
if (!isThenable(answer)) return answer;
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
timer = setTimeout(() => resolve(TIMED_OUT), HOOK_TIMEOUT_MS);
|
|
1030
|
-
timer.unref?.();
|
|
1031
|
-
});
|
|
1032
|
-
try {
|
|
1033
|
-
const first = await Promise.race([answer, deadline]);
|
|
1034
|
-
if (first !== TIMED_OUT) return first;
|
|
1035
|
-
warn(
|
|
1036
|
-
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
1037
|
-
);
|
|
1038
|
-
return null;
|
|
1039
|
-
} finally {
|
|
1040
|
-
clearTimeout(timer);
|
|
1041
|
-
}
|
|
1042
|
-
}
|
|
1043
|
-
var warnedPreRenameShape = false;
|
|
1044
|
-
function warnIfPreRenameShape(result) {
|
|
1045
|
-
const userId = result?.userId;
|
|
1046
|
-
if (warnedPreRenameShape || typeof userId !== "string") return;
|
|
1047
|
-
warnedPreRenameShape = true;
|
|
1580
|
+
const first = await raceDeadline(answer, HOOK_TIMEOUT_MS);
|
|
1581
|
+
if (first !== TIMED_OUT) return first;
|
|
1048
1582
|
warn(
|
|
1049
|
-
|
|
1583
|
+
`baton: resolvePrincipal did not answer within ${String(HOOK_TIMEOUT_MS / 1e3)}s; this request is sent without a principal.`
|
|
1050
1584
|
);
|
|
1585
|
+
return null;
|
|
1051
1586
|
}
|
|
1052
|
-
|
|
1053
|
-
|
|
1587
|
+
var warned = /* @__PURE__ */ new Set();
|
|
1588
|
+
function warnOnce(key, message) {
|
|
1589
|
+
if (warned.has(key)) return;
|
|
1590
|
+
warned.add(key);
|
|
1591
|
+
warn(`baton: resolvePrincipal ${message}`);
|
|
1592
|
+
}
|
|
1593
|
+
async function resolveCaller(hook, call) {
|
|
1594
|
+
if (hook === void 0) return NO_CALLER;
|
|
1054
1595
|
try {
|
|
1055
1596
|
const context = buildPrincipalResolutionContext(call.extra, call.toolName, call.arguments);
|
|
1056
1597
|
const result = await withinHookBudget(hook(context));
|
|
1057
|
-
|
|
1058
|
-
if (principal === null) {
|
|
1059
|
-
warnIfPreRenameShape(result);
|
|
1060
|
-
return null;
|
|
1061
|
-
}
|
|
1062
|
-
return principalFor(principal, (form) => {
|
|
1063
|
-
warn(
|
|
1064
|
-
`baton: resolvePrincipal returned form ${describeForm(form)}, expected "raw" or "hashed" \u2014 sending it as "${PRINCIPAL_FORM_RAW}".`
|
|
1065
|
-
);
|
|
1066
|
-
});
|
|
1598
|
+
return callerFor(result, warnOnce);
|
|
1067
1599
|
} catch {
|
|
1068
|
-
return
|
|
1600
|
+
return NO_CALLER;
|
|
1069
1601
|
}
|
|
1070
1602
|
}
|
|
1071
|
-
function describeForm(form) {
|
|
1072
|
-
return typeof form === "string" ? JSON.stringify(form.slice(0, 32)) : `of type ${typeof form}`;
|
|
1073
|
-
}
|
|
1074
1603
|
|
|
1075
1604
|
// src/integrations/mcp/safeScrub.ts
|
|
1076
|
-
var
|
|
1605
|
+
var warned2 = /* @__PURE__ */ new Set();
|
|
1077
1606
|
function scrubOrNull(scrubber, value, field) {
|
|
1078
1607
|
if (value === null) return null;
|
|
1079
1608
|
try {
|
|
1080
1609
|
return scrubber(value);
|
|
1081
1610
|
} catch (err) {
|
|
1082
|
-
if (!
|
|
1083
|
-
|
|
1611
|
+
if (!warned2.has(field)) {
|
|
1612
|
+
warned2.add(field);
|
|
1084
1613
|
process.stderr.write(
|
|
1085
|
-
`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)}
|
|
1086
1615
|
`
|
|
1087
1616
|
);
|
|
1088
1617
|
}
|
|
@@ -1181,9 +1710,9 @@ function registeredHeaders(input) {
|
|
|
1181
1710
|
}
|
|
1182
1711
|
return out;
|
|
1183
1712
|
}
|
|
1184
|
-
function clientObservedFrom(clientInfo, headers, scrubber) {
|
|
1713
|
+
function clientObservedFrom(clientInfo, headers, scrubber, meta) {
|
|
1185
1714
|
return assemble(
|
|
1186
|
-
orNothing(() => cleanInfo(declared(clientInfo), scrubber)),
|
|
1715
|
+
orNothing(() => cleanInfo(declared(meta?.[CLIENT_INFO_META_KEY]) ?? declared(clientInfo), scrubber)),
|
|
1187
1716
|
orNothing(() => headers ? cleanHeaders(registeredHeaders(headers), scrubber) : void 0)
|
|
1188
1717
|
);
|
|
1189
1718
|
}
|
|
@@ -1191,16 +1720,19 @@ function clientObservedFrom(clientInfo, headers, scrubber) {
|
|
|
1191
1720
|
// src/integrations/mcp/sessionResolution.ts
|
|
1192
1721
|
async function resolveSessionId(fallbackSessionId, extra) {
|
|
1193
1722
|
if (typeof extra.sessionId === "string" && extra.sessionId) {
|
|
1194
|
-
return { sessionId: extra.sessionId, origin: "observed" };
|
|
1723
|
+
return { sessionId: extra.sessionId, origin: "observed", perCall: false };
|
|
1195
1724
|
}
|
|
1196
1725
|
const fromHeader = sessionIdFromHeader(extra);
|
|
1197
|
-
if (fromHeader !== null) return { sessionId: fromHeader, origin: "observed" };
|
|
1198
|
-
|
|
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 };
|
|
1199
1731
|
}
|
|
1200
1732
|
function sessionIdFromHeader(extra) {
|
|
1201
1733
|
try {
|
|
1202
|
-
const value = extraHeaders(extra)?.get("mcp-session-id")
|
|
1203
|
-
return value ? value : null;
|
|
1734
|
+
const value = extraHeaders(extra)?.get("mcp-session-id");
|
|
1735
|
+
return value ? stripWhiteSpace(value) || null : null;
|
|
1204
1736
|
} catch {
|
|
1205
1737
|
return null;
|
|
1206
1738
|
}
|
|
@@ -1209,7 +1741,7 @@ function sessionIdFromHeader(extra) {
|
|
|
1209
1741
|
// src/integrations/mcp/annotation.ts
|
|
1210
1742
|
var TOOL_NAME_PARAM_NAME = "tool_name";
|
|
1211
1743
|
function isReport(whatHappened) {
|
|
1212
|
-
return typeof whatHappened === "string" && whatHappened
|
|
1744
|
+
return typeof whatHappened === "string" && !isBlank(whatHappened);
|
|
1213
1745
|
}
|
|
1214
1746
|
function registerAnnotationTool(server, options) {
|
|
1215
1747
|
const name = deriveAnnotationToolName(options.vendorId, options.annotationToolName);
|
|
@@ -1252,8 +1784,8 @@ function registerAnnotationTool(server, options) {
|
|
|
1252
1784
|
meta ? roundMetaCoordinates(meta) : null,
|
|
1253
1785
|
"_meta"
|
|
1254
1786
|
);
|
|
1255
|
-
const
|
|
1256
|
-
const
|
|
1787
|
+
const session = await resolveSessionId(options.fallbackSessionId, extra);
|
|
1788
|
+
const caller = await resolveCaller(
|
|
1257
1789
|
options.resolvePrincipal,
|
|
1258
1790
|
{ extra, toolName: name, arguments: args }
|
|
1259
1791
|
);
|
|
@@ -1262,13 +1794,14 @@ function registerAnnotationTool(server, options) {
|
|
|
1262
1794
|
() => AnnotationEventSchema.parse({
|
|
1263
1795
|
tenant_id: options.tenantId,
|
|
1264
1796
|
vendor_id: options.vendorId,
|
|
1265
|
-
session_id: sessionId,
|
|
1266
|
-
sequence_number: options.counter.
|
|
1797
|
+
session_id: session.sessionId,
|
|
1798
|
+
sequence_number: options.counter.nextFor(session),
|
|
1267
1799
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1268
1800
|
consent_token: options.consentToken,
|
|
1269
|
-
principal,
|
|
1801
|
+
principal: caller.principal,
|
|
1802
|
+
organization: caller.organization,
|
|
1270
1803
|
transport_observed: observeTransport(extra),
|
|
1271
|
-
session_id_origin: origin,
|
|
1804
|
+
session_id_origin: session.origin,
|
|
1272
1805
|
client_observed: observeClient(extra, { server, scrubber: options.scrubber }),
|
|
1273
1806
|
runtime_meta: scrubbedMeta,
|
|
1274
1807
|
payload: {
|
|
@@ -1295,7 +1828,7 @@ function registerAnnotationTool(server, options) {
|
|
|
1295
1828
|
var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
|
|
1296
1829
|
var WORKSPACE_PATTERN = /^ten_(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{32})$/;
|
|
1297
1830
|
var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
|
|
1298
|
-
var NOT_IN_A_KEY = /[\x00\n\r]/;
|
|
1831
|
+
var NOT_IN_A_KEY = /[\x00\t\n\r]/;
|
|
1299
1832
|
var PUBLISHABLE_PREFIX = "baton_pk_";
|
|
1300
1833
|
var SECRET_PREFIX = "baton_sk_";
|
|
1301
1834
|
var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
|
|
@@ -1306,11 +1839,6 @@ function containsKey(value) {
|
|
|
1306
1839
|
return sweep(value) !== value;
|
|
1307
1840
|
}
|
|
1308
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";
|
|
1309
|
-
function warn2(message) {
|
|
1310
|
-
if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
|
|
1311
|
-
process.emitWarning(message);
|
|
1312
|
-
}
|
|
1313
|
-
}
|
|
1314
1842
|
function splitDsn(raw) {
|
|
1315
1843
|
const schemeEnd = raw.indexOf("://");
|
|
1316
1844
|
if (schemeEnd === -1) return null;
|
|
@@ -1370,7 +1898,7 @@ function selectDsn(explicit, supplied, door) {
|
|
|
1370
1898
|
const ambient = dsnFromEnvironment();
|
|
1371
1899
|
if (ambient === void 0) return void 0;
|
|
1372
1900
|
if (conflicts.length > 0) {
|
|
1373
|
-
|
|
1901
|
+
warn(
|
|
1374
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.`
|
|
1375
1903
|
);
|
|
1376
1904
|
return void 0;
|
|
@@ -1378,10 +1906,8 @@ function selectDsn(explicit, supplied, door) {
|
|
|
1378
1906
|
return ambient;
|
|
1379
1907
|
}
|
|
1380
1908
|
function parseDsn(raw) {
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
}
|
|
1384
|
-
const dsn = raw.trim();
|
|
1909
|
+
const dsn = typeof raw === "string" ? stripWhiteSpace(raw) : "";
|
|
1910
|
+
if (dsn === "") fail("dsn must be a non-empty string");
|
|
1385
1911
|
if (looksLikeAKey(dsn)) {
|
|
1386
1912
|
fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
|
|
1387
1913
|
}
|
|
@@ -1407,7 +1933,7 @@ function parseDsn(raw) {
|
|
|
1407
1933
|
}
|
|
1408
1934
|
if (NOT_IN_A_KEY.test(key)) {
|
|
1409
1935
|
fail(
|
|
1410
|
-
`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.`
|
|
1411
1937
|
);
|
|
1412
1938
|
}
|
|
1413
1939
|
if (key.includes(":")) {
|
|
@@ -1466,7 +1992,7 @@ function parseDsn(raw) {
|
|
|
1466
1992
|
);
|
|
1467
1993
|
}
|
|
1468
1994
|
if (key.startsWith(SECRET_PREFIX)) {
|
|
1469
|
-
|
|
1995
|
+
warn(
|
|
1470
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.`
|
|
1471
1997
|
);
|
|
1472
1998
|
}
|
|
@@ -1498,11 +2024,14 @@ function sealKey(dsn) {
|
|
|
1498
2024
|
// src/integrations/mcp/errorResult.ts
|
|
1499
2025
|
var TOOL_ERROR_TYPE = "tool_error";
|
|
1500
2026
|
var OUTPUT_SCHEMA_MISMATCH = "output_schema_mismatch";
|
|
2027
|
+
var REFUSED = "refused";
|
|
1501
2028
|
var TASK_MODES = /* @__PURE__ */ new Set(["required", "optional"]);
|
|
1502
|
-
function requestSideFailureKind(entry) {
|
|
2029
|
+
function requestSideFailureKind(entry, validation) {
|
|
1503
2030
|
if (entry == null) return "unknown_tool";
|
|
1504
2031
|
if (entry.enabled === false) return "tool_disabled";
|
|
1505
|
-
|
|
2032
|
+
if (validation === "rejected") return "invalid_argument";
|
|
2033
|
+
if (TASK_MODES.has(entry.execution?.taskSupport)) return void 0;
|
|
2034
|
+
return REFUSED;
|
|
1506
2035
|
}
|
|
1507
2036
|
var ERROR_BODY_MAX_CODE_POINTS = 2e3;
|
|
1508
2037
|
function isErrorResult(value) {
|
|
@@ -1521,7 +2050,7 @@ function errorText(value) {
|
|
|
1521
2050
|
for (const part of content) {
|
|
1522
2051
|
const text = part?.text;
|
|
1523
2052
|
if (typeof text !== "string") continue;
|
|
1524
|
-
const trimmed = text
|
|
2053
|
+
const trimmed = stripWhiteSpace(text);
|
|
1525
2054
|
if (trimmed) parts.push(trimmed);
|
|
1526
2055
|
}
|
|
1527
2056
|
} catch {
|
|
@@ -1553,6 +2082,9 @@ function resultDerivedFields(mode, text, result, errorBody2, scrubber) {
|
|
|
1553
2082
|
function requestSideErrorFields(text, errorBody2) {
|
|
1554
2083
|
return { error_body: errorBody2(text), result: null };
|
|
1555
2084
|
}
|
|
2085
|
+
function requestSideFailureFields(kind, mode, text, result, errorBody2, scrubber) {
|
|
2086
|
+
return kind === REFUSED ? resultDerivedFields(mode, text, result ?? null, errorBody2, scrubber) : requestSideErrorFields(text(), errorBody2);
|
|
2087
|
+
}
|
|
1556
2088
|
function errorTypeOf(err) {
|
|
1557
2089
|
return err instanceof Error ? err.constructor.name : "Error";
|
|
1558
2090
|
}
|
|
@@ -1698,7 +2230,7 @@ var SWITCH = "BATON_DISABLED";
|
|
|
1698
2230
|
var OFF_VALUES = /* @__PURE__ */ new Set(["", "0", "false", "no", "off"]);
|
|
1699
2231
|
function captureDisabled() {
|
|
1700
2232
|
const value = typeof process !== "undefined" ? process.env?.[SWITCH] : void 0;
|
|
1701
|
-
if (value !== void 0 && !OFF_VALUES.has(value
|
|
2233
|
+
if (value !== void 0 && !OFF_VALUES.has(stripWhiteSpace(value).toLowerCase())) {
|
|
1702
2234
|
return SWITCH;
|
|
1703
2235
|
}
|
|
1704
2236
|
return null;
|
|
@@ -1729,9 +2261,9 @@ var DisabledSink = class {
|
|
|
1729
2261
|
var BatonHandle = class {
|
|
1730
2262
|
sink;
|
|
1731
2263
|
vendorId;
|
|
1732
|
-
/**
|
|
1733
|
-
* when no
|
|
1734
|
-
*
|
|
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). */
|
|
1735
2267
|
sessionId;
|
|
1736
2268
|
/** The resolved annotation tool name: `BatonConfig.annotationToolName` if
|
|
1737
2269
|
* set, else derived from the server's own name (`{slug}_annotate`), else
|
|
@@ -1743,19 +2275,25 @@ var BatonHandle = class {
|
|
|
1743
2275
|
this.sessionId = options.sessionId;
|
|
1744
2276
|
this.annotationToolName = options.annotationToolName;
|
|
1745
2277
|
}
|
|
1746
|
-
/** 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). */
|
|
1747
2280
|
async flush() {
|
|
1748
|
-
await this.sink
|
|
2281
|
+
await boundedSinkCall(this.sink, "flush");
|
|
1749
2282
|
}
|
|
1750
|
-
/** Flush and release sink resources
|
|
2283
|
+
/** Flush and release sink resources, on the same terms as `flush()`. */
|
|
1751
2284
|
async aclose() {
|
|
1752
|
-
await this.sink
|
|
2285
|
+
await boundedSinkCall(this.sink, "aclose");
|
|
1753
2286
|
}
|
|
1754
2287
|
};
|
|
1755
2288
|
|
|
1756
2289
|
// src/integrations/mcp/sessionCounter.ts
|
|
1757
2290
|
var SessionCounter = class {
|
|
1758
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
|
+
}
|
|
1759
2297
|
next(sessionId) {
|
|
1760
2298
|
const current2 = this.counters.get(sessionId) ?? 0;
|
|
1761
2299
|
const next = current2 + 1;
|
|
@@ -1842,6 +2380,7 @@ function toJsonSchemaCompat(schema, opts) {
|
|
|
1842
2380
|
// src/integrations/mcp/schemaCompat.ts
|
|
1843
2381
|
import { z as zV4 } from "zod";
|
|
1844
2382
|
import { z as zV3 } from "zod/v3";
|
|
2383
|
+
var DEFAULT_INTENT_PARAM_MODE = "required";
|
|
1845
2384
|
var EMPTY_OBJECT_JSON_SCHEMA = { type: "object", properties: {} };
|
|
1846
2385
|
function injectGoalParams(inputSchema, intentParamMode) {
|
|
1847
2386
|
const objSchema = normalizeObjectSchema(inputSchema);
|
|
@@ -1920,9 +2459,9 @@ function surfaceHash(surface) {
|
|
|
1920
2459
|
}
|
|
1921
2460
|
function canonicalJson(value) {
|
|
1922
2461
|
if (value === null || typeof value !== "object") return JSON.stringify(value);
|
|
1923
|
-
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(",")}]`;
|
|
1924
2463
|
const record = value;
|
|
1925
|
-
const keys = Object.keys(record).sort();
|
|
2464
|
+
const keys = Object.keys(record).filter((k) => record[k] !== void 0).sort();
|
|
1926
2465
|
return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalJson(record[k])}`).join(",")}}`;
|
|
1927
2466
|
}
|
|
1928
2467
|
function buildServerMeta(lowlevelServer) {
|
|
@@ -1944,6 +2483,25 @@ function assembleSurface(serverMeta, tools) {
|
|
|
1944
2483
|
tools
|
|
1945
2484
|
};
|
|
1946
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
|
+
};
|
|
1947
2505
|
function buildSeamAugmentations(options) {
|
|
1948
2506
|
return {
|
|
1949
2507
|
injected_tools: [...options.injectedToolNames].sort(),
|
|
@@ -1962,12 +2520,12 @@ var wired = /* @__PURE__ */ new WeakSet();
|
|
|
1962
2520
|
var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
|
|
1963
2521
|
var callSlots = new AsyncLocalStorage();
|
|
1964
2522
|
var SurfaceState = class {
|
|
1965
|
-
constructor(serverMeta,
|
|
2523
|
+
constructor(serverMeta, sentSurfaces) {
|
|
1966
2524
|
this.serverMeta = serverMeta;
|
|
1967
|
-
this.
|
|
2525
|
+
this.sentSurfaces = sentSurfaces;
|
|
1968
2526
|
}
|
|
1969
2527
|
serverMeta;
|
|
1970
|
-
|
|
2528
|
+
sentSurfaces;
|
|
1971
2529
|
/** Every tool this install has seen, keyed by its CURRENT name. `disabled`
|
|
1972
2530
|
* is tracked alongside rather than pruned, so re-enabling costs nothing and
|
|
1973
2531
|
* — crucially — never needs a re-capture, which would re-read Baton's own
|
|
@@ -2024,29 +2582,30 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
2024
2582
|
}
|
|
2025
2583
|
async function openCall(ctx, toolName, extra, params, retired, registered = true) {
|
|
2026
2584
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
2027
|
-
const {
|
|
2585
|
+
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
2028
2586
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
2029
2587
|
const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
|
|
2030
2588
|
const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
|
|
2031
2589
|
const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
|
|
2032
2590
|
(name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, retired[name] ?? popText(params, name), name)
|
|
2033
2591
|
);
|
|
2034
|
-
const
|
|
2592
|
+
const caller = await resolveCaller(
|
|
2035
2593
|
ctx.resolvePrincipal,
|
|
2036
2594
|
{ extra, toolName, arguments: params }
|
|
2037
2595
|
);
|
|
2038
2596
|
const common = {
|
|
2039
2597
|
tenant_id: ctx.tenantId,
|
|
2040
2598
|
vendor_id: ctx.vendorId,
|
|
2041
|
-
session_id: sessionId,
|
|
2599
|
+
session_id: session.sessionId,
|
|
2042
2600
|
consent_token: ctx.consentToken,
|
|
2043
2601
|
// Every `...common` site is an event of this call, so `call_id` rides in
|
|
2044
2602
|
// it. `surface_snapshot` is deliberately not among them: it describes the
|
|
2045
2603
|
// SERVER and is captured outside any call, so it has no caller, transport
|
|
2046
2604
|
// or client to name.
|
|
2047
|
-
principal,
|
|
2605
|
+
principal: caller.principal,
|
|
2606
|
+
organization: caller.organization,
|
|
2048
2607
|
transport_observed: observeTransport(extra),
|
|
2049
|
-
session_id_origin: origin,
|
|
2608
|
+
session_id_origin: session.origin,
|
|
2050
2609
|
client_observed: observeClient(extra, ctx),
|
|
2051
2610
|
runtime_meta: scrubbedMeta,
|
|
2052
2611
|
call_id: uuid7()
|
|
@@ -2055,7 +2614,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2055
2614
|
ctx.sink,
|
|
2056
2615
|
() => ToolCallStartEventSchema.parse({
|
|
2057
2616
|
...common,
|
|
2058
|
-
sequence_number: ctx.counter.
|
|
2617
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2059
2618
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2060
2619
|
payload: {
|
|
2061
2620
|
tool_name: toolName,
|
|
@@ -2068,7 +2627,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2068
2627
|
}
|
|
2069
2628
|
})
|
|
2070
2629
|
);
|
|
2071
|
-
return { common,
|
|
2630
|
+
return { common, session };
|
|
2072
2631
|
}
|
|
2073
2632
|
function batonWrap(nameRef, original, ctx) {
|
|
2074
2633
|
return async (...callArgs) => {
|
|
@@ -2079,7 +2638,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2079
2638
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
2080
2639
|
const retired = slot?.retired ?? {};
|
|
2081
2640
|
if (slot) slot.retired = {};
|
|
2082
|
-
const { common,
|
|
2641
|
+
const { common, session } = await openCall(ctx, toolName, extra, params, retired);
|
|
2083
2642
|
const terminate = async (build, replacement) => {
|
|
2084
2643
|
if (!slot) {
|
|
2085
2644
|
await emit(ctx.sink, build);
|
|
@@ -2105,18 +2664,20 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2105
2664
|
await parkFailure(
|
|
2106
2665
|
() => ToolCallErrorEventSchema.parse({
|
|
2107
2666
|
...common,
|
|
2108
|
-
sequence_number: ctx.counter.
|
|
2667
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2109
2668
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2110
2669
|
payload: {
|
|
2111
2670
|
tool_name: toolName,
|
|
2112
2671
|
error_type: errorTypeOf(err),
|
|
2113
|
-
//
|
|
2114
|
-
//
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
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
|
+
),
|
|
2120
2681
|
duration_ms: durationMs2,
|
|
2121
2682
|
// Explicit, though the field is `.optional()` and this is its
|
|
2122
2683
|
// absent value. The schema is deliberately not an emitter (see
|
|
@@ -2140,7 +2701,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2140
2701
|
await parkFailure(
|
|
2141
2702
|
() => ToolCallErrorEventSchema.parse({
|
|
2142
2703
|
...common,
|
|
2143
|
-
sequence_number: ctx.counter.
|
|
2704
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2144
2705
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2145
2706
|
payload: {
|
|
2146
2707
|
tool_name: toolName,
|
|
@@ -2170,7 +2731,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2170
2731
|
await parkSuccess(
|
|
2171
2732
|
() => ToolCallEndEventSchema.parse({
|
|
2172
2733
|
...common,
|
|
2173
|
-
sequence_number: ctx.counter.
|
|
2734
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2174
2735
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2175
2736
|
payload: {
|
|
2176
2737
|
tool_name: toolName,
|
|
@@ -2186,7 +2747,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2186
2747
|
// CALLER saw fail, which is a success the product invented.
|
|
2187
2748
|
(outcome) => ToolCallErrorEventSchema.parse({
|
|
2188
2749
|
...common,
|
|
2189
|
-
sequence_number: ctx.counter.
|
|
2750
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2190
2751
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2191
2752
|
payload: {
|
|
2192
2753
|
tool_name: toolName,
|
|
@@ -2253,7 +2814,7 @@ function popText(args, paramName) {
|
|
|
2253
2814
|
if (!(paramName in args)) return null;
|
|
2254
2815
|
const raw = args[paramName];
|
|
2255
2816
|
delete args[paramName];
|
|
2256
|
-
return typeof raw === "string" && raw
|
|
2817
|
+
return typeof raw === "string" && !isBlank(raw) ? raw : null;
|
|
2257
2818
|
}
|
|
2258
2819
|
function stripRetiredParams(params, ctx) {
|
|
2259
2820
|
const toolName = params?.name;
|
|
@@ -2269,7 +2830,6 @@ function stripRetiredParams(params, ctx) {
|
|
|
2269
2830
|
}
|
|
2270
2831
|
return retired;
|
|
2271
2832
|
}
|
|
2272
|
-
var MAX_REMEMBERED_SURFACES = 1024;
|
|
2273
2833
|
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
2274
2834
|
if (!ctx.surfaceState.dirty) return;
|
|
2275
2835
|
ctx.surfaceState.dirty = false;
|
|
@@ -2283,10 +2843,9 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2283
2843
|
`);
|
|
2284
2844
|
return;
|
|
2285
2845
|
}
|
|
2286
|
-
const
|
|
2287
|
-
if (
|
|
2288
|
-
|
|
2289
|
-
emitted.add(digest);
|
|
2846
|
+
const sent = ctx.surfaceState.sentSurfaces;
|
|
2847
|
+
if (sent.wasSent(digest)) return;
|
|
2848
|
+
sent.mark(digest);
|
|
2290
2849
|
const seam = buildSeamAugmentations({
|
|
2291
2850
|
injectedToolNames: ctx.annotationToolName ? [ctx.annotationToolName] : [],
|
|
2292
2851
|
intentParamNames: [USER_GOAL_PARAM_NAME],
|
|
@@ -2299,7 +2858,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
2299
2858
|
} catch (err) {
|
|
2300
2859
|
process.stderr.write(`baton: surface snapshot capture failed: ${String(err)}
|
|
2301
2860
|
`);
|
|
2302
|
-
|
|
2861
|
+
sent.unmark(digest);
|
|
2303
2862
|
ctx.surfaceState.dirty = true;
|
|
2304
2863
|
}
|
|
2305
2864
|
}
|
|
@@ -2394,7 +2953,7 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2394
2953
|
ctx.sink,
|
|
2395
2954
|
() => schema.parse({
|
|
2396
2955
|
...opened.common,
|
|
2397
|
-
sequence_number: ctx.counter.
|
|
2956
|
+
sequence_number: ctx.counter.nextFor(opened.session),
|
|
2398
2957
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2399
2958
|
payload: scrubLifecyclePayload(ctx, { ...opened.subject, ...payload })
|
|
2400
2959
|
})
|
|
@@ -2426,25 +2985,26 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2426
2985
|
}
|
|
2427
2986
|
async function openLifecycleCall(ctx, spec, requestParams, extra) {
|
|
2428
2987
|
try {
|
|
2429
|
-
const
|
|
2430
|
-
const
|
|
2988
|
+
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
2989
|
+
const caller = await resolveCaller(ctx.resolvePrincipal, {
|
|
2431
2990
|
extra,
|
|
2432
2991
|
toolName: null,
|
|
2433
2992
|
arguments: {}
|
|
2434
2993
|
});
|
|
2435
2994
|
return {
|
|
2436
|
-
|
|
2995
|
+
session,
|
|
2437
2996
|
subject: spec.subjectKey === void 0 ? {} : { [spec.subjectKey]: stringSubject(requestParams[spec.subjectKey]) },
|
|
2438
2997
|
common: {
|
|
2439
2998
|
tenant_id: ctx.tenantId,
|
|
2440
2999
|
vendor_id: ctx.vendorId,
|
|
2441
|
-
session_id:
|
|
3000
|
+
session_id: session.sessionId,
|
|
2442
3001
|
consent_token: ctx.consentToken,
|
|
2443
|
-
principal,
|
|
3002
|
+
principal: caller.principal,
|
|
3003
|
+
organization: caller.organization,
|
|
2444
3004
|
transport_observed: observeTransport(extra),
|
|
2445
|
-
session_id_origin:
|
|
3005
|
+
session_id_origin: session.origin,
|
|
2446
3006
|
client_observed: observeClient(extra, ctx),
|
|
2447
|
-
runtime_meta:
|
|
3007
|
+
runtime_meta: scrubbedMeta
|
|
2448
3008
|
}
|
|
2449
3009
|
};
|
|
2450
3010
|
} catch (err) {
|
|
@@ -2572,7 +3132,8 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
2572
3132
|
const slot = {
|
|
2573
3133
|
innerFired: false,
|
|
2574
3134
|
flushTerminal: null,
|
|
2575
|
-
retired: stripRetiredParams(request?.params, ctx)
|
|
3135
|
+
retired: stripRetiredParams(request?.params, ctx),
|
|
3136
|
+
validation: "unseen"
|
|
2576
3137
|
};
|
|
2577
3138
|
let outcome = CLEAN_OUTCOME;
|
|
2578
3139
|
try {
|
|
@@ -2588,6 +3149,25 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
2588
3149
|
}
|
|
2589
3150
|
);
|
|
2590
3151
|
}
|
|
3152
|
+
var VALIDATION_PROBE = /* @__PURE__ */ Symbol("baton.validationProbe");
|
|
3153
|
+
function installValidationProbe(server) {
|
|
3154
|
+
const target = server;
|
|
3155
|
+
const original = target.validateToolInput;
|
|
3156
|
+
if (typeof original !== "function" || original[VALIDATION_PROBE]) return;
|
|
3157
|
+
const probe = async function(...args) {
|
|
3158
|
+
const slot = callSlots.getStore();
|
|
3159
|
+
try {
|
|
3160
|
+
const parsed = await original.apply(this, args);
|
|
3161
|
+
if (slot) slot.validation = "passed";
|
|
3162
|
+
return parsed;
|
|
3163
|
+
} catch (err) {
|
|
3164
|
+
if (slot) slot.validation = "rejected";
|
|
3165
|
+
throw err;
|
|
3166
|
+
}
|
|
3167
|
+
};
|
|
3168
|
+
Object.assign(probe, { [VALIDATION_PROBE]: true });
|
|
3169
|
+
target.validateToolInput = probe;
|
|
3170
|
+
}
|
|
2591
3171
|
async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
2592
3172
|
try {
|
|
2593
3173
|
if (slot.flushTerminal !== null) {
|
|
@@ -2598,13 +3178,14 @@ async function settleCall(slot, outcome, args, toolEntry, ctx) {
|
|
|
2598
3178
|
}
|
|
2599
3179
|
if (slot.innerFired) return;
|
|
2600
3180
|
if (!outcome.failed) return;
|
|
2601
|
-
await emitRequestSideFailure(outcome, args, slot
|
|
3181
|
+
await emitRequestSideFailure(outcome, args, slot, toolEntry, ctx);
|
|
2602
3182
|
} catch (err) {
|
|
3183
|
+
PROCESS_DROPS.add("encode_failed");
|
|
2603
3184
|
process.stderr.write(`baton: settling a tool call failed; events dropped: ${String(err)}
|
|
2604
3185
|
`);
|
|
2605
3186
|
}
|
|
2606
3187
|
}
|
|
2607
|
-
async function emitRequestSideFailure(outcome, args,
|
|
3188
|
+
async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
2608
3189
|
const request = args[0];
|
|
2609
3190
|
const toolName = request?.params?.name;
|
|
2610
3191
|
if (typeof toolName !== "string") return;
|
|
@@ -2612,13 +3193,21 @@ async function emitRequestSideFailure(outcome, args, retired, toolEntry, ctx) {
|
|
|
2612
3193
|
const entry = toolEntry(toolName);
|
|
2613
3194
|
if (entry != null && dispatchTarget(entry)?.[BATON_WRAPPED] !== true) return;
|
|
2614
3195
|
const params = { ...request?.params?.arguments ?? {} };
|
|
2615
|
-
const { common,
|
|
2616
|
-
|
|
3196
|
+
const { common, session } = await openCall(
|
|
3197
|
+
ctx,
|
|
3198
|
+
toolName,
|
|
3199
|
+
args[1],
|
|
3200
|
+
params,
|
|
3201
|
+
slot.retired,
|
|
3202
|
+
entry != null
|
|
3203
|
+
);
|
|
3204
|
+
const failureKind = requestSideFailureKind(entry, slot.validation);
|
|
3205
|
+
const text = () => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result);
|
|
2617
3206
|
await emit(
|
|
2618
3207
|
ctx.sink,
|
|
2619
3208
|
() => ToolCallErrorEventSchema.parse({
|
|
2620
3209
|
...common,
|
|
2621
|
-
sequence_number: ctx.counter.
|
|
3210
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2622
3211
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2623
3212
|
payload: {
|
|
2624
3213
|
tool_name: toolName,
|
|
@@ -2634,8 +3223,8 @@ async function emitRequestSideFailure(outcome, args, retired, toolEntry, ctx) {
|
|
|
2634
3223
|
error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
|
|
2635
3224
|
// ⚠ `null`, not 0. The vendor's handler never ran, so there is no
|
|
2636
3225
|
// handler duration to report; the time this call did spend was spent
|
|
2637
|
-
//
|
|
2638
|
-
//
|
|
3226
|
+
// above the handler, which is not what any other event means by this
|
|
3227
|
+
// member. §11.4 types it nullable for cases like this one.
|
|
2639
3228
|
duration_ms: null,
|
|
2640
3229
|
// ⚠ A CONDITIONAL SPREAD, not `failure_kind: failureKind`. Zod's
|
|
2641
3230
|
// `.optional()` accepts `undefined` and keeps the KEY in its output,
|
|
@@ -2645,11 +3234,13 @@ async function emitRequestSideFailure(outcome, args, retired, toolEntry, ctx) {
|
|
|
2645
3234
|
// determine the kind MUST OMIT the member, and omitting is what this
|
|
2646
3235
|
// spells.
|
|
2647
3236
|
...failureKind === void 0 ? {} : { failure_kind: failureKind },
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2652
|
-
|
|
3237
|
+
...requestSideFailureFields(
|
|
3238
|
+
failureKind,
|
|
3239
|
+
ctx.resultCaptureMode,
|
|
3240
|
+
text,
|
|
3241
|
+
outcome.raised ? null : outcome.result,
|
|
3242
|
+
(value) => errorBody(ctx, value),
|
|
3243
|
+
ctx.scrubber
|
|
2653
3244
|
)
|
|
2654
3245
|
}
|
|
2655
3246
|
})
|
|
@@ -2732,15 +3323,19 @@ function withBaton(server, supplied = {}) {
|
|
|
2732
3323
|
}
|
|
2733
3324
|
const resolved = resolveBatonConfig(supplied);
|
|
2734
3325
|
warnUnusedReportSettings(resolved);
|
|
2735
|
-
return install(server, supplied, resolved,
|
|
3326
|
+
return install(server, supplied, resolved, new SentSurfaces(), /* @__PURE__ */ new Set());
|
|
2736
3327
|
}
|
|
2737
3328
|
function createBaton(supplied = {}) {
|
|
2738
3329
|
const disabledBy = captureDisabled();
|
|
2739
3330
|
if (disabledBy !== null) {
|
|
2740
3331
|
logDisabled(disabledBy, "createBaton");
|
|
2741
3332
|
const unused = supplied.sink ?? new DisabledSink();
|
|
2742
|
-
return {
|
|
2743
|
-
|
|
3333
|
+
return {
|
|
3334
|
+
wrap: () => {
|
|
3335
|
+
},
|
|
3336
|
+
flush: () => boundedSinkCall(unused, "flush"),
|
|
3337
|
+
aclose: () => boundedSinkCall(unused, "aclose")
|
|
3338
|
+
};
|
|
2744
3339
|
}
|
|
2745
3340
|
const resolved = resolveBatonConfig(supplied);
|
|
2746
3341
|
warnUnusedReportSettings(resolved);
|
|
@@ -2751,17 +3346,17 @@ function createBaton(supplied = {}) {
|
|
|
2751
3346
|
sink,
|
|
2752
3347
|
tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
|
|
2753
3348
|
};
|
|
2754
|
-
const
|
|
2755
|
-
const
|
|
3349
|
+
const sentSurfaces = new SentSurfaces();
|
|
3350
|
+
const warned3 = /* @__PURE__ */ new Set();
|
|
2756
3351
|
return {
|
|
2757
3352
|
wrap: (server) => {
|
|
2758
|
-
install(server, supplied, config,
|
|
3353
|
+
install(server, supplied, config, sentSurfaces, warned3);
|
|
2759
3354
|
},
|
|
2760
|
-
flush: () => sink
|
|
2761
|
-
aclose: () => sink
|
|
3355
|
+
flush: () => boundedSinkCall(sink, "flush"),
|
|
3356
|
+
aclose: () => boundedSinkCall(sink, "aclose")
|
|
2762
3357
|
};
|
|
2763
3358
|
}
|
|
2764
|
-
function install(server, supplied, resolved,
|
|
3359
|
+
function install(server, supplied, resolved, sentSurfaces, warned3) {
|
|
2765
3360
|
const internals = server;
|
|
2766
3361
|
const serverName = usableServerName(() => ({
|
|
2767
3362
|
name: internals.server._serverInfo?.name,
|
|
@@ -2771,13 +3366,13 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
|
|
|
2771
3366
|
const sink = config.sink ?? new StdoutSink();
|
|
2772
3367
|
const reports = reportsFor(config);
|
|
2773
3368
|
const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
|
|
2774
|
-
const intentParamMode = config.intentParamMode ??
|
|
3369
|
+
const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
|
|
2775
3370
|
const counter2 = new SessionCounter();
|
|
2776
3371
|
const fallbackSessionId = `sdk-${uuid7()}`;
|
|
2777
3372
|
const tenantId = resolveTenantId(config.tenantId, config.vendorId);
|
|
2778
3373
|
const scrubber = config.scrubber ?? new Scrubber().scrub;
|
|
2779
3374
|
const serverMeta = buildServerMeta(server.server);
|
|
2780
|
-
const surfaceState = new SurfaceState(serverMeta,
|
|
3375
|
+
const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
|
|
2781
3376
|
const emitSurface = async (sessionId, digest, snapshot) => {
|
|
2782
3377
|
const event = SurfaceSnapshotEventSchema.parse({
|
|
2783
3378
|
tenant_id: tenantId,
|
|
@@ -2802,9 +3397,9 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
|
|
|
2802
3397
|
const memo = internals._toolInputSchemaJson;
|
|
2803
3398
|
if (memo && typeof memo === "object") delete memo[name];
|
|
2804
3399
|
};
|
|
2805
|
-
const
|
|
2806
|
-
if (
|
|
2807
|
-
|
|
3400
|
+
const warnOnce2 = (key, message) => {
|
|
3401
|
+
if (warned3.has(key)) return;
|
|
3402
|
+
warned3.add(key);
|
|
2808
3403
|
process.stderr.write(message);
|
|
2809
3404
|
};
|
|
2810
3405
|
const dropSubagentClause = (name) => {
|
|
@@ -2816,7 +3411,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
|
|
|
2816
3411
|
} else {
|
|
2817
3412
|
return;
|
|
2818
3413
|
}
|
|
2819
|
-
|
|
3414
|
+
warnOnce2(
|
|
2820
3415
|
"native-user-goal",
|
|
2821
3416
|
`baton: tool ${JSON.stringify(name)} declares its own user_goal, so the subagent sentence was removed from the server instructions; a session that already started keeps it
|
|
2822
3417
|
`
|
|
@@ -2843,6 +3438,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
|
|
|
2843
3438
|
return { type: "object", properties: {} };
|
|
2844
3439
|
}
|
|
2845
3440
|
};
|
|
3441
|
+
installValidationProbe(server);
|
|
2846
3442
|
const ctx = {
|
|
2847
3443
|
sink,
|
|
2848
3444
|
counter: counter2,
|
|
@@ -2868,7 +3464,7 @@ function install(server, supplied, resolved, emittedSurfaceHashes, warned2) {
|
|
|
2868
3464
|
internals.server._instructions = withVendorInstructions(
|
|
2869
3465
|
internals.server,
|
|
2870
3466
|
ours,
|
|
2871
|
-
(message) =>
|
|
3467
|
+
(message) => warnOnce2("instructions-length", message)
|
|
2872
3468
|
);
|
|
2873
3469
|
installToolsListSeam(internals.server, ctx);
|
|
2874
3470
|
installToolsCallSeam(
|
|
@@ -2945,7 +3541,7 @@ function claimsOf(context) {
|
|
|
2945
3541
|
}
|
|
2946
3542
|
function stringClaim(claims, name) {
|
|
2947
3543
|
const value = claims[name];
|
|
2948
|
-
return typeof value === "string" &&
|
|
3544
|
+
return typeof value === "string" && !isBlank(value) ? value : null;
|
|
2949
3545
|
}
|
|
2950
3546
|
function principalFromOAuthSub(context) {
|
|
2951
3547
|
const claims = claimsOf(context);
|
|
@@ -2975,46 +3571,48 @@ function sessionEnvelope(session) {
|
|
|
2975
3571
|
session_id_origin: session.origin,
|
|
2976
3572
|
transport_observed: TRANSPORT_LIBRARY,
|
|
2977
3573
|
principal: session.principal,
|
|
3574
|
+
organization: session.organization,
|
|
2978
3575
|
client_observed: session.clientObserved,
|
|
2979
|
-
runtime_meta: session.
|
|
3576
|
+
runtime_meta: session.runtimeMeta
|
|
2980
3577
|
};
|
|
2981
3578
|
}
|
|
2982
|
-
function
|
|
3579
|
+
function warn2(message) {
|
|
2983
3580
|
process.stderr.write(`baton: ${message}
|
|
2984
3581
|
`);
|
|
2985
3582
|
}
|
|
2986
3583
|
function vendorId(name, value) {
|
|
2987
|
-
const cleaned = typeof value === "string" ?
|
|
3584
|
+
const cleaned = typeof value === "string" ? stripWhiteSpace(value) : "";
|
|
2988
3585
|
if (cleaned !== "") return cleaned;
|
|
2989
3586
|
if (value !== void 0 && value !== null) {
|
|
2990
|
-
|
|
3587
|
+
warn2(`${name} is not a non-blank string \u2014 ignoring it.`);
|
|
2991
3588
|
}
|
|
2992
3589
|
return null;
|
|
2993
3590
|
}
|
|
2994
|
-
function
|
|
2995
|
-
return { sessionId
|
|
3591
|
+
function blank(sessionId, origin) {
|
|
3592
|
+
return { sessionId, origin, ...NO_CALLER, clientObserved: null, runtimeMeta: null };
|
|
2996
3593
|
}
|
|
2997
|
-
function
|
|
2998
|
-
if (
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
}
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
);
|
|
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;
|
|
3008
3605
|
}
|
|
3009
3606
|
function newSession(values, scrubber, disabled) {
|
|
3010
3607
|
const id = vendorId("sessionId", values.sessionId);
|
|
3011
|
-
const base = id !== null ?
|
|
3608
|
+
const base = id !== null ? blank(id, "observed") : blank(uuid7(), "minted");
|
|
3012
3609
|
if (disabled) return base;
|
|
3610
|
+
const meta = requestMeta(values.meta);
|
|
3013
3611
|
return {
|
|
3014
3612
|
...base,
|
|
3015
|
-
|
|
3016
|
-
clientObserved: clientObservedFrom(values.clientInfo, values.headers, scrubber),
|
|
3017
|
-
|
|
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)
|
|
3018
3616
|
};
|
|
3019
3617
|
}
|
|
3020
3618
|
var current = new AsyncLocalStorage2();
|
|
@@ -3023,13 +3621,73 @@ function runInSession(owner, session, fn) {
|
|
|
3023
3621
|
}
|
|
3024
3622
|
function sessionForCall(owner) {
|
|
3025
3623
|
const entry = current.getStore();
|
|
3026
|
-
return entry !== void 0 && entry.owner === owner ? entry.session :
|
|
3624
|
+
return entry !== void 0 && entry.owner === owner ? entry.session : blank(uuid7(), "minted");
|
|
3027
3625
|
}
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
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];
|
|
3033
3691
|
}
|
|
3034
3692
|
|
|
3035
3693
|
// src/library/client.ts
|
|
@@ -3092,7 +3750,7 @@ function resolveClientOptions(options) {
|
|
|
3092
3750
|
resultCaptureMode
|
|
3093
3751
|
};
|
|
3094
3752
|
}
|
|
3095
|
-
var hasText2 = (value) => typeof value === "string" &&
|
|
3753
|
+
var hasText2 = (value) => typeof value === "string" && !isBlank(value);
|
|
3096
3754
|
function describeError(err) {
|
|
3097
3755
|
let type = "Error";
|
|
3098
3756
|
let body = "";
|
|
@@ -3106,19 +3764,18 @@ function describeError(err) {
|
|
|
3106
3764
|
}
|
|
3107
3765
|
return [type, body];
|
|
3108
3766
|
}
|
|
3109
|
-
function isPlainObject3(value) {
|
|
3110
|
-
if (typeof value !== "object" || value === null) return false;
|
|
3111
|
-
const proto = Object.getPrototypeOf(value);
|
|
3112
|
-
return proto === Object.prototype || proto === null;
|
|
3113
|
-
}
|
|
3114
3767
|
function paramsOf(args) {
|
|
3115
|
-
if (args.length === 1 &&
|
|
3768
|
+
if (args.length === 1 && isPlainObject(args[0])) return args[0];
|
|
3116
3769
|
return args.length === 0 ? {} : { args };
|
|
3117
3770
|
}
|
|
3118
3771
|
var Core = class {
|
|
3119
3772
|
closed = false;
|
|
3120
3773
|
pending = /* @__PURE__ */ new Set();
|
|
3121
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();
|
|
3122
3779
|
sink;
|
|
3123
3780
|
vendorId;
|
|
3124
3781
|
tenantId;
|
|
@@ -3151,6 +3808,7 @@ var Core = class {
|
|
|
3151
3808
|
live() {
|
|
3152
3809
|
if (this.disabled) return false;
|
|
3153
3810
|
if (!this.closed) return true;
|
|
3811
|
+
PROCESS_DROPS.add("after_close");
|
|
3154
3812
|
if (!this.closedWarned) {
|
|
3155
3813
|
this.closedWarned = true;
|
|
3156
3814
|
process.stderr.write("baton: Client is closed; further events are dropped.\n");
|
|
@@ -3159,19 +3817,69 @@ var Core = class {
|
|
|
3159
3817
|
}
|
|
3160
3818
|
/** Never rejects. Tracked so `flush()` can wait for it. */
|
|
3161
3819
|
emit(build) {
|
|
3162
|
-
|
|
3163
|
-
|
|
3164
|
-
|
|
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
|
+
);
|
|
3165
3862
|
}
|
|
3166
|
-
|
|
3167
|
-
|
|
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);
|
|
3168
3876
|
}
|
|
3169
3877
|
scrub(value, field) {
|
|
3170
3878
|
return scrubOrNull(this.scrubber, value, field);
|
|
3171
3879
|
}
|
|
3172
3880
|
annotate(session, consentToken, options) {
|
|
3173
3881
|
if (!this.live()) return Promise.resolve();
|
|
3174
|
-
const sequence =
|
|
3882
|
+
const sequence = nextClockSequence();
|
|
3175
3883
|
const text = (value) => value === void 0 ? null : this.scrubber(value);
|
|
3176
3884
|
return this.emit(
|
|
3177
3885
|
() => AnnotationEventSchema.parse({
|
|
@@ -3239,7 +3947,7 @@ var Trace = class _Trace {
|
|
|
3239
3947
|
try {
|
|
3240
3948
|
this.#result = this.#core.scrubber(result);
|
|
3241
3949
|
} catch (err) {
|
|
3242
|
-
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)}
|
|
3243
3951
|
`);
|
|
3244
3952
|
this.#result = SCRUB_FAILED;
|
|
3245
3953
|
}
|
|
@@ -3259,7 +3967,7 @@ var Trace = class _Trace {
|
|
|
3259
3967
|
#start() {
|
|
3260
3968
|
this.#startedAt = performance.now();
|
|
3261
3969
|
if (!this.#core.live()) return;
|
|
3262
|
-
const sequence =
|
|
3970
|
+
const sequence = nextClockSequence();
|
|
3263
3971
|
const o = this.#options;
|
|
3264
3972
|
const params = o.params === void 0 ? {} : this.#core.scrub(o.params, "params") ?? {};
|
|
3265
3973
|
const textOf = (value, field) => {
|
|
@@ -3288,7 +3996,7 @@ var Trace = class _Trace {
|
|
|
3288
3996
|
const durationMs = this.#durationMs();
|
|
3289
3997
|
if (!this.#core.live()) return;
|
|
3290
3998
|
if (this.#result === UNSET && this.#error === null) this.observed(value);
|
|
3291
|
-
const sequence =
|
|
3999
|
+
const sequence = nextClockSequence();
|
|
3292
4000
|
const error = this.#error;
|
|
3293
4001
|
if (error !== null) {
|
|
3294
4002
|
this.#emitError(sequence, error.type, error.body, durationMs);
|
|
@@ -3310,7 +4018,7 @@ var Trace = class _Trace {
|
|
|
3310
4018
|
#fail(err) {
|
|
3311
4019
|
const durationMs = this.#durationMs();
|
|
3312
4020
|
if (!this.#core.live()) return;
|
|
3313
|
-
this.#emitError(
|
|
4021
|
+
this.#emitError(nextClockSequence(), ...describeError(err), durationMs);
|
|
3314
4022
|
}
|
|
3315
4023
|
#emitError(sequence, type, body, durationMs) {
|
|
3316
4024
|
void this.#core.emit(
|
|
@@ -3386,7 +4094,7 @@ var Client = class {
|
|
|
3386
4094
|
try {
|
|
3387
4095
|
block = newSession(options, this.#core.scrubber, this.#core.disabled);
|
|
3388
4096
|
} catch (err) {
|
|
3389
|
-
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)}
|
|
3390
4098
|
`);
|
|
3391
4099
|
block = newSession({}, this.#core.scrubber, this.#core.disabled);
|
|
3392
4100
|
}
|
|
@@ -3416,30 +4124,41 @@ var Client = class {
|
|
|
3416
4124
|
const given = options ?? {};
|
|
3417
4125
|
return this.#core.annotate(sessionForCall(this), given.consentToken || this.#core.consentToken, given);
|
|
3418
4126
|
}
|
|
3419
|
-
/**
|
|
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). */
|
|
3420
4145
|
async flush() {
|
|
3421
|
-
await this.#
|
|
3422
|
-
try {
|
|
3423
|
-
await this.#core.sink.flush();
|
|
3424
|
-
} catch (err) {
|
|
3425
|
-
process.stderr.write(`baton: sink.flush failed: ${String(err)}
|
|
3426
|
-
`);
|
|
3427
|
-
}
|
|
4146
|
+
await this.#settleThen("flush");
|
|
3428
4147
|
}
|
|
3429
4148
|
/** Flush, then close the sink. Later events are dropped. */
|
|
3430
4149
|
aclose() {
|
|
3431
|
-
this.#closing ??= this.#
|
|
4150
|
+
this.#closing ??= this.#settleThen("aclose");
|
|
3432
4151
|
return this.#closing;
|
|
3433
4152
|
}
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
}
|
|
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
|
+
});
|
|
3443
4162
|
}
|
|
3444
4163
|
};
|
|
3445
4164
|
export {
|
|
@@ -3447,13 +4166,18 @@ export {
|
|
|
3447
4166
|
AnnotationPayloadSchema,
|
|
3448
4167
|
BatonHandle,
|
|
3449
4168
|
Client,
|
|
4169
|
+
ClientReportEventSchema,
|
|
4170
|
+
ClientReportPayloadSchema,
|
|
3450
4171
|
DEFAULT_CONSENT_TOKEN,
|
|
3451
4172
|
DEPTH_LIMIT,
|
|
4173
|
+
DEPTH_MARKER,
|
|
3452
4174
|
EventSchema,
|
|
3453
4175
|
EventTypeSchema,
|
|
4176
|
+
FileSink,
|
|
3454
4177
|
HttpSink,
|
|
3455
4178
|
INTENT_INSTRUCTIONS,
|
|
3456
4179
|
INTENT_PARAMS,
|
|
4180
|
+
MultiSink,
|
|
3457
4181
|
PRINCIPAL_FORM_HASHED,
|
|
3458
4182
|
PRINCIPAL_FORM_RAW,
|
|
3459
4183
|
PRINCIPAL_SOURCE_ASSERTED,
|