@goodtiming/baton-sdk 0.2.0 → 0.3.1

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/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
 
3
- declare const SDK_VERSION = "ts-0.2.0";
3
+ declare const SDK_VERSION = "ts-0.3.1";
4
4
 
5
5
  /**
6
6
  * Zod schemas + TS types for the Baton event stream per SPEC §11.4.
@@ -83,6 +83,19 @@ declare const SurfaceSnapshotPayloadSchema: z.ZodObject<{
83
83
  seam_augmentations: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
84
84
  }, z.core.$strict>;
85
85
  type SurfaceSnapshotPayload = z.infer<typeof SurfaceSnapshotPayloadSchema>;
86
+ /**
87
+ * What the SDK puts in `consent_token` when the vendor names no other value.
88
+ * Byte-for-byte Python's `baton.events.DEFAULT_CONSENT_TOKEN`, and the two
89
+ * must not drift: a collector comparing the field across arms would see two
90
+ * populations where there is one.
91
+ *
92
+ * **The field stays on the wire and the customer stops carrying it.** SPEC
93
+ * §2.3 governs the envelope, not the config, so defaulting here changes
94
+ * nothing a consumer sees — this is the value the onboarding recipe has been
95
+ * minting into `BATON_CONSENT_TOKEN` all along, now stated once instead of
96
+ * threaded through an environment variable that reads to nobody.
97
+ */
98
+ declare const DEFAULT_CONSENT_TOKEN = "customer-consented";
86
99
  declare const EventTypeSchema: z.ZodEnum<{
87
100
  tool_call_start: "tool_call_start";
88
101
  tool_call_end: "tool_call_end";
@@ -479,6 +492,20 @@ declare class HttpSink implements Sink {
479
492
  private drainChain;
480
493
  private beforeExitHandler;
481
494
  constructor(url: string, options: HttpSinkOptions);
495
+ /**
496
+ * What this sink shows when something prints it — never the bearer.
497
+ *
498
+ * ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it
499
+ * hangs off `BatonHandle.sink` and off the resolved config, so
500
+ * `console.log(handle.sink)` or a structured logger serialising either one
501
+ * wrote a publishable key into the vendor's logs. Found by the S2 test that
502
+ * asserts the DSN's own string does not survive resolution: it does not, and
503
+ * the key was one field further down. Same treatment as the parsed DSN —
504
+ * `toJSON` for serialisers, the inspect symbol for `console.log`, and
505
+ * `Symbol.for` rather than importing `node:util`, since this package runs on
506
+ * runtimes that have no such module.
507
+ */
508
+ toJSON(): Record<string, unknown>;
482
509
  write(event: Event): Promise<void>;
483
510
  flush(): Promise<void>;
484
511
  aclose(): Promise<void>;
@@ -519,10 +546,33 @@ interface SessionResolutionContext {
519
546
  }
520
547
  type ResolveSessionIdHook = (context: SessionResolutionContext) => string | null | undefined | Promise<string | null | undefined>;
521
548
  interface BatonConfig {
549
+ /** The packed connection string from /account — one value carrying the
550
+ * ingest host, the workspace, the server and the key that binds them.
551
+ *
552
+ * `withBaton(server, { dsn })` is the whole wrap block a DISTRIBUTABLE
553
+ * server ships with, and that is the case it exists for: a stdio server
554
+ * runs on every user's machine, so five `BATON_*` variables are five values
555
+ * that never arrive. Resolved explicit → `BATON_DSN` → unset.
556
+ *
557
+ * **Environment variables do not override it.** A server being re-onboarded
558
+ * has last install's `.env` beside the new inline DSN, and if these values
559
+ * fell through to `BATON_TENANT_ID` the way an unset field does, the stale
560
+ * file would win silently and the events would arrive under the previous
561
+ * server's name.
562
+ *
563
+ * Passing a dsn AND an explicit `vendorId`, `tenantId` or `sink` throws:
564
+ * two sources for one value cannot be reconciled without guessing, and a
565
+ * wrong guess routes a server's traffic under someone else's identity.
566
+ * Everything else — the display name, the scrubber, the injection modes,
567
+ * every identity option — is unaffected; set them alongside a dsn freely. */
568
+ dsn?: string;
522
569
  /** Short stable identifier for the SERVER whose surface is captured
523
570
  * (e.g. `"acme"`). Also the default annotation tool name prefix
524
- * (`{vendorId}_annotate`). This is not the account — see `tenantId`. */
525
- vendorId: string;
571
+ * (`{vendorId}_annotate`). This is not the account — see `tenantId`.
572
+ *
573
+ * Required unless a `dsn` supplies it — the DSN's last path segment IS this
574
+ * value, and it is what the key is BOUND to. */
575
+ vendorId?: string;
526
576
  /** Account identifier for the envelope's `tenant_id` (SPEC §11.4).
527
577
  *
528
578
  * **This is not `vendorId`, and conflating them is the bug this field
@@ -541,11 +591,29 @@ interface BatonConfig {
541
591
  tenantId?: string;
542
592
  /** Human-readable vendor name used in server instructions and the
543
593
  * annotation tool description — whitelabel obligation (SPEC §5.4): no
544
- * Baton-branded strings reach the calling agent. */
545
- vendorDisplayName: string;
594
+ * Baton-branded strings reach the calling agent.
595
+ *
596
+ * Defaults to the DSN's server segment VERBATIM when a `dsn` is given and
597
+ * this is not. Verbatim rather than prettified: this string reaches the
598
+ * calling agent, so inventing a capitalisation the vendor never chose would
599
+ * put a fabricated name in front of their users. */
600
+ vendorDisplayName?: string;
546
601
  /** End-user consent token attached to every emitted event per SPEC §2.3 —
547
- * required, the Console MUST reject events missing it. */
548
- consentToken: string;
602
+ * the Console MUST reject events missing it.
603
+ *
604
+ * **Defaulted, so the customer never has to carry it** — see
605
+ * `DEFAULT_CONSENT_TOKEN` for why the field stays on the wire regardless.
606
+ * Passing `""` explicitly still throws: a value the vendor deliberately
607
+ * emptied is a mistake, not a request for the default.
608
+ *
609
+ * ⚠ **No environment variable is read for this, and that is parity rather
610
+ * than a gap.** Python reads `BATON_CONSENT_TOKEN` on its `Client` door
611
+ * only; its `VendorConfig` — the door this package mirrors — takes a plain
612
+ * default, and the `os.environ["BATON_CONSENT_TOKEN"]` in its install
613
+ * examples is the RECIPE passing a value explicitly, not the SDK reading
614
+ * one. Adding the read here would make this arm honour a variable the
615
+ * equivalent Python door ignores. */
616
+ consentToken?: string;
549
617
  /** Where events go. Defaults to `new StdoutSink()` — zero-config dev mode. */
550
618
  sink?: Sink;
551
619
  /** Default `agent_runtime` when `_meta` heuristics can't detect one. */
@@ -696,6 +764,6 @@ interface SupportedMcpServer {
696
764
  registerTool(name: string, ...rest: unknown[]): unknown;
697
765
  }
698
766
  /** Install Baton into an `McpServer`. See module docstring for usage. */
699
- declare function withBaton(server: SupportedMcpServer, config: BatonConfig): BatonHandle;
767
+ declare function withBaton(server: SupportedMcpServer, supplied?: BatonConfig): BatonHandle;
700
768
 
701
- export { type AnnotationEvent, AnnotationEventSchema, type AnnotationPayload, AnnotationPayloadSchema, type BatonConfig, BatonHandle, DEPTH_LIMIT, type Event, EventSchema, type EventType, EventTypeSchema, HttpSink, type HttpSinkOptions, type ResolveSessionIdHook, SDK_VERSION, Scrubber, type SessionResolutionContext, type Sink, StdoutSink, type StdoutSinkOptions, type SupportedMcpServer, type SurfaceSnapshotEvent, SurfaceSnapshotEventSchema, type SurfaceSnapshotPayload, SurfaceSnapshotPayloadSchema, type ToolCallEndEvent, ToolCallEndEventSchema, type ToolCallEndPayload, ToolCallEndPayloadSchema, type ToolCallErrorEvent, ToolCallErrorEventSchema, type ToolCallErrorPayload, ToolCallErrorPayloadSchema, type ToolCallStartEvent, ToolCallStartEventSchema, type ToolCallStartPayload, ToolCallStartPayloadSchema, identityScrub, safeWrite, withBaton };
769
+ export { type AnnotationEvent, AnnotationEventSchema, type AnnotationPayload, AnnotationPayloadSchema, type BatonConfig, BatonHandle, DEFAULT_CONSENT_TOKEN, DEPTH_LIMIT, type Event, EventSchema, type EventType, EventTypeSchema, HttpSink, type HttpSinkOptions, type ResolveSessionIdHook, SDK_VERSION, Scrubber, type SessionResolutionContext, type Sink, StdoutSink, type StdoutSinkOptions, type SupportedMcpServer, type SurfaceSnapshotEvent, SurfaceSnapshotEventSchema, type SurfaceSnapshotPayload, SurfaceSnapshotPayloadSchema, type ToolCallEndEvent, ToolCallEndEventSchema, type ToolCallEndPayload, ToolCallEndPayloadSchema, type ToolCallErrorEvent, ToolCallErrorEventSchema, type ToolCallErrorPayload, ToolCallErrorPayloadSchema, type ToolCallStartEvent, ToolCallStartEventSchema, type ToolCallStartPayload, ToolCallStartPayloadSchema, identityScrub, safeWrite, withBaton };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
 
3
- declare const SDK_VERSION = "ts-0.2.0";
3
+ declare const SDK_VERSION = "ts-0.3.1";
4
4
 
5
5
  /**
6
6
  * Zod schemas + TS types for the Baton event stream per SPEC §11.4.
@@ -83,6 +83,19 @@ declare const SurfaceSnapshotPayloadSchema: z.ZodObject<{
83
83
  seam_augmentations: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
84
84
  }, z.core.$strict>;
85
85
  type SurfaceSnapshotPayload = z.infer<typeof SurfaceSnapshotPayloadSchema>;
86
+ /**
87
+ * What the SDK puts in `consent_token` when the vendor names no other value.
88
+ * Byte-for-byte Python's `baton.events.DEFAULT_CONSENT_TOKEN`, and the two
89
+ * must not drift: a collector comparing the field across arms would see two
90
+ * populations where there is one.
91
+ *
92
+ * **The field stays on the wire and the customer stops carrying it.** SPEC
93
+ * §2.3 governs the envelope, not the config, so defaulting here changes
94
+ * nothing a consumer sees — this is the value the onboarding recipe has been
95
+ * minting into `BATON_CONSENT_TOKEN` all along, now stated once instead of
96
+ * threaded through an environment variable that reads to nobody.
97
+ */
98
+ declare const DEFAULT_CONSENT_TOKEN = "customer-consented";
86
99
  declare const EventTypeSchema: z.ZodEnum<{
87
100
  tool_call_start: "tool_call_start";
88
101
  tool_call_end: "tool_call_end";
@@ -479,6 +492,20 @@ declare class HttpSink implements Sink {
479
492
  private drainChain;
480
493
  private beforeExitHandler;
481
494
  constructor(url: string, options: HttpSinkOptions);
495
+ /**
496
+ * What this sink shows when something prints it — never the bearer.
497
+ *
498
+ * ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it
499
+ * hangs off `BatonHandle.sink` and off the resolved config, so
500
+ * `console.log(handle.sink)` or a structured logger serialising either one
501
+ * wrote a publishable key into the vendor's logs. Found by the S2 test that
502
+ * asserts the DSN's own string does not survive resolution: it does not, and
503
+ * the key was one field further down. Same treatment as the parsed DSN —
504
+ * `toJSON` for serialisers, the inspect symbol for `console.log`, and
505
+ * `Symbol.for` rather than importing `node:util`, since this package runs on
506
+ * runtimes that have no such module.
507
+ */
508
+ toJSON(): Record<string, unknown>;
482
509
  write(event: Event): Promise<void>;
483
510
  flush(): Promise<void>;
484
511
  aclose(): Promise<void>;
@@ -519,10 +546,33 @@ interface SessionResolutionContext {
519
546
  }
520
547
  type ResolveSessionIdHook = (context: SessionResolutionContext) => string | null | undefined | Promise<string | null | undefined>;
521
548
  interface BatonConfig {
549
+ /** The packed connection string from /account — one value carrying the
550
+ * ingest host, the workspace, the server and the key that binds them.
551
+ *
552
+ * `withBaton(server, { dsn })` is the whole wrap block a DISTRIBUTABLE
553
+ * server ships with, and that is the case it exists for: a stdio server
554
+ * runs on every user's machine, so five `BATON_*` variables are five values
555
+ * that never arrive. Resolved explicit → `BATON_DSN` → unset.
556
+ *
557
+ * **Environment variables do not override it.** A server being re-onboarded
558
+ * has last install's `.env` beside the new inline DSN, and if these values
559
+ * fell through to `BATON_TENANT_ID` the way an unset field does, the stale
560
+ * file would win silently and the events would arrive under the previous
561
+ * server's name.
562
+ *
563
+ * Passing a dsn AND an explicit `vendorId`, `tenantId` or `sink` throws:
564
+ * two sources for one value cannot be reconciled without guessing, and a
565
+ * wrong guess routes a server's traffic under someone else's identity.
566
+ * Everything else — the display name, the scrubber, the injection modes,
567
+ * every identity option — is unaffected; set them alongside a dsn freely. */
568
+ dsn?: string;
522
569
  /** Short stable identifier for the SERVER whose surface is captured
523
570
  * (e.g. `"acme"`). Also the default annotation tool name prefix
524
- * (`{vendorId}_annotate`). This is not the account — see `tenantId`. */
525
- vendorId: string;
571
+ * (`{vendorId}_annotate`). This is not the account — see `tenantId`.
572
+ *
573
+ * Required unless a `dsn` supplies it — the DSN's last path segment IS this
574
+ * value, and it is what the key is BOUND to. */
575
+ vendorId?: string;
526
576
  /** Account identifier for the envelope's `tenant_id` (SPEC §11.4).
527
577
  *
528
578
  * **This is not `vendorId`, and conflating them is the bug this field
@@ -541,11 +591,29 @@ interface BatonConfig {
541
591
  tenantId?: string;
542
592
  /** Human-readable vendor name used in server instructions and the
543
593
  * annotation tool description — whitelabel obligation (SPEC §5.4): no
544
- * Baton-branded strings reach the calling agent. */
545
- vendorDisplayName: string;
594
+ * Baton-branded strings reach the calling agent.
595
+ *
596
+ * Defaults to the DSN's server segment VERBATIM when a `dsn` is given and
597
+ * this is not. Verbatim rather than prettified: this string reaches the
598
+ * calling agent, so inventing a capitalisation the vendor never chose would
599
+ * put a fabricated name in front of their users. */
600
+ vendorDisplayName?: string;
546
601
  /** End-user consent token attached to every emitted event per SPEC §2.3 —
547
- * required, the Console MUST reject events missing it. */
548
- consentToken: string;
602
+ * the Console MUST reject events missing it.
603
+ *
604
+ * **Defaulted, so the customer never has to carry it** — see
605
+ * `DEFAULT_CONSENT_TOKEN` for why the field stays on the wire regardless.
606
+ * Passing `""` explicitly still throws: a value the vendor deliberately
607
+ * emptied is a mistake, not a request for the default.
608
+ *
609
+ * ⚠ **No environment variable is read for this, and that is parity rather
610
+ * than a gap.** Python reads `BATON_CONSENT_TOKEN` on its `Client` door
611
+ * only; its `VendorConfig` — the door this package mirrors — takes a plain
612
+ * default, and the `os.environ["BATON_CONSENT_TOKEN"]` in its install
613
+ * examples is the RECIPE passing a value explicitly, not the SDK reading
614
+ * one. Adding the read here would make this arm honour a variable the
615
+ * equivalent Python door ignores. */
616
+ consentToken?: string;
549
617
  /** Where events go. Defaults to `new StdoutSink()` — zero-config dev mode. */
550
618
  sink?: Sink;
551
619
  /** Default `agent_runtime` when `_meta` heuristics can't detect one. */
@@ -696,6 +764,6 @@ interface SupportedMcpServer {
696
764
  registerTool(name: string, ...rest: unknown[]): unknown;
697
765
  }
698
766
  /** Install Baton into an `McpServer`. See module docstring for usage. */
699
- declare function withBaton(server: SupportedMcpServer, config: BatonConfig): BatonHandle;
767
+ declare function withBaton(server: SupportedMcpServer, supplied?: BatonConfig): BatonHandle;
700
768
 
701
- export { type AnnotationEvent, AnnotationEventSchema, type AnnotationPayload, AnnotationPayloadSchema, type BatonConfig, BatonHandle, DEPTH_LIMIT, type Event, EventSchema, type EventType, EventTypeSchema, HttpSink, type HttpSinkOptions, type ResolveSessionIdHook, SDK_VERSION, Scrubber, type SessionResolutionContext, type Sink, StdoutSink, type StdoutSinkOptions, type SupportedMcpServer, type SurfaceSnapshotEvent, SurfaceSnapshotEventSchema, type SurfaceSnapshotPayload, SurfaceSnapshotPayloadSchema, type ToolCallEndEvent, ToolCallEndEventSchema, type ToolCallEndPayload, ToolCallEndPayloadSchema, type ToolCallErrorEvent, ToolCallErrorEventSchema, type ToolCallErrorPayload, ToolCallErrorPayloadSchema, type ToolCallStartEvent, ToolCallStartEventSchema, type ToolCallStartPayload, ToolCallStartPayloadSchema, identityScrub, safeWrite, withBaton };
769
+ export { type AnnotationEvent, AnnotationEventSchema, type AnnotationPayload, AnnotationPayloadSchema, type BatonConfig, BatonHandle, DEFAULT_CONSENT_TOKEN, DEPTH_LIMIT, type Event, EventSchema, type EventType, EventTypeSchema, HttpSink, type HttpSinkOptions, type ResolveSessionIdHook, SDK_VERSION, Scrubber, type SessionResolutionContext, type Sink, StdoutSink, type StdoutSinkOptions, type SupportedMcpServer, type SurfaceSnapshotEvent, SurfaceSnapshotEventSchema, type SurfaceSnapshotPayload, SurfaceSnapshotPayloadSchema, type ToolCallEndEvent, ToolCallEndEventSchema, type ToolCallEndPayload, ToolCallEndPayloadSchema, type ToolCallErrorEvent, ToolCallErrorEventSchema, type ToolCallErrorPayload, ToolCallErrorPayloadSchema, type ToolCallStartEvent, ToolCallStartEventSchema, type ToolCallStartPayload, ToolCallStartPayloadSchema, identityScrub, safeWrite, withBaton };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.2.0";
2
+ var SDK_VERSION = "ts-0.3.1";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -41,6 +41,7 @@ var SurfaceSnapshotPayloadSchema = z.object({
41
41
  tools: z.array(z.record(z.string(), z.unknown())).default([]),
42
42
  seam_augmentations: z.record(z.string(), z.unknown()).default({})
43
43
  }).strict();
44
+ var DEFAULT_CONSENT_TOKEN = "customer-consented";
44
45
  var envelopeShape = {
45
46
  event_id: z.uuid().default(() => uuidv7()),
46
47
  tenant_id: z.string(),
@@ -264,6 +265,25 @@ var HttpSink = class _HttpSink {
264
265
  );
265
266
  this.fetchImpl = options.fetchImpl ?? fetch;
266
267
  }
268
+ /**
269
+ * What this sink shows when something prints it — never the bearer.
270
+ *
271
+ * ⚠ **A sink built from a DSN holds a key the vendor never typed**, and it
272
+ * hangs off `BatonHandle.sink` and off the resolved config, so
273
+ * `console.log(handle.sink)` or a structured logger serialising either one
274
+ * wrote a publishable key into the vendor's logs. Found by the S2 test that
275
+ * asserts the DSN's own string does not survive resolution: it does not, and
276
+ * the key was one field further down. Same treatment as the parsed DSN —
277
+ * `toJSON` for serialisers, the inspect symbol for `console.log`, and
278
+ * `Symbol.for` rather than importing `node:util`, since this package runs on
279
+ * runtimes that have no such module.
280
+ */
281
+ toJSON() {
282
+ return { url: this.url, apiKey: "<key>" };
283
+ }
284
+ [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
285
+ return this.toJSON();
286
+ }
267
287
  async write(event) {
268
288
  if (this.closed) throw new Error("HttpSink is closed");
269
289
  this.enqueue(event);
@@ -457,11 +477,6 @@ function extraMeta(extra) {
457
477
  // src/integrations/mcp/runtimeAdapter.ts
458
478
  function detectAgentRuntime(meta) {
459
479
  if (!meta) return null;
460
- const batonMeta = meta["baton"];
461
- if (batonMeta && typeof batonMeta === "object") {
462
- const runtime = batonMeta["agent_runtime"];
463
- if (typeof runtime === "string" && runtime) return runtime;
464
- }
465
480
  for (const key of Object.keys(meta)) {
466
481
  if (key.startsWith("claudecode/")) return "claude-code";
467
482
  }
@@ -566,8 +581,194 @@ function registerAnnotationTool(server, options) {
566
581
  return name;
567
582
  }
568
583
 
569
- // src/integrations/mcp/config.ts
584
+ // src/dsn.ts
570
585
  var VENDOR_ID_PATTERN = /^[a-zA-Z0-9_-]{1,48}$/;
586
+ var WORKSPACE_PATTERN = /^ten_[0-9a-fA-F]{32}$/;
587
+ var NOT_IN_A_HOST = /[\\\s\x00-\x1f\x7f]/;
588
+ var NOT_IN_A_KEY = /[\x00\n\r]/;
589
+ var PUBLISHABLE_PREFIX = "baton_pk_";
590
+ var SECRET_PREFIX = "baton_sk_";
591
+ var KEY_RUN = /baton_(?:pk|sk)_[A-Za-z0-9_%-]{8,}/g;
592
+ function looksLikeAKey(value) {
593
+ return value.startsWith(PUBLISHABLE_PREFIX) || value.startsWith(SECRET_PREFIX);
594
+ }
595
+ function containsKey(value) {
596
+ return sweep(value) !== value;
597
+ }
598
+ 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";
599
+ function warn(message) {
600
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
601
+ process.emitWarning(message);
602
+ }
603
+ }
604
+ function splitDsn(raw) {
605
+ const schemeEnd = raw.indexOf("://");
606
+ if (schemeEnd === -1) return null;
607
+ const scheme = raw.slice(0, schemeEnd).toLowerCase();
608
+ const rest = raw.slice(schemeEnd + 3);
609
+ const end = rest.search(/[/?#]/);
610
+ if (end === -1) return { scheme, netloc: rest, slash: "", path: "" };
611
+ const netloc = rest.slice(0, end);
612
+ if (rest[end] !== "/") {
613
+ return { scheme, netloc, slash: "", path: "" };
614
+ }
615
+ const afterSlash = rest.slice(end + 1);
616
+ const pathEnd = afterSlash.search(/[?#]/);
617
+ return {
618
+ scheme,
619
+ netloc,
620
+ slash: "/",
621
+ path: pathEnd === -1 ? afterSlash : afterSlash.slice(0, pathEnd)
622
+ };
623
+ }
624
+ function splitKeyFromAuthority(netloc) {
625
+ const index = netloc.lastIndexOf("@");
626
+ if (index === -1) return { key: "", at: false, authority: netloc };
627
+ return { key: netloc.slice(0, index), at: true, authority: netloc.slice(index + 1) };
628
+ }
629
+ function redact(raw) {
630
+ const parts = splitDsn(raw);
631
+ if (parts === null) return "<dsn>";
632
+ const { at, authority } = splitKeyFromAuthority(parts.netloc);
633
+ const assembled = at ? `${parts.scheme}://***@${authority}${parts.slash}${parts.path}` : `${parts.scheme}://<no key>@${parts.netloc}${parts.slash}${parts.path}`;
634
+ return sweep(assembled);
635
+ }
636
+ function sweep(message) {
637
+ return message.replace(KEY_RUN, "<key>");
638
+ }
639
+ function fail(message) {
640
+ throw new Error(sweep(message));
641
+ }
642
+ function dsnFromEnvironment() {
643
+ const fromEnv = typeof process !== "undefined" ? process.env?.BATON_DSN : void 0;
644
+ return fromEnv ? fromEnv : void 0;
645
+ }
646
+ function selectDsn(explicit, supplied, door) {
647
+ const conflicts = Object.keys(supplied).filter((name) => supplied[name]).sort();
648
+ if (explicit) {
649
+ if (conflicts.length > 0) {
650
+ fail(
651
+ `${door} got both a dsn and an explicit ${conflicts[0]} \u2014 the dsn already supplies it. Drop one: the dsn is the single value from /account, and ${conflicts[0]} is what it unpacks to.`
652
+ );
653
+ }
654
+ return explicit;
655
+ }
656
+ const ambient = dsnFromEnvironment();
657
+ if (ambient === void 0) return void 0;
658
+ if (conflicts.length > 0) {
659
+ warn(
660
+ `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.`
661
+ );
662
+ return void 0;
663
+ }
664
+ return ambient;
665
+ }
666
+ function parseDsn(raw) {
667
+ if (typeof raw !== "string" || raw.trim() === "") {
668
+ fail("dsn must be a non-empty string");
669
+ }
670
+ const dsn = raw.trim();
671
+ if (looksLikeAKey(dsn)) {
672
+ fail(`dsn is not a URL: ${BARE_KEY_HINT}`);
673
+ }
674
+ const safe = redact(dsn);
675
+ const parts = splitDsn(dsn);
676
+ if (parts === null || parts.scheme !== "https" && parts.scheme !== "http") {
677
+ fail(
678
+ `dsn ${safe} must start with https:// (or http:// for local development) \u2014 ${BARE_KEY_HINT}`
679
+ );
680
+ }
681
+ const { key, at, authority } = splitKeyFromAuthority(parts.netloc);
682
+ if (!at || !key) {
683
+ if (looksLikeAKey(parts.netloc)) {
684
+ fail(
685
+ `dsn ${safe} is a bare key with a scheme in front of it: ${BARE_KEY_HINT}. The full value also carries a host, your workspace and your server \u2014 https://baton_pk_...@host/ten_.../server`
686
+ );
687
+ }
688
+ const misplaced = parts.path.split("/").some((segment) => containsKey(segment));
689
+ const detail = misplaced ? "the key is in the PATH \u2014 it goes before an @" : "the value from /account has the key before an @";
690
+ fail(
691
+ `dsn ${safe} carries no key: ${detail}, as in https://baton_pk_...@host/ten_.../server`
692
+ );
693
+ }
694
+ if (NOT_IN_A_KEY.test(key)) {
695
+ fail(
696
+ `dsn ${safe} has a line break or a null inside its key \u2014 those can never be sent in an Authorization header, so this DSN could not have worked. Check for a line wrap where the value was copied.`
697
+ );
698
+ }
699
+ if (key.includes(":")) {
700
+ fail(
701
+ `dsn ${safe} has a ':' in its key \u2014 a DSN carries one credential and no password field`
702
+ );
703
+ }
704
+ if (!authority) {
705
+ fail(`dsn ${safe} has no host`);
706
+ }
707
+ if (NOT_IN_A_HOST.test(authority)) {
708
+ fail(
709
+ `dsn ${safe} has whitespace, a control character or a backslash inside its host. Those are silently REMOVED or reinterpreted when a URL is parsed, so the address dialled would not be the one you wrote \u2014 check for a line wrap or a stray space where the value was copied.`
710
+ );
711
+ }
712
+ let hostReason = null;
713
+ let parsedAuthority = null;
714
+ try {
715
+ parsedAuthority = new URL(`${parts.scheme}://${authority}`);
716
+ } catch (error) {
717
+ hostReason = error instanceof Error ? error.constructor.name : "Error";
718
+ }
719
+ if (parsedAuthority === null) {
720
+ fail(`dsn ${safe} is not a parseable URL (${hostReason ?? "Error"})`);
721
+ }
722
+ const segments = parts.path.split("/").filter((segment) => segment !== "");
723
+ const [workspace, server, ...extra] = segments;
724
+ if (workspace === void 0 || server === void 0 || extra.length > 0) {
725
+ fail(
726
+ `dsn ${safe} must carry exactly two path segments \u2014 the workspace and the server, as in /ten_<32 hex>/<server>. A missing server is never defaulted: it is what the key is bound to.`
727
+ );
728
+ }
729
+ for (const [slot, segment] of [
730
+ ["workspace", workspace],
731
+ ["server", server]
732
+ ]) {
733
+ if (containsKey(segment)) {
734
+ fail(
735
+ `dsn ${safe} has a KEY in the ${slot} slot. The key goes before the @, and the path carries the workspace and the server: https://baton_pk_...@host/ten_<32 hex>/<server>`
736
+ );
737
+ }
738
+ }
739
+ if (!WORKSPACE_PATTERN.test(workspace)) {
740
+ fail(
741
+ `dsn ${safe} has ${JSON.stringify(workspace)} where the workspace belongs \u2014 expected ten_ followed by 32 hex characters. If the two path segments are the right way round, this is not a Baton DSN.`
742
+ );
743
+ }
744
+ if (!VENDOR_ID_PATTERN.test(server)) {
745
+ fail(
746
+ `dsn ${safe} has ${JSON.stringify(server)} where the server belongs \u2014 it must match ${VENDOR_ID_PATTERN.source}, because this value becomes the annotation tool name prefix as well as the envelope's vendor_id.`
747
+ );
748
+ }
749
+ if (key.startsWith(SECRET_PREFIX)) {
750
+ warn(
751
+ `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.`
752
+ );
753
+ }
754
+ return sealKey({
755
+ origin: `${parts.scheme}://${authority}`,
756
+ tenantId: workspace,
757
+ vendorId: server,
758
+ key
759
+ });
760
+ }
761
+ function sealKey(dsn) {
762
+ const shown = { origin: dsn.origin, tenantId: dsn.tenantId, vendorId: dsn.vendorId, key: "<key>" };
763
+ Object.defineProperty(dsn, "toJSON", { value: () => shown, enumerable: false });
764
+ Object.defineProperty(dsn, /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom"), {
765
+ value: () => shown,
766
+ enumerable: false
767
+ });
768
+ return dsn;
769
+ }
770
+
771
+ // src/integrations/mcp/config.ts
571
772
  var INTENT_PARAM_MODES = /* @__PURE__ */ new Set(["optional", "required", "off"]);
572
773
  function resolveTenantId(explicit, vendorId) {
573
774
  if (explicit) return explicit;
@@ -575,7 +776,62 @@ function resolveTenantId(explicit, vendorId) {
575
776
  if (fromEnv) return fromEnv;
576
777
  return vendorId;
577
778
  }
779
+ function resolveBatonConfig(config) {
780
+ const dsnString = selectDsn(
781
+ config.dsn,
782
+ {
783
+ // Truthiness per field, mirroring Python's `bool()` / `is not None`
784
+ // split: an empty `vendorId` is an unset one, while an explicitly
785
+ // supplied `tenantId` or `sink` is a conflict whatever it holds.
786
+ vendorId: Boolean(config.vendorId),
787
+ tenantId: config.tenantId !== void 0,
788
+ sink: config.sink !== void 0
789
+ },
790
+ "BatonConfig"
791
+ );
792
+ if (dsnString === void 0) {
793
+ const defaulted = {
794
+ ...config,
795
+ consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
796
+ };
797
+ validateBatonConfig(defaulted);
798
+ return defaulted;
799
+ }
800
+ const dsn = parseDsn(dsnString);
801
+ const rest = { ...config };
802
+ delete rest.dsn;
803
+ const identity = {
804
+ ...rest,
805
+ vendorId: dsn.vendorId,
806
+ tenantId: dsn.tenantId,
807
+ // `??`, for the same reason as `consentToken` directly below, and the
808
+ // inconsistency was worth fixing rather than mirroring: with no dsn,
809
+ // `vendorDisplayName: ""` is REFUSED by validation; with one, `||` quietly
810
+ // substituted the server slug. One input, two answers, decided by whether
811
+ // a dsn happens to be present — and this string reaches the calling agent
812
+ // in the server instructions and the annotation tool description, which is
813
+ // the whitelabel obligation the validator cites when it refuses the empty
814
+ // one. ⚠ Python uses `or` here and still has the inconsistency.
815
+ vendorDisplayName: config.vendorDisplayName ?? dsn.vendorId,
816
+ // `??`, not `||`: an explicit empty string must survive to the validation
817
+ // below and be REFUSED there, rather than be quietly replaced by the
818
+ // default it was deliberately not left as.
819
+ consentToken: config.consentToken ?? DEFAULT_CONSENT_TOKEN
820
+ };
821
+ validateBatonConfig(identity);
822
+ return {
823
+ ...identity,
824
+ // The origin is scheme + authority; `HttpSink` appends `/v0/events`
825
+ // itself, exactly as it does for an explicitly-constructed sink.
826
+ sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
827
+ };
828
+ }
578
829
  function validateBatonConfig(config) {
830
+ if (!config.vendorId) {
831
+ throw new Error(
832
+ "BatonConfig needs a vendorId \u2014 either directly, or via a dsn whose last path segment names the server (see /account)."
833
+ );
834
+ }
579
835
  if (!VENDOR_ID_PATTERN.test(config.vendorId)) {
580
836
  throw new Error(
581
837
  `vendorId ${JSON.stringify(config.vendorId)} must match ${VENDOR_ID_PATTERN.source} \u2014 used as the default annotation tool name prefix.`
@@ -586,6 +842,11 @@ function validateBatonConfig(config) {
586
842
  "BatonConfig.vendorDisplayName is required \u2014 used in server instructions and the annotation tool description (whitelabel obligation, SPEC \xA75.4)."
587
843
  );
588
844
  }
845
+ if (config.consentToken !== void 0 && !config.consentToken) {
846
+ throw new Error(
847
+ "BatonConfig.consentToken was set to an empty string, and events without a valid consent_token MUST be rejected by the consumer per SPEC \xA72.3. Omit it to take the SDK's default."
848
+ );
849
+ }
589
850
  if (!config.consentToken) {
590
851
  throw new Error(
591
852
  "BatonConfig.consentToken is required per SPEC \xA72.3 \u2014 events without a valid consent_token MUST be rejected by the consumer."
@@ -598,6 +859,38 @@ function validateBatonConfig(config) {
598
859
  }
599
860
  }
600
861
 
862
+ // src/optout.ts
863
+ var SWITCH = "BATON_DISABLED";
864
+ var OFF_VALUES = /* @__PURE__ */ new Set(["", "0", "false", "no", "off"]);
865
+ function captureDisabled() {
866
+ const value = typeof process !== "undefined" ? process.env?.[SWITCH] : void 0;
867
+ if (value !== void 0 && !OFF_VALUES.has(value.trim().toLowerCase())) {
868
+ return SWITCH;
869
+ }
870
+ return null;
871
+ }
872
+ function logDisabled(switchName, surface) {
873
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") {
874
+ process.emitWarning(
875
+ `baton: ${switchName} is set, so capture is OFF \u2014 ${surface} installed nothing and will emit no events. Unset it to re-enable.`
876
+ );
877
+ }
878
+ }
879
+ var DisabledSink = class {
880
+ // The parameter is omitted rather than named-and-ignored: a narrower
881
+ // signature satisfies `Sink` in TypeScript, and there is nothing to do with
882
+ // an event that cannot arrive.
883
+ async write() {
884
+ return;
885
+ }
886
+ async flush() {
887
+ return;
888
+ }
889
+ async aclose() {
890
+ return;
891
+ }
892
+ };
893
+
601
894
  // src/integrations/mcp/handle.ts
602
895
  var BatonHandle = class {
603
896
  sink;
@@ -1113,8 +1406,25 @@ function wireEntry(name, entry, ctx) {
1113
1406
  };
1114
1407
  }
1115
1408
  }
1116
- function withBaton(server, config) {
1117
- validateBatonConfig(config);
1409
+ function withBaton(server, supplied = {}) {
1410
+ const disabledBy = captureDisabled();
1411
+ if (disabledBy !== null) {
1412
+ logDisabled(disabledBy, "withBaton");
1413
+ return new BatonHandle({
1414
+ // A sink the VENDOR constructed is held rather than dropped, so their
1415
+ // `handle.aclose()` still releases it — we took ownership of that object
1416
+ // the moment they passed it, and the switch does not undo that. Nothing
1417
+ // writes to it: nothing is wrapped.
1418
+ sink: supplied.sink ?? new DisabledSink(),
1419
+ // Empty, and a constant, because when the switch is on nothing was
1420
+ // resolved: inventing a session id would put a real identifier on a
1421
+ // handle whose whole meaning is that no events exist under it.
1422
+ vendorId: "",
1423
+ sessionId: "baton-disabled",
1424
+ annotationToolName: ""
1425
+ });
1426
+ }
1427
+ const config = resolveBatonConfig(supplied);
1118
1428
  const sink = config.sink ?? new StdoutSink();
1119
1429
  const annotationToolName = config.annotationToolName || `${config.vendorId}_annotate`;
1120
1430
  const intentParamMode = config.intentParamMode ?? "optional";
@@ -1232,6 +1542,7 @@ export {
1232
1542
  AnnotationEventSchema,
1233
1543
  AnnotationPayloadSchema,
1234
1544
  BatonHandle,
1545
+ DEFAULT_CONSENT_TOKEN,
1235
1546
  DEPTH_LIMIT,
1236
1547
  EventSchema,
1237
1548
  EventTypeSchema,