@phosphorco/bb-cross-references 0.3.0 → 0.4.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/react.js CHANGED
@@ -365,7 +365,7 @@ function referenceLabelError(value) {
365
365
  }
366
366
 
367
367
  // src/index.ts
368
- import { z as z3 } from "zod";
368
+ import { z as z4 } from "zod";
369
369
 
370
370
  // src/recognition.ts
371
371
  import { z } from "zod";
@@ -415,9 +415,648 @@ function verifiedFileIdentityRecord(value) {
415
415
  throw new Error("Verified file mapping exceeds its bound.");
416
416
  return json;
417
417
  }
418
- // src/evidence-v2.ts
418
+ // src/producer.ts
419
419
  import { z as z2 } from "zod";
420
- import { ContextBundleV1Schema, SafeHrefSchema as SafeHrefSchema2, CandidateV1Schema, SourceIdentitySchema as SourceIdentitySchema2 } from "@phosphorco/bb-context-recognition";
420
+ import { canonicalJson as canonicalJson2, SafeHrefSchema as SafeHrefSchema2, SourceIdentitySchema as SourceIdentitySchema2 } from "@phosphorco/bb-context-recognition";
421
+ var PRODUCER_METHODS = Object.freeze({ describe: "crossReferencesProducer.describe", getState: "crossReferencesProducerV1GetState", apply: "crossReferencesProducerV1Apply", reportStatus: "crossReferencesProducerV1ReportStatus" });
422
+ var BRIEF_NAVIGATION_METHODS = Object.freeze({ describe: "threadBriefNavigation.describe", resolve: "threadBriefNavigationV1ResolveHeading" });
423
+ var BRIEF_LIMITS = Object.freeze({ inputBytes: 1048576, statusBytes: 16384, responseBytes: 1048576, locations: 512, perTarget: 100, headingBytes: 256, describeMs: 1000, callMs: 5000, readMs: 2000, navigationInputBytes: 8192, navigationOutputBytes: 16384 });
424
+ var DISPLAY_POLICY_LIMITS = Object.freeze({ valueChars: 1048576, valueBytes: 1048576, fields: 8192, distinct: 4096, sourceBytes: 2097152, work: 8388608, views: 4, tokens: 128, tokenChars: 4096, tokenBytes: 16384 });
425
+ var BRIEF_LIMIT_CODES = ["target-count", "projection-bytes", "occurrence-count", "per-target-occurrences", "heading-bytes", "envelope-bytes", "presentation-label-bytes", "presentation-detail-bytes", "presentation-url-bytes", "presentation-bytes"];
426
+ var roles = ["heading", "source-label", "target-label", "detail", "presentation-href", "provenance", "codec", "authored-url", "required-identity"];
427
+ function wellFormed(s) {
428
+ for (const c of s) {
429
+ const n = c.codePointAt(0);
430
+ if (n >= 55296 && n <= 57343)
431
+ return false;
432
+ }
433
+ return true;
434
+ }
435
+ function control(s) {
436
+ for (const c of s) {
437
+ const n = c.codePointAt(0);
438
+ if (n < 32 || n >= 127 && n <= 159)
439
+ return true;
440
+ }
441
+ return false;
442
+ }
443
+ var space = (c) => c.trim() === "";
444
+
445
+ class PolicyStop {
446
+ reason;
447
+ constructor(reason) {
448
+ this.reason = reason;
449
+ }
450
+ }
451
+
452
+ class PolicyHit {
453
+ reason;
454
+ constructor(reason) {
455
+ this.reason = reason;
456
+ }
457
+ }
458
+ function charge(m, n) {
459
+ if (n < 0 || m.work + n > DISPLAY_POLICY_LIMITS.work)
460
+ throw new PolicyStop("source-work-limit");
461
+ m.work += n;
462
+ }
463
+ var entities = { amp: "&", colon: ":", sol: "/", bsol: "\\", quest: "?", num: "#", percnt: "%", equals: "=", commat: "@", semi: ";", Tab: "\t", NewLine: `
464
+ ` };
465
+ function decodeView(s, m) {
466
+ charge(m, s.length * 2);
467
+ const out = [];
468
+ let changed = false;
469
+ for (let i = 0;i < s.length; ) {
470
+ const c = s[i];
471
+ if (c === "%" && /[0-9a-f]/i.test(s[i + 1] ?? "")) {
472
+ const bytes = [];
473
+ while (s[i] === "%") {
474
+ const h = s.slice(i + 1, i + 3);
475
+ if (h.length !== 2 || !/^[0-9a-f]{2}$/i.test(h))
476
+ throw new PolicyStop("encoding-ambiguity");
477
+ bytes.push(parseInt(h, 16));
478
+ i += 3;
479
+ }
480
+ try {
481
+ out.push(new TextDecoder("utf-8", { fatal: true }).decode(Uint8Array.from(bytes)));
482
+ } catch {
483
+ throw new PolicyStop("encoding-ambiguity");
484
+ }
485
+ changed = true;
486
+ continue;
487
+ }
488
+ if (c === "\\") {
489
+ const n = s[i + 1];
490
+ if (n === "u") {
491
+ const h = s.slice(i + 2, i + 6);
492
+ if (!/^[0-9a-f]{4}$/i.test(h))
493
+ throw new PolicyStop("encoding-ambiguity");
494
+ let value = String.fromCharCode(parseInt(h, 16));
495
+ i += 6;
496
+ if (value.charCodeAt(0) >= 55296 && value.charCodeAt(0) <= 56319) {
497
+ if (s.slice(i, i + 2) !== "\\u" || !/^[0-9a-f]{4}$/i.test(s.slice(i + 2, i + 6)))
498
+ throw new PolicyStop("encoding-ambiguity");
499
+ value += String.fromCharCode(parseInt(s.slice(i + 2, i + 6), 16));
500
+ i += 6;
501
+ }
502
+ if (!wellFormed(value))
503
+ throw new PolicyStop("encoding-ambiguity");
504
+ out.push(value);
505
+ changed = true;
506
+ continue;
507
+ }
508
+ const escape = { "/": "/", "\\": "\\", '"': '"', b: "\b", f: "\f", n: `
509
+ `, r: "\r", t: "\t" };
510
+ if (n === undefined || escape[n] === undefined)
511
+ throw new PolicyStop("encoding-ambiguity");
512
+ out.push(escape[n]);
513
+ i += 2;
514
+ changed = true;
515
+ continue;
516
+ }
517
+ if (c === "&" && /[A-Za-z0-9_#]/.test(s[i + 1] ?? "")) {
518
+ let j = i + 1;
519
+ while (j < s.length && j - i <= 32 && !space(s[j]) && s[j] !== ";" && s[j] !== "&")
520
+ j++;
521
+ if (s[j] === ";") {
522
+ const name = s.slice(i + 1, j);
523
+ let decoded;
524
+ if (name.startsWith("#")) {
525
+ const hex = name[1]?.toLowerCase() === "x", digits = name.slice(hex ? 2 : 1);
526
+ if (!(hex ? /^[a-f0-9]+$/i : /^[0-9]+$/).test(digits))
527
+ throw new PolicyStop("encoding-ambiguity");
528
+ const cp = parseInt(digits, hex ? 16 : 10);
529
+ if (cp > 1114111 || cp >= 55296 && cp <= 57343)
530
+ throw new PolicyStop("encoding-ambiguity");
531
+ decoded = String.fromCodePoint(cp);
532
+ } else
533
+ decoded = Object.hasOwn(entities, name) ? entities[name] : undefined;
534
+ if (decoded === undefined)
535
+ throw new PolicyStop("encoding-ambiguity");
536
+ out.push(decoded);
537
+ i = j + 1;
538
+ changed = true;
539
+ continue;
540
+ }
541
+ const partial = s.slice(i + 1, j);
542
+ if (s[i + 1] === "#" || j - i > 32 || !partial.includes("=") && Object.keys(entities).some((name) => name.startsWith(partial) || partial.startsWith(name)))
543
+ throw new PolicyStop("encoding-ambiguity");
544
+ }
545
+ out.push(c);
546
+ i++;
547
+ }
548
+ return { text: out.join(""), changed };
549
+ }
550
+ function scanPolicy(s, m, tokens) {
551
+ charge(m, s.length * 4);
552
+ const token = (value) => {
553
+ if (++tokens.count > DISPLAY_POLICY_LIMITS.tokens)
554
+ throw new PolicyStop("token-limit");
555
+ if (value.length > DISPLAY_POLICY_LIMITS.tokenChars)
556
+ throw new PolicyStop("token-limit");
557
+ charge(m, value.length * 2);
558
+ if (utf8ByteLength(value) > DISPLAY_POLICY_LIMITS.tokenBytes)
559
+ throw new PolicyStop("token-limit");
560
+ };
561
+ const url = (value) => {
562
+ token(value);
563
+ let u;
564
+ try {
565
+ u = new URL(value, "https://display-policy.invalid");
566
+ } catch {
567
+ throw new PolicyStop("encoding-ambiguity");
568
+ }
569
+ if (u.username || u.password)
570
+ throw new PolicyHit("url-credentials");
571
+ if (hasSensitiveUrlParameter(u))
572
+ throw new PolicyHit("sensitive-url-parameter");
573
+ if (!SafeHrefSchema2.safeParse(value).success)
574
+ throw new PolicyHit("unsafe-url-form");
575
+ };
576
+ for (let at = 0;at < s.length; ) {
577
+ while (at < s.length && space(s[at]))
578
+ at++;
579
+ const start = at;
580
+ while (at < s.length && !space(s[at]))
581
+ at++;
582
+ const run = s.slice(start, at);
583
+ if (!run)
584
+ continue;
585
+ let hasScheme = false;
586
+ for (let i = 0;i < run.length; i++) {
587
+ const tail = run.slice(i, i + 8).toLowerCase();
588
+ if (tail.startsWith("http://") || tail.startsWith("https://")) {
589
+ hasScheme = true;
590
+ if (run.length - i > DISPLAY_POLICY_LIMITS.tokenChars)
591
+ throw new PolicyStop("token-limit");
592
+ url(run.slice(i));
593
+ } else if (run[i] === ":" && run.slice(i + 1, i + 3) === "//" && i > 0 && !run.slice(Math.max(0, i - 5), i).toLowerCase().endsWith("http") && !run.slice(Math.max(0, i - 5), i).toLowerCase().endsWith("https"))
594
+ throw new PolicyHit("unsafe-url-form");
595
+ }
596
+ if (!hasScheme) {
597
+ const slash = run.indexOf("/");
598
+ if (slash >= 0) {
599
+ if (run.length - slash > DISPLAY_POLICY_LIMITS.tokenChars)
600
+ throw new PolicyStop("token-limit");
601
+ url(run.slice(slash));
602
+ }
603
+ }
604
+ for (let i = 0;i < run.length; i++)
605
+ if (run[i] === "=") {
606
+ let begin = i;
607
+ while (begin > 0 && /[A-Za-z0-9_%.-]/.test(run[begin - 1]))
608
+ begin--;
609
+ const name = run.slice(begin, i);
610
+ if (!name)
611
+ continue;
612
+ token(name);
613
+ const u = new URL("https://display-policy.invalid");
614
+ u.search = "?" + name + "=value";
615
+ if (hasSensitiveUrlParameter(u))
616
+ throw new PolicyHit("credential-shaped-token");
617
+ }
618
+ }
619
+ }
620
+ function classify(value, m) {
621
+ const before = m.work;
622
+ let views = 0;
623
+ const tokens = { count: 0 };
624
+ const result = (extra) => ({ version: 1, workUnits: m.work - before, decodedViews: views, ...extra });
625
+ try {
626
+ if (value.length > DISPLAY_POLICY_LIMITS.valueChars)
627
+ throw new PolicyStop("input-limit");
628
+ charge(m, value.length * 3);
629
+ if (!wellFormed(value))
630
+ throw new PolicyStop("ill-formed-unicode");
631
+ if (utf8ByteLength(value) > DISPLAY_POLICY_LIMITS.valueBytes)
632
+ throw new PolicyStop("input-limit");
633
+ let current = value;
634
+ for (let i = 0;i < DISPLAY_POLICY_LIMITS.views; i++) {
635
+ views++;
636
+ if (control(current))
637
+ throw new PolicyStop("control-character");
638
+ scanPolicy(current, m, tokens);
639
+ const decoded = decodeView(current, m);
640
+ if (!decoded.changed)
641
+ return result({ state: "safe", coverage: "complete" });
642
+ if (i === DISPLAY_POLICY_LIMITS.views - 1)
643
+ throw new PolicyStop("encoding-limit");
644
+ current = decoded.text;
645
+ }
646
+ throw new PolicyStop("encoding-limit");
647
+ } catch (e) {
648
+ if (e instanceof PolicyHit)
649
+ return result({ state: "unsafe", coverage: "complete-for-hit", reason: e.reason });
650
+ if (e instanceof PolicyStop)
651
+ return result({ state: "unclassified", coverage: "incomplete", reason: e.reason });
652
+ throw e;
653
+ }
654
+ }
655
+ function classifyBriefDisplayTextV1(value) {
656
+ if (typeof value !== "string")
657
+ throw new Error("Invalid display-policy argument.");
658
+ return classify(value, { work: 0 });
659
+ }
660
+ function classifyBriefDisplayFieldsV1(fields) {
661
+ if (!Array.isArray(fields) || fields.length > DISPLAY_POLICY_LIMITS.fields)
662
+ return { version: 1, state: "unclassified", reason: "field-limit", results: [], usage: { distinctValues: 0, originalUtf8Bytes: 0, workUnits: 0 }, complete: false };
663
+ for (const f of fields)
664
+ if (!f || !Array.isArray(f.key) || f.key.length > 8 || f.key.some((n) => typeof n !== "number" || !Number.isSafeInteger(n) || n < 0 || n > 8191) || !roles.includes(f.role) || typeof f.value !== "string")
665
+ throw new Error("Invalid display-policy field.");
666
+ const ordered = fields.map((f, i) => ({ f, i })).sort((a, b) => Number(b.f.role === "required-identity") - Number(a.f.role === "required-identity") || compareNumbers(a.f.key, b.f.key) || a.i - b.i);
667
+ const meter = { work: 0 }, cache = new Map, results = { version: 1, state: "classified", results: [], usage: { distinctValues: 0, originalUtf8Bytes: 0, workUnits: 0 }, complete: true };
668
+ for (const { f, i } of ordered) {
669
+ let r = cache.get(f.value);
670
+ if (!r) {
671
+ const incomplete = (reason) => ({ version: 1, state: "unclassified", coverage: "incomplete", reason, workUnits: 0, decodedViews: 0 });
672
+ if (cache.size >= DISPLAY_POLICY_LIMITS.distinct)
673
+ r = incomplete("field-limit");
674
+ else {
675
+ try {
676
+ if (f.value.length > DISPLAY_POLICY_LIMITS.valueChars)
677
+ r = incomplete("input-limit");
678
+ else {
679
+ charge(meter, f.value.length);
680
+ const bytes = utf8ByteLength(f.value);
681
+ if (results.usage.originalUtf8Bytes + bytes > DISPLAY_POLICY_LIMITS.sourceBytes)
682
+ r = incomplete("source-work-limit");
683
+ else {
684
+ results.usage.originalUtf8Bytes += bytes;
685
+ r = classify(f.value, meter);
686
+ }
687
+ }
688
+ } catch (e) {
689
+ if (e instanceof PolicyStop)
690
+ r = incomplete(e.reason);
691
+ else
692
+ throw e;
693
+ }
694
+ cache.set(f.value, r);
695
+ }
696
+ }
697
+ results.results[i] = { key: f.key, result: r };
698
+ if (r.state !== "safe")
699
+ results.complete = false;
700
+ }
701
+ results.usage.distinctValues = cache.size;
702
+ results.usage.workUnits = meter.work;
703
+ return results;
704
+ }
705
+ function compareNumbers(a, b) {
706
+ for (let i = 0;i < Math.min(a.length, b.length); i++)
707
+ if (a[i] !== b[i])
708
+ return a[i] - b[i];
709
+ return a.length - b.length;
710
+ }
711
+ var integer = z2.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
712
+ var positive = integer.min(1);
713
+ var digest = z2.string().regex(/^[a-f0-9]{64}$/);
714
+ var bytes = (n) => z2.string().refine(wellFormed, "Malformed Unicode.").refine((v) => utf8ByteLength(v) <= n, "Text byte bound exceeded.");
715
+ var plugin = z2.string().regex(/^[a-z][a-z0-9._-]{0,63}$/);
716
+ var identity = z2.strictObject({ provider: z2.string(), keys: z2.record(z2.string(), z2.string()) }).superRefine((v, c) => {
717
+ try {
718
+ canonicalizeIdentity(v);
719
+ } catch {
720
+ c.addIssue({ code: "custom", message: "Invalid resource identity." });
721
+ }
722
+ });
723
+ var briefFileSchema = z2.strictObject({ kind: z2.literal("thread-storage"), threadId: z2.string().regex(/^[A-Za-z0-9_-]{1,128}$/), path: z2.literal("BRIEF.md") });
724
+ var safeHref = SafeHrefSchema2.refine((v) => utf8ByteLength(v) <= 16384 && !hasSensitiveUrlParameter(new URL(v, "https://display-policy.invalid")), "Unsafe URL.");
725
+ var cause = z2.enum(["policy", "unclassified"]);
726
+ var withheld = (display) => z2.strictObject({ state: z2.literal("withheld"), digest, display: z2.literal(display), cause });
727
+ var briefHeadingSchema = z2.union([z2.null(), z2.strictObject({ state: z2.literal("named"), text: bytes(256) }), withheld("Heading withheld")]);
728
+ var labelText = bytes(256).refine((v) => !control(v) && v.trim().length > 0, "Invalid label.");
729
+ var briefSourceLabelSchema = z2.union([z2.strictObject({ state: z2.literal("safe"), text: labelText }), withheld("Brief")]);
730
+ var briefTargetLabelSchema = z2.union([z2.strictObject({ state: z2.literal("safe"), text: labelText }), withheld("Reference")]);
731
+ var detail = z2.union([z2.null(), z2.strictObject({ state: z2.literal("safe"), text: bytes(1024).refine((v) => !control(v) && v.trim().length > 0) }), withheld("Details withheld")]);
732
+ var presentationHref = z2.union([z2.strictObject({ state: z2.literal("absent") }), z2.strictObject({ state: z2.literal("exact"), href: safeHref.refine((v) => utf8ByteLength(v) <= 2048 && !control(v) && v.trim().length > 0) }), withheld("Destination withheld")]);
733
+ var presentation = (label) => z2.strictObject({ label, detail, url: presentationHref });
734
+ var briefSourcePresentationSchema = presentation(briefSourceLabelSchema);
735
+ var briefTargetPresentationSchema = presentation(briefTargetLabelSchema);
736
+ var span = z2.strictObject({ start: integer, end: positive }).refine((v) => v.end > v.start);
737
+ var provenanceValue = z2.strictObject({
738
+ pluginId: plugin,
739
+ origin: z2.enum(["builtin", "contributed"]),
740
+ confidence: z2.enum(["high", "medium", "low"]),
741
+ recognition: z2.strictObject({ basis: z2.enum(["explicit", "text-url", "existing-link", "git-remote", "context"]), explanation: bytes(1024).min(1), evidence: z2.strictObject({ span: span.optional(), link: integer.optional(), remote: bytes(1024).optional() }).optional() }),
742
+ source: SourceIdentitySchema2.strict(),
743
+ authoredHref: safeHref.optional(),
744
+ verifiedFile: VerifiedFileTargetSchema.optional()
745
+ });
746
+ var provenanceSummary = z2.strictObject({ pluginId: plugin, origin: z2.enum(["builtin", "contributed"]), confidence: z2.enum(["high", "medium", "low"]), basis: z2.enum(["explicit", "text-url", "existing-link", "git-remote", "context"]) });
747
+ var briefProvenanceSchema = z2.union([z2.strictObject({ state: z2.literal("safe"), value: provenanceValue }), withheld("Recognition details withheld").extend({ summary: provenanceSummary })]);
748
+ var codecProof = z2.discriminatedUnion("kind", [
749
+ z2.strictObject({ kind: z2.literal("recognition"), source: SourceIdentitySchema2.strict() }),
750
+ z2.strictObject({ kind: z2.literal("thread"), source: SourceIdentitySchema2.strict(), verified: z2.strictObject({ id: z2.string(), projectId: z2.string() }) }),
751
+ z2.strictObject({ kind: z2.literal("file"), verified: VerifiedFileTargetSchema }),
752
+ z2.strictObject({ kind: z2.literal("url"), href: safeHref })
753
+ ]);
754
+ var codec = z2.union([z2.strictObject({ state: z2.literal("available"), value: codecProof }), withheld("Identity metadata withheld")]);
755
+ var briefAuthoredUrlSchema = z2.union([z2.strictObject({ state: z2.literal("exact"), href: safeHref }), z2.strictObject({ state: z2.literal("not-url") }), z2.strictObject({ state: z2.literal("unknown") }), withheld("Destination withheld")]);
756
+ var briefFrameSchema = z2.strictObject({
757
+ codec: z2.literal("utf8-fatal-bom-consumed-v1"),
758
+ rawBytes: integer.max(1048576),
759
+ bomBytes: z2.union([z2.literal(0), z2.literal(3)]),
760
+ fileUtf16Length: integer.max(1048576),
761
+ bodyBase: z2.strictObject({ startUtf16: integer, startLine: positive, utf16Length: integer }),
762
+ lineMapping: z2.strictObject({ codec: z2.literal("native-file-lines-v1"), fileLineCount: positive })
763
+ }).superRefine((v, c) => {
764
+ if (v.rawBytes < v.bomBytes || v.bodyBase.startUtf16 + v.bodyBase.utf16Length > v.fileUtf16Length || v.bodyBase.startLine > v.lineMapping.fileLineCount)
765
+ c.addIssue({ code: "custom", message: "Invalid source frame." });
766
+ });
767
+ var briefLocatorSchema = z2.strictObject({
768
+ kind: z2.literal("thread-brief"),
769
+ threadId: z2.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
770
+ file: briefFileSchema,
771
+ sourceContentRevision: digest,
772
+ section: z2.strictObject({ heading: briefHeadingSchema, line: positive }),
773
+ location: z2.strictObject({ kind: z2.literal("line"), line: positive, column: positive.nullable(), endLine: positive.nullable() }),
774
+ span: z2.strictObject({ frame: z2.enum(["file-utf16", "body-utf16"]), start: integer, end: positive }).refine((v) => v.end > v.start).optional()
775
+ });
776
+ var briefOccurrenceSchema = z2.strictObject({ occurrenceKey: digest, sourceOccurrenceId: bytes(256).regex(/^ref-(0|[1-9]\d{0,2})$/).refine((v) => Number(v.slice(4)) < 512), target: identity, locator: briefLocatorSchema, provenance: briefProvenanceSchema, authoredUrl: briefAuthoredUrlSchema });
777
+ var briefTargetDescriptorSchema = z2.strictObject({ target: identity, presentation: briefTargetPresentationSchema, codec });
778
+ var briefEvidenceSchema = z2.strictObject({
779
+ kind: z2.literal("thread-brief"),
780
+ sourceFile: briefFileSchema,
781
+ sourceState: z2.enum(["present", "absent", "empty"]),
782
+ sourceContentRevision: digest.nullable(),
783
+ completeness: z2.strictObject({ state: z2.literal("complete"), codecVersion: z2.literal(1) }),
784
+ metadataPolicyVersion: z2.literal(1),
785
+ frame: briefFrameSchema.nullable(),
786
+ sourcePresentation: briefSourcePresentationSchema,
787
+ targetDescriptors: z2.array(briefTargetDescriptorSchema).max(256),
788
+ occurrences: z2.array(briefOccurrenceSchema).max(512)
789
+ });
790
+ function briefWithheldDigest(role, original) {
791
+ if (!roles.includes(role))
792
+ throw new Error("Invalid withheld role.");
793
+ return sha256Hex(canonicalJson2(["brief-withheld", 1, role, original]));
794
+ }
795
+ function briefOccurrenceKey(rawRevision, target, locator, sourceOccurrenceId) {
796
+ return sha256Hex(canonicalJson2(["brief-occurrence", 1, rawRevision, identityValue(target), locator, sourceOccurrenceId]));
797
+ }
798
+ function identityValue(v) {
799
+ const c = canonicalizeIdentity(v);
800
+ return { provider: c.provider, keys: c.keys };
801
+ }
802
+ function briefEvidenceDigest(input) {
803
+ const e = briefEvidenceSchema.parse(input);
804
+ return sha256Hex(canonicalJson2(["brief-evidence", 1, {
805
+ ...e,
806
+ targetDescriptors: e.targetDescriptors.map((d) => ({ ...d, target: identityValue(d.target) })).sort((a, b) => canonicalJson2(a.target) < canonicalJson2(b.target) ? -1 : canonicalJson2(a.target) > canonicalJson2(b.target) ? 1 : 0),
807
+ occurrences: e.occurrences.map((o) => ({ ...o, target: identityValue(o.target) })).sort((a, b) => a.occurrenceKey < b.occurrenceKey ? -1 : a.occurrenceKey > b.occurrenceKey ? 1 : 0)
808
+ }]));
809
+ }
810
+ function briefPresentation(p) {
811
+ return { label: p.label.state === "safe" ? p.label.text : p.label.display, ...p.detail?.state === "safe" ? { detail: p.detail.text } : {}, ...p.url.state === "exact" ? { url: p.url.href } : {} };
812
+ }
813
+ function briefApplyLimitCodes(input) {
814
+ const codes = new Set;
815
+ const { evidence: e, projection: p } = input;
816
+ if (utf8ByteLength(JSON.stringify(input)) > BRIEF_LIMITS.inputBytes)
817
+ codes.add("envelope-bytes");
818
+ if (p.targets.length > 256)
819
+ codes.add("target-count");
820
+ if (e.occurrences.length > 512)
821
+ codes.add("occurrence-count");
822
+ const per = new Map;
823
+ for (const o of e.occurrences) {
824
+ const k = canonicalJson2(o.target);
825
+ per.set(k, (per.get(k) ?? 0) + 1);
826
+ if (o.locator.section.heading?.state === "named" && utf8ByteLength(o.locator.section.heading.text) > 256)
827
+ codes.add("heading-bytes");
828
+ }
829
+ if ([...per.values()].some((n) => n > 100))
830
+ codes.add("per-target-occurrences");
831
+ for (const witness of [e.sourcePresentation, ...e.targetDescriptors.map((d) => d.presentation)]) {
832
+ const v = briefPresentation(witness);
833
+ if (witness.label.state === "safe" && utf8ByteLength(witness.label.text) > 256)
834
+ codes.add("presentation-label-bytes");
835
+ if (witness.detail?.state === "safe" && utf8ByteLength(witness.detail.text) > 1024)
836
+ codes.add("presentation-detail-bytes");
837
+ if (witness.url.state === "exact" && utf8ByteLength(witness.url.href) > 2048)
838
+ codes.add("presentation-url-bytes");
839
+ if (utf8ByteLength(JSON.stringify(v)) > 4096)
840
+ codes.add("presentation-bytes");
841
+ }
842
+ for (const r of [p.source, ...p.targets]) {
843
+ const v = r.presentation;
844
+ if (typeof v.label === "string" && utf8ByteLength(v.label) > 256)
845
+ codes.add("presentation-label-bytes");
846
+ if (typeof v.detail === "string" && utf8ByteLength(v.detail) > 1024)
847
+ codes.add("presentation-detail-bytes");
848
+ if (typeof v.url === "string" && utf8ByteLength(v.url) > 2048)
849
+ codes.add("presentation-url-bytes");
850
+ if (utf8ByteLength(JSON.stringify(v)) > 4096)
851
+ codes.add("presentation-bytes");
852
+ }
853
+ if (utf8ByteLength(JSON.stringify({ protocolVersion: 1, producerPluginId: p.producerPluginId, source: p.source, tombstone: p.tombstone, targets: p.targets })) > 262144)
854
+ codes.add("projection-bytes");
855
+ return [...codes].sort();
856
+ }
857
+
858
+ class BriefAdmissionError extends Error {
859
+ code;
860
+ limits;
861
+ constructor(code, limits = []) {
862
+ super(code === "over-limit" ? "Brief references exceed admitted limits." : code === "identity-unrepresentable" ? "Brief identity cannot be represented safely." : "Invalid brief evidence.");
863
+ this.code = code;
864
+ this.limits = limits;
865
+ this.name = "BriefAdmissionError";
866
+ }
867
+ }
868
+ function assertBriefDisplaySafe(e) {
869
+ const fields = [];
870
+ let index = 0;
871
+ const strings = (v, role) => {
872
+ if (typeof v === "string")
873
+ fields.push({ key: [index++], role, value: v });
874
+ else if (Array.isArray(v))
875
+ for (const x of v)
876
+ strings(x, role);
877
+ else if (v && typeof v === "object")
878
+ for (const x of Object.values(v))
879
+ strings(x, role);
880
+ };
881
+ strings(verifiedFileIdentity(e.sourceFile), "required-identity");
882
+ for (const d of e.targetDescriptors)
883
+ strings(identityValue(d.target), "required-identity");
884
+ const p = (v, source) => {
885
+ if (v.label.state === "safe")
886
+ strings(v.label.text, source ? "source-label" : "target-label");
887
+ if (v.detail?.state === "safe")
888
+ strings(v.detail.text, "detail");
889
+ if (v.url.state === "exact")
890
+ strings(v.url.href, "presentation-href");
891
+ };
892
+ p(e.sourcePresentation, true);
893
+ for (const d of e.targetDescriptors) {
894
+ p(d.presentation, false);
895
+ if (d.codec.state === "available")
896
+ strings(d.codec.value, "codec");
897
+ }
898
+ for (const o of e.occurrences) {
899
+ if (o.locator.section.heading?.state === "named")
900
+ strings(o.locator.section.heading.text, "heading");
901
+ if (o.provenance.state === "safe")
902
+ strings(o.provenance.value, "provenance");
903
+ if (o.authoredUrl.state === "exact")
904
+ strings(o.authoredUrl.href, "authored-url");
905
+ }
906
+ const result = classifyBriefDisplayFieldsV1(fields);
907
+ if (result.state !== "classified")
908
+ throw new BriefAdmissionError("identity-unrepresentable");
909
+ for (let i = 0;i < result.results.length; i++)
910
+ if (result.results[i].result.state !== "safe")
911
+ throw new BriefAdmissionError(fields[i].role === "required-identity" ? "identity-unrepresentable" : "invalid");
912
+ }
913
+ function validateBriefCommand(projection, evidence, evidenceDigest) {
914
+ const e = briefEvidenceSchema.parse(evidence);
915
+ if (projection.producerPluginId !== "thread-brief" || canonicalJson2(identityValue({ provider: projection.source.provider, keys: projection.source.keys })) !== canonicalJson2(verifiedFileIdentity(e.sourceFile)))
916
+ throw new BriefAdmissionError("invalid");
917
+ if (canonicalJson2(projection.source.presentation) !== canonicalJson2(briefPresentation(e.sourcePresentation)))
918
+ throw new BriefAdmissionError("invalid");
919
+ const targets = new Map(projection.targets.map((t) => {
920
+ const c = canonicalizeResource(t);
921
+ return [c.identityDigest, c];
922
+ }));
923
+ if (targets.size !== projection.targets.length || targets.size !== e.targetDescriptors.length)
924
+ throw new BriefAdmissionError("invalid");
925
+ const descriptors = new Set;
926
+ for (const d of e.targetDescriptors) {
927
+ const key = canonicalizeIdentity(d.target).identityDigest, t = targets.get(key);
928
+ if (!t || descriptors.has(key) || canonicalJson2(t.presentation) !== canonicalJson2(briefPresentation(d.presentation)))
929
+ throw new BriefAdmissionError("invalid");
930
+ descriptors.add(key);
931
+ if (d.codec.state === "available") {
932
+ const p = d.codec.value;
933
+ const decoded = p.kind === "file" ? verifiedFileIdentity(p.verified) : p.kind === "url" ? { provider: "url", keys: { href: new URL(p.href).href } } : recognitionIdentity(p.source, p.kind === "thread" ? p.verified : undefined);
934
+ if (canonicalJson2(identityValue(decoded)) !== canonicalJson2(identityValue(d.target)))
935
+ throw new BriefAdmissionError("invalid");
936
+ }
937
+ }
938
+ const limits = [], keys = new Set, ids = new Set, counts = new Map;
939
+ if (e.sourceState === "absent") {
940
+ if (e.sourceContentRevision !== null || e.frame !== null || e.occurrences.length || targets.size || !projection.tombstone)
941
+ throw new BriefAdmissionError("invalid");
942
+ } else {
943
+ if (e.sourceContentRevision === null || e.frame === null || e.sourceState === "empty" && (e.occurrences.length > 0 || targets.size > 0 || !projection.tombstone) || e.sourceState === "present" && projection.tombstone)
944
+ throw new BriefAdmissionError("invalid");
945
+ }
946
+ if (e.sourceState === "empty") {
947
+ const f = e.frame;
948
+ if (f.fileUtf16Length !== 0 || f.bodyBase.startUtf16 !== 0 || f.bodyBase.utf16Length !== 0 || f.bodyBase.startLine !== 1 || f.lineMapping.fileLineCount !== 1 || f.rawBytes !== f.bomBytes || e.sourceContentRevision !== sha256Hex(f.bomBytes === 3 ? "\uFEFF" : ""))
949
+ throw new BriefAdmissionError("invalid");
950
+ }
951
+ for (const o of e.occurrences) {
952
+ const key = canonicalizeIdentity(o.target).identityDigest;
953
+ counts.set(key, (counts.get(key) ?? 0) + 1);
954
+ if (!targets.has(key) || keys.has(o.occurrenceKey) || ids.has(o.sourceOccurrenceId) || o.locator.threadId !== e.sourceFile.threadId || canonicalJson2(o.locator.file) !== canonicalJson2(e.sourceFile) || o.locator.sourceContentRevision !== e.sourceContentRevision || o.occurrenceKey !== briefOccurrenceKey(e.sourceContentRevision, o.target, o.locator, o.sourceOccurrenceId))
955
+ throw new BriefAdmissionError("invalid");
956
+ const f = e.frame;
957
+ if (o.locator.section.line > f.lineMapping.fileLineCount || o.locator.location.line > f.lineMapping.fileLineCount || o.locator.location.endLine !== null && (o.locator.location.endLine < o.locator.location.line || o.locator.location.endLine > f.lineMapping.fileLineCount) || o.locator.span && o.locator.span.end > (o.locator.span.frame === "file-utf16" ? f.fileUtf16Length : f.bodyBase.utf16Length))
958
+ throw new BriefAdmissionError("invalid");
959
+ keys.add(o.occurrenceKey);
960
+ ids.add(o.sourceOccurrenceId);
961
+ }
962
+ if (counts.size !== targets.size)
963
+ throw new BriefAdmissionError("invalid");
964
+ if ([...counts.values()].some((n) => n > 100))
965
+ limits.push("per-target-occurrences");
966
+ if (limits.length)
967
+ throw new BriefAdmissionError("over-limit", limits);
968
+ assertBriefDisplaySafe(e);
969
+ if (briefEvidenceDigest(e) !== evidenceDigest)
970
+ throw new BriefAdmissionError("invalid");
971
+ return e;
972
+ }
973
+ var limitCodes = z2.array(z2.enum(BRIEF_LIMIT_CODES)).max(10).refine((v) => new Set(v).size === v.length && v.every((x, i) => i === 0 || v[i - 1] < x));
974
+ var identityCodes = z2.array(z2.enum(["unsafe-required-identity", "unsupported-required-codec", "required-identity-bound"])).min(1).max(3).refine((v) => new Set(v).size === v.length && v.every((x, i) => i === 0 || v[i - 1] < x));
975
+ var blockedBriefStatusSchema = z2.discriminatedUnion("state", [
976
+ z2.strictObject({ state: z2.literal("over-limit"), sourceContentRevision: digest, limits: limitCodes.refine((v) => v.length > 0) }),
977
+ z2.strictObject({ state: z2.literal("identity-unrepresentable"), sourceContentRevision: digest, identityReasons: identityCodes, limits: limitCodes })
978
+ ]);
979
+ function briefStatusDigest(producerPluginId, source, sourceFile, status) {
980
+ const s = blockedBriefStatusSchema.parse(status);
981
+ return sha256Hex(canonicalJson2(["brief-status", 1, producerPluginId, identityValue(source), briefFileSchema.parse(sourceFile), { ...s, limits: [...s.limits].sort(), ..."identityReasons" in s ? { identityReasons: [...s.identityReasons].sort() } : {} }]));
982
+ }
983
+ var producerGetStateInputSchema = z2.strictObject({ version: z2.literal(1), producerPluginId: z2.literal("thread-brief"), source: identity });
984
+ var producerReportStatusInputSchema = producerGetStateInputSchema.extend({ sourceFile: briefFileSchema, attemptRevision: positive, expectedRevision: integer, statusDigest: digest, status: blockedBriefStatusSchema }).superRefine((v, c) => {
985
+ if (canonicalJson2(identityValue(v.source)) !== canonicalJson2(verifiedFileIdentity(v.sourceFile)) || briefStatusDigest(v.producerPluginId, v.source, v.sourceFile, v.status) !== v.statusDigest)
986
+ c.addIssue({ code: "custom", message: "Invalid brief status binding." });
987
+ });
988
+ var presentationOut = z2.object({ label: labelText, detail: bytes(1024).refine((v) => !control(v) && v.trim().length > 0).optional(), url: bytes(2048).optional() }).passthrough();
989
+ var resourceOut = z2.object({ provider: z2.string(), keys: z2.record(z2.string(), z2.string()), presentation: presentationOut }).passthrough();
990
+ var projectionOut = z2.object({ producerPluginId: plugin, source: resourceOut, revision: integer, mutationId: z2.string(), payloadDigest: digest, tombstone: z2.boolean(), targets: z2.array(resourceOut).max(256) }).passthrough();
991
+ var statusOut = z2.union([
992
+ blockedBriefStatusSchema.options[0].extend({ attemptRevision: positive, statusDigest: digest, sourceFile: briefFileSchema.passthrough(), applicability: z2.enum(["current", "superseded-by-graph"]) }).passthrough(),
993
+ blockedBriefStatusSchema.options[1].extend({ attemptRevision: positive, statusDigest: digest, sourceFile: briefFileSchema.passthrough(), applicability: z2.enum(["current", "superseded-by-graph"]) }).passthrough()
994
+ ]);
995
+ var producerStateSchema = z2.object({ version: z2.literal(1), projection: projectionOut.nullable(), evidence: z2.object({ kind: z2.literal("thread-brief"), graphRevision: positive, graphPayloadDigest: digest, evidenceDigest: digest, sourceContentRevision: digest.nullable(), state: z2.enum(["bound", "unconfirmed"]), sourceState: z2.enum(["present", "absent", "empty"]), occurrenceCount: integer.max(512) }).passthrough().nullable(), status: statusOut.nullable(), revisionHighWater: integer }).passthrough();
996
+ var producerDescribeInputSchema = z2.null();
997
+ var producerDescribeOutputSchema = z2.object({ protocol: z2.literal("cross-references-producer"), versions: z2.array(positive).max(16), sourceKinds: z2.array(z2.literal("thread-brief")).max(1), limits: z2.object({ inputBytes: positive, statusBytes: positive, locations: positive, perTarget: positive, headingBytes: positive, limitCodes: z2.array(z2.string()).max(32) }).passthrough() }).passthrough();
998
+ var producerDescribe = () => ({ protocol: "cross-references-producer", versions: [1], sourceKinds: ["thread-brief"], limits: { inputBytes: BRIEF_LIMITS.inputBytes, statusBytes: BRIEF_LIMITS.statusBytes, locations: 512, perTarget: 100, headingBytes: 256, limitCodes: [...BRIEF_LIMIT_CODES] } });
999
+ function projectionValue(value) {
1000
+ const resource = (r) => ({ provider: r.provider, keys: r.keys, presentation: { label: r.presentation.label, ...r.presentation.detail === undefined ? {} : { detail: r.presentation.detail }, ...r.presentation.url === undefined ? {} : { url: r.presentation.url } } });
1001
+ return { protocolVersion: value.protocolVersion, producerPluginId: value.producerPluginId, mutationId: value.mutationId, source: resource(value.source), revision: value.revision, expectedRevision: value.expectedRevision, payloadDigest: value.payloadDigest, tombstone: value.tombstone, targets: value.targets.map(resource) };
1002
+ }
1003
+ function createProducerSchemas(projection) {
1004
+ const admittedProjection = projection.transform(projectionValue);
1005
+ return {
1006
+ [PRODUCER_METHODS.describe]: { input: producerDescribeInputSchema, output: producerDescribeOutputSchema },
1007
+ [PRODUCER_METHODS.getState]: { input: producerGetStateInputSchema, output: producerStateSchema },
1008
+ [PRODUCER_METHODS.apply]: { input: z2.strictObject({ version: z2.literal(1), projection: admittedProjection, evidence: briefEvidenceSchema, evidenceDigest: digest }), output: z2.object({ version: z2.literal(1), outcome: z2.enum(["applied", "duplicate", "equal", "stale", "conflict", "cas-mismatch"]), currentRevision: integer, currentDigest: digest.nullable(), evidenceDisposition: z2.enum(["installed", "replayed", "conflict", "not-applied"]), state: producerStateSchema }).passthrough() },
1009
+ [PRODUCER_METHODS.reportStatus]: { input: producerReportStatusInputSchema, output: z2.object({ version: z2.literal(1), outcome: z2.enum(["recorded", "duplicate", "stale", "conflict", "cas-mismatch"]), state: producerStateSchema }).passthrough() }
1010
+ };
1011
+ }
1012
+ var BRIEF_READER_ROUTE = Object.freeze({ kind: "thread-brief-reader", version: 1, owner: "thread-brief", path: "reveal" });
1013
+ var briefReaderDestinationSchema = z2.object({ kind: z2.literal(BRIEF_READER_ROUTE.kind), version: z2.literal(1), owner: z2.literal(BRIEF_READER_ROUTE.owner), path: z2.literal(BRIEF_READER_ROUTE.path), threadId: z2.string().regex(/^thr_[23456789abcdefghijkmnpqrstuvwxyz]{10}$/u), token: z2.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/u) }).passthrough();
1014
+ function encodeBriefReaderPath(raw) {
1015
+ const d = briefReaderDestinationSchema.parse(raw);
1016
+ return `/plugins/${BRIEF_READER_ROUTE.owner}/${BRIEF_READER_ROUTE.path}/v1/${d.threadId}/${d.token}`;
1017
+ }
1018
+ function decodeBriefReaderPath(path) {
1019
+ if (path.length > 256)
1020
+ return null;
1021
+ const match = /^\/plugins\/thread-brief\/reveal\/v1\/(thr_[23456789abcdefghijkmnpqrstuvwxyz]{10})\/([a-f0-9-]{36})$/u.exec(path);
1022
+ if (!match)
1023
+ return null;
1024
+ const parsed = briefReaderDestinationSchema.safeParse({ ...BRIEF_READER_ROUTE, threadId: match[1], token: match[2] });
1025
+ return parsed.success ? parsed.data : null;
1026
+ }
1027
+ var briefNavigationInputSchema = z2.strictObject({ version: z2.literal(1), sourceFile: briefFileSchema, sourceContentRevision: digest, frame: briefFrameSchema, section: z2.strictObject({ heading: briefHeadingSchema, originalLine: positive }) });
1028
+ var briefNavigationOutputSchema = z2.discriminatedUnion("state", [
1029
+ z2.object({ version: z2.literal(1), state: z2.literal("ready"), sourceFile: briefFileSchema.passthrough(), sourceContentRevision: digest, location: z2.object({ kind: z2.literal("line"), line: positive, column: z2.null() }).passthrough(), proof: z2.object({ kind: z2.literal("accepted-revision-revalidated"), acceptedRevision: digest, selection: z2.literal("same-revision"), frame: briefFrameSchema.safeExtend({ bodyBase: briefFrameSchema.shape.bodyBase.passthrough(), lineMapping: briefFrameSchema.shape.lineMapping.passthrough() }).passthrough() }).passthrough(), reader: briefReaderDestinationSchema.optional() }).passthrough(),
1030
+ z2.object({ version: z2.literal(1), state: z2.literal("fallback"), sourceFile: briefFileSchema.passthrough(), location: z2.null(), reason: z2.enum(["stale", "no-accepted-document", "ambiguous", "heading-unavailable", "source-unavailable", "over-limit"]), reader: briefReaderDestinationSchema.optional() }).passthrough()
1031
+ ]);
1032
+ var briefNavigationDescribeOutputSchema = z2.object({ protocol: z2.literal("thread-brief-navigation"), versions: z2.array(positive).max(16), renderedReaderVersions: z2.array(positive).max(16).optional() }).passthrough();
1033
+ var briefNavigationRpcSchemas = { [BRIEF_NAVIGATION_METHODS.describe]: { input: z2.null(), output: briefNavigationDescribeOutputSchema }, [BRIEF_NAVIGATION_METHODS.resolve]: { input: briefNavigationInputSchema, output: briefNavigationOutputSchema } };
1034
+ var outWithheld = (display) => withheld(display).passthrough();
1035
+ var briefHeadingOutputSchema = z2.union([z2.null(), z2.object({ state: z2.literal("named"), text: bytes(256) }).passthrough(), outWithheld("Heading withheld")]);
1036
+ var briefFileOutputSchema = briefFileSchema.passthrough();
1037
+ var briefFrameOutputSchema = briefFrameSchema.safeExtend({ bodyBase: briefFrameSchema.shape.bodyBase.passthrough(), lineMapping: briefFrameSchema.shape.lineMapping.passthrough() }).passthrough();
1038
+ var briefLocatorOutputSchema = briefLocatorSchema.extend({ file: briefFileOutputSchema, section: z2.object({ heading: briefHeadingOutputSchema, line: positive }).passthrough(), location: briefLocatorSchema.shape.location.passthrough(), span: briefLocatorSchema.shape.span.unwrap().passthrough().optional() }).passthrough();
1039
+ var verifiedFileOutput = z2.union([VerifiedFileTargetSchema.options[0].passthrough(), VerifiedFileTargetSchema.options[1].passthrough()]);
1040
+ var provenanceValueOutput = provenanceValue.extend({ source: SourceIdentitySchema2.passthrough(), verifiedFile: verifiedFileOutput.optional(), recognition: provenanceValue.shape.recognition.extend({ evidence: provenanceValue.shape.recognition.shape.evidence.unwrap().extend({ span: span.passthrough().optional() }).passthrough().optional() }).passthrough() }).passthrough();
1041
+ var briefProvenanceOutputSchema = z2.union([z2.object({ state: z2.literal("safe"), value: provenanceValueOutput }).passthrough(), outWithheld("Recognition details withheld").extend({ summary: provenanceSummary.passthrough() })]);
1042
+ var briefAuthoredUrlOutputSchema = z2.union([z2.object({ state: z2.literal("exact"), href: safeHref }).passthrough(), z2.object({ state: z2.literal("not-url") }).passthrough(), z2.object({ state: z2.literal("unknown") }).passthrough(), outWithheld("Destination withheld")]);
1043
+ function validateBriefNavigationResultV1(input, raw) {
1044
+ const value = briefNavigationOutputSchema.parse(raw), file = value.sourceFile;
1045
+ if (file.kind !== input.sourceFile.kind || file.threadId !== input.sourceFile.threadId || file.path !== input.sourceFile.path)
1046
+ throw new Error("Brief navigation target mismatch.");
1047
+ if (value.reader && value.reader.threadId !== input.sourceFile.threadId)
1048
+ throw new Error("Brief reader target mismatch.");
1049
+ if (value.state === "ready" && (value.sourceContentRevision !== input.sourceContentRevision || value.proof.acceptedRevision !== input.sourceContentRevision || canonicalJson2(knownFrame(value.proof.frame)) !== canonicalJson2(knownFrame(input.frame)) || value.location.line !== input.section.originalLine || value.location.line > input.frame.lineMapping.fileLineCount))
1050
+ throw new Error("Brief navigation proof mismatch.");
1051
+ return value;
1052
+ }
1053
+ function knownFrame(f) {
1054
+ return { codec: f.codec, rawBytes: f.rawBytes, bomBytes: f.bomBytes, fileUtf16Length: f.fileUtf16Length, bodyBase: { startUtf16: f.bodyBase.startUtf16, startLine: f.bodyBase.startLine, utf16Length: f.bodyBase.utf16Length }, lineMapping: { codec: f.lineMapping.codec, fileLineCount: f.lineMapping.fileLineCount } };
1055
+ }
1056
+
1057
+ // src/evidence-v2.ts
1058
+ import { z as z3 } from "zod";
1059
+ import { ContextBundleV1Schema, SafeHrefSchema as SafeHrefSchema3, CandidateV1Schema, SourceIdentitySchema as SourceIdentitySchema3 } from "@phosphorco/bb-context-recognition";
421
1060
  var MENTION_V2_LIMITS = Object.freeze({
422
1061
  responseBytes: 1048576,
423
1062
  inputBytes: 65536,
@@ -432,13 +1071,13 @@ var MENTION_V2_LIMITS = Object.freeze({
432
1071
  lookupCalls: 8
433
1072
  });
434
1073
  var MENTION_V2_METHODS = Object.freeze({ list: "crossReferencesV2ListMentions", resolve: "crossReferencesV2ResolveLookup" });
435
- var integer = () => z2.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
436
- var time = () => integer().max(8640000000000000);
437
- var digest = z2.string().regex(/^[a-f0-9]{64}$/);
438
- var text = (n) => z2.string().max(n).refine((v) => utf8ByteLength(v) <= n, "UTF8 byte bound exceeded.");
439
- var id = z2.string().min(1).max(256).refine((v) => !/[\p{Cc}]/u.test(v));
440
- var producer = z2.string().regex(/^[a-z][a-z0-9._-]{0,63}$/);
441
- var keys = z2.record(z2.string(), z2.string()).refine((v) => Object.keys(v).length <= 16);
1074
+ var integer2 = () => z3.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
1075
+ var time = () => integer2().max(8640000000000000);
1076
+ var digest2 = z3.string().regex(/^[a-f0-9]{64}$/);
1077
+ var text = (n) => z3.string().max(n).refine((v) => utf8ByteLength(v) <= n, "UTF8 byte bound exceeded.");
1078
+ var id = z3.string().min(1).max(256).refine((v) => !/[\p{Cc}]/u.test(v));
1079
+ var producer = z3.string().regex(/^[a-z][a-z0-9._-]{0,63}$/);
1080
+ var keys = z3.record(z3.string(), z3.string()).refine((v) => Object.keys(v).length <= 16);
442
1081
  function isUtf16CodePointBoundary(text2, offset) {
443
1082
  if (!Number.isSafeInteger(offset) || offset < 0 || offset > text2.length)
444
1083
  return false;
@@ -453,110 +1092,125 @@ function wellFormedUtf16(text2) {
453
1092
  }
454
1093
  return true;
455
1094
  }
456
- var identityShape = { provider: z2.string().min(1).max(64), keys };
457
- var identityInputV2Schema = z2.strictObject(identityShape).superRefine((v, c) => {
1095
+ var identityShape = { provider: z3.string().min(1).max(64), keys };
1096
+ var identityInputV2Schema = z3.strictObject(identityShape).superRefine((v, c) => {
458
1097
  try {
459
1098
  canonicalizeIdentity(v);
460
1099
  } catch {
461
1100
  c.addIssue({ code: "custom", message: "Invalid resource identity." });
462
1101
  }
463
1102
  });
464
- var presentation = z2.object({ label: text(256).min(1), url: text(2048).optional(), detail: text(1024).optional() }).passthrough();
465
- var resourceOutputV2Schema = z2.object({ ...identityShape, presentation }).passthrough().superRefine((v, c) => {
1103
+ var presentation2 = z3.object({ label: text(256).min(1), url: text(2048).optional(), detail: text(1024).optional() }).passthrough();
1104
+ var resourceOutputV2Schema = z3.object({ ...identityShape, presentation: presentation2 }).passthrough().superRefine((v, c) => {
466
1105
  try {
467
1106
  canonicalizeResource({ provider: v.provider, keys: v.keys, presentation: { label: v.presentation.label, ...v.presentation.url === undefined ? {} : { url: v.presentation.url }, ...v.presentation.detail === undefined ? {} : { detail: v.presentation.detail } } });
468
1107
  } catch {
469
1108
  c.addIssue({ code: "custom", message: "Invalid resource." });
470
1109
  }
471
1110
  });
472
- var safeAuthoredHrefSchema = SafeHrefSchema2.refine((v) => utf8ByteLength(v) <= 16384 && !hasSensitiveUrlParameter(new URL(v, "https://local.invalid")), "Unsafe destination.");
473
- var mentionQueryV2Schema = z2.discriminatedUnion("kind", [
474
- z2.strictObject({ kind: z2.literal("resource"), target: identityInputV2Schema, relation: z2.enum(["self", "github-pr-family"]) }).refine((v) => v.relation === "self" || v.target.provider === "recognition" && v.target.keys.provider === "github" && /^[a-f0-9]{64}$/.test(v.target.keys.identity ?? ""), "Expected a GitHub root identity."),
475
- z2.strictObject({ kind: z2.literal("authored-url"), href: safeAuthoredHrefSchema })
1111
+ var safeAuthoredHrefSchema = SafeHrefSchema3.refine((v) => utf8ByteLength(v) <= 16384 && !hasSensitiveUrlParameter(new URL(v, "https://local.invalid")), "Unsafe destination.");
1112
+ var mentionQueryV2Schema = z3.discriminatedUnion("kind", [
1113
+ z3.strictObject({ kind: z3.literal("resource"), target: identityInputV2Schema, relation: z3.enum(["self", "github-pr-family"]) }).refine((v) => v.relation === "self" || v.target.provider === "recognition" && v.target.keys.provider === "github" && /^[a-f0-9]{64}$/.test(v.target.keys.identity ?? ""), "Expected a GitHub root identity."),
1114
+ z3.strictObject({ kind: z3.literal("authored-url"), href: safeAuthoredHrefSchema })
476
1115
  ]);
477
- var listMentionsInputV2Schema = z2.strictObject({
478
- version: z2.literal(2),
1116
+ var listMentionsInputV2Schema = z3.strictObject({
1117
+ version: z3.literal(2),
479
1118
  query: mentionQueryV2Schema,
480
1119
  source: identityInputV2Schema.optional(),
481
1120
  producerPluginId: producer.optional(),
482
- pageSize: z2.number().int().min(1).max(100).optional(),
1121
+ pageSize: z3.number().int().min(1).max(100).optional(),
483
1122
  cursor: text(4096).optional(),
484
- ifSnapshot: digest.optional()
1123
+ ifSnapshot: digest2.optional()
485
1124
  }).refine((v) => !(v.cursor !== undefined && v.ifSnapshot !== undefined), "Cursor and conditional are exclusive.");
486
- var spanShape = { start: integer(), end: integer() };
487
- var spanOutputV2Schema = z2.object(spanShape).passthrough().refine((v) => v.end > v.start);
1125
+ var spanShape = { start: integer2(), end: integer2() };
1126
+ var spanOutputV2Schema = z3.object(spanShape).passthrough().refine((v) => v.end > v.start);
488
1127
  var readyShape = {
489
- state: z2.literal("ready"),
490
- text: z2.string().refine(wellFormedUtf16, "Excerpt text must be well-formed UTF16.").refine((v) => [...v].length <= 320 && utf8ByteLength(v) <= 1280),
1128
+ state: z3.literal("ready"),
1129
+ text: z3.string().refine(wellFormedUtf16, "Excerpt text must be well-formed UTF16.").refine((v) => [...v].length <= 320 && utf8ByteLength(v) <= 1280),
491
1130
  sourceSpan: spanOutputV2Schema,
492
1131
  matchSpan: spanOutputV2Schema,
493
- clippedBefore: z2.boolean(),
494
- clippedAfter: z2.boolean(),
495
- matchClippedBefore: z2.boolean(),
496
- matchClippedAfter: z2.boolean(),
497
- codecVersion: z2.literal(1)
1132
+ clippedBefore: z3.boolean(),
1133
+ clippedAfter: z3.boolean(),
1134
+ matchClippedBefore: z3.boolean(),
1135
+ matchClippedAfter: z3.boolean(),
1136
+ codecVersion: z3.literal(1)
498
1137
  };
499
1138
  var readyCoordinates = (v) => v.matchSpan.end <= v.text.length && v.sourceSpan.end - v.sourceSpan.start === v.text.length && isUtf16CodePointBoundary(v.text, v.matchSpan.start) && isUtf16CodePointBoundary(v.text, v.matchSpan.end);
500
- var excerptV2Schema = z2.discriminatedUnion("state", [
501
- z2.object(readyShape).passthrough().refine(readyCoordinates, "Excerpt bounds must be code-point aligned."),
502
- z2.object({ state: z2.literal("unavailable"), reason: z2.enum(["not-materialized", "indivisible-word", "no-eligible-context"]), codecVersion: z2.literal(1) }).passthrough()
1139
+ var excerptV2Schema = z3.discriminatedUnion("state", [
1140
+ z3.object(readyShape).passthrough().refine(readyCoordinates, "Excerpt bounds must be code-point aligned."),
1141
+ z3.object({ state: z3.literal("unavailable"), reason: z3.enum(["not-materialized", "indivisible-word", "no-eligible-context"]), codecVersion: z3.literal(1) }).passthrough()
503
1142
  ]);
504
- var excerptRecordV2Schema = z2.discriminatedUnion("state", [
505
- z2.strictObject({ ...readyShape, sourceSpan: z2.strictObject(spanShape).refine((v) => v.end > v.start), matchSpan: z2.strictObject(spanShape).refine((v) => v.end > v.start) }).refine(readyCoordinates, "Excerpt bounds must be code-point aligned."),
506
- z2.strictObject({ state: z2.literal("unavailable"), reason: z2.enum(["indivisible-word", "no-eligible-context"]), codecVersion: z2.literal(1) })
1143
+ var excerptRecordV2Schema = z3.discriminatedUnion("state", [
1144
+ z3.strictObject({ ...readyShape, sourceSpan: z3.strictObject(spanShape).refine((v) => v.end > v.start), matchSpan: z3.strictObject(spanShape).refine((v) => v.end > v.start) }).refine(readyCoordinates, "Excerpt bounds must be code-point aligned."),
1145
+ z3.strictObject({ state: z3.literal("unavailable"), reason: z3.enum(["indivisible-word", "no-eligible-context"]), codecVersion: z3.literal(1) })
507
1146
  ]);
508
- var locatorOutputV2Schema = z2.object({ kind: z2.literal("conversation"), threadId: id, messageId: id, messageSeq: integer(), anchorSeq: integer().nullable(), role: z2.enum(["user", "assistant"]) }).passthrough();
509
- var recognitionProvenance = z2.object({
1147
+ var locatorOutputV2Schema = z3.object({ kind: z3.literal("conversation"), threadId: id, messageId: id, messageSeq: integer2(), anchorSeq: integer2().nullable(), role: z3.enum(["user", "assistant"]) }).passthrough();
1148
+ var recognitionProvenance = z3.object({
510
1149
  pluginId: id,
511
- origin: z2.enum(["builtin", "contributed"]),
1150
+ origin: z3.enum(["builtin", "contributed"]),
512
1151
  confidence: CandidateV1Schema.shape.confidence,
513
- recognition: z2.object({
514
- basis: z2.enum(["explicit", "text-url", "existing-link", "git-remote", "context"]),
515
- explanation: z2.string().min(1).max(200),
516
- evidence: z2.object({ span: spanOutputV2Schema.optional(), link: integer().optional(), remote: id.optional() }).passthrough().optional()
1152
+ recognition: z3.object({
1153
+ basis: z3.enum(["explicit", "text-url", "existing-link", "git-remote", "context"]),
1154
+ explanation: z3.string().min(1).max(200),
1155
+ evidence: z3.object({ span: spanOutputV2Schema.optional(), link: integer2().optional(), remote: id.optional() }).passthrough().optional()
517
1156
  }).passthrough(),
518
- source: SourceIdentitySchema2.passthrough(),
1157
+ source: SourceIdentitySchema3.passthrough(),
519
1158
  authoredHref: safeAuthoredHrefSchema.optional(),
520
1159
  verifiedFile: VerifiedFileTargetSchema.optional()
521
1160
  }).passthrough();
522
- var verifiedFileOutput = z2.union([
523
- z2.object({ kind: z2.literal("workspace"), environmentId: id, path: z2.string().min(1).max(4096) }).passthrough(),
524
- z2.object({ kind: z2.literal("thread-storage"), threadId: id, path: z2.string().min(1).max(4096) }).passthrough()
1161
+ var verifiedFileOutput2 = z3.union([
1162
+ z3.object({ kind: z3.literal("workspace"), environmentId: id, path: z3.string().min(1).max(4096) }).passthrough(),
1163
+ z3.object({ kind: z3.literal("thread-storage"), threadId: id, path: z3.string().min(1).max(4096) }).passthrough()
525
1164
  ]);
526
- var provenanceOutput = recognitionProvenance.extend({ verifiedFile: verifiedFileOutput.optional() });
1165
+ var provenanceOutput = recognitionProvenance.extend({ verifiedFile: verifiedFileOutput2.optional() });
527
1166
  var claimShape = {
528
1167
  source: resourceOutputV2Schema,
529
1168
  target: resourceOutputV2Schema,
530
1169
  producerPluginId: producer,
531
- graphRevision: integer(),
532
- cap: z2.object({ state: z2.enum(["uncapped", "capped", "unknown"]), limit: z2.literal(100).nullable(), sourceHistoryUnknown: z2.boolean().nullable() }).passthrough()
1170
+ graphRevision: integer2(),
1171
+ cap: z3.object({ state: z3.enum(["uncapped", "capped", "unknown"]), limit: z3.literal(100).nullable(), sourceHistoryUnknown: z3.boolean().nullable() }).passthrough()
533
1172
  };
534
- var knownItem = z2.discriminatedUnion("kind", [
535
- z2.object({
1173
+ var knownItem = z3.discriminatedUnion("kind", [
1174
+ z3.object({
1175
+ ...claimShape,
1176
+ kind: z3.literal("brief-occurrence"),
1177
+ evidenceRevision: integer2().min(1),
1178
+ occurrenceKey: digest2,
1179
+ sourceOccurrenceId: text(256),
1180
+ locator: briefLocatorOutputSchema,
1181
+ sourceContentRevision: digest2,
1182
+ frame: briefFrameOutputSchema,
1183
+ excerpt: z3.object({ state: z3.literal("unavailable"), reason: z3.literal("not-materialized"), codecVersion: z3.literal(1) }).passthrough(),
1184
+ provenance: briefProvenanceOutputSchema,
1185
+ authoredUrl: briefAuthoredUrlOutputSchema,
1186
+ authoredUrlState: z3.enum(["exact", "not-url", "unknown", "withheld"]),
1187
+ confirmation: z3.enum(["producer-attested", "retained-unconfirmed"])
1188
+ }).passthrough().refine((v) => v.authoredUrlState === v.authoredUrl.state && v.sourceContentRevision === v.locator.sourceContentRevision && v.locator.threadId === v.locator.file.threadId, "Inconsistent Brief item."),
1189
+ z3.object({
536
1190
  ...claimShape,
537
- kind: z2.literal("occurrence"),
538
- evidenceRevision: integer().min(1),
539
- occurrenceKey: digest,
1191
+ kind: z3.literal("occurrence"),
1192
+ evidenceRevision: integer2().min(1),
1193
+ occurrenceKey: digest2,
540
1194
  locator: locatorOutputV2Schema,
541
- sourceContentRevision: digest,
1195
+ sourceContentRevision: digest2,
542
1196
  span: spanOutputV2Schema,
543
1197
  excerpt: excerptV2Schema,
544
1198
  messageCreatedAt: time(),
545
1199
  observedAt: time(),
546
- confirmation: z2.enum(["observed", "retained-unconfirmed"]),
1200
+ confirmation: z3.enum(["observed", "retained-unconfirmed"]),
547
1201
  provenance: provenanceOutput,
548
- authoredUrlState: z2.enum(["exact", "not-url", "unknown"])
1202
+ authoredUrlState: z3.enum(["exact", "not-url", "unknown"])
549
1203
  }).passthrough(),
550
- z2.object({ ...claimShape, kind: z2.literal("claim-without-evidence"), reason: z2.enum(["legacy", "producer-no-evidence", "not-yet-collected"]), matchBasis: z2.enum(["primary-resource", "primary-url-identity"]) }).passthrough(),
551
- z2.object({ ...claimShape, kind: z2.literal("unsupported"), reason: z2.literal("unsupported-format") }).passthrough()
1204
+ z3.object({ ...claimShape, kind: z3.literal("claim-without-evidence"), reason: z3.enum(["legacy", "producer-no-evidence", "not-yet-collected"]), matchBasis: z3.enum(["primary-resource", "primary-url-identity"]) }).passthrough(),
1205
+ z3.object({ ...claimShape, kind: z3.literal("unsupported"), reason: z3.literal("unsupported-format") }).passthrough()
552
1206
  ]);
553
- var mentionItemV2Schema = z2.unknown().transform((raw, ctx) => {
1207
+ var mentionItemV2Schema = z3.unknown().transform((raw, ctx) => {
554
1208
  const r = raw;
555
1209
  const unknown = (value, known) => typeof value === "string" && !known.includes(value);
556
- const future = !!r && typeof r === "object" && (unknown(r.kind, ["occurrence", "claim-without-evidence", "unsupported"]) || r.kind === "occurrence" && (unknown(r.locator?.kind, ["conversation"]) || unknown(r.excerpt?.state, ["ready", "unavailable"]) || typeof r.excerpt?.codecVersion === "number" && r.excerpt.codecVersion !== 1 || unknown(r.confirmation, ["observed", "retained-unconfirmed"]) || unknown(r.authoredUrlState, ["exact", "not-url", "unknown"]) || unknown(r.locator?.role, ["user", "assistant"]) || unknown(r.provenance?.origin, ["builtin", "contributed"]) || unknown(r.provenance?.confidence, ["high", "medium", "low"]) || unknown(r.provenance?.recognition?.basis, ["explicit", "text-url", "existing-link", "git-remote", "context"]) || r.excerpt?.state === "unavailable" && unknown(r.excerpt.reason, ["not-materialized", "indivisible-word", "no-eligible-context"])) || r.kind === "claim-without-evidence" && (unknown(r.reason, ["legacy", "producer-no-evidence", "not-yet-collected"]) || unknown(r.matchBasis, ["primary-resource", "primary-url-identity"])) || unknown(r.cap?.state, ["uncapped", "capped", "unknown"]));
557
- if (future && (!r.cap || !z2.object({ state: z2.string(), limit: z2.literal(100).nullable(), sourceHistoryUnknown: z2.boolean().nullable() }).safeParse(r.cap).success)) {
1210
+ const future = !!r && typeof r === "object" && (unknown(r.kind, ["occurrence", "brief-occurrence", "claim-without-evidence", "unsupported"]) || r.kind === "occurrence" && (unknown(r.locator?.kind, ["conversation"]) || unknown(r.excerpt?.state, ["ready", "unavailable"]) || typeof r.excerpt?.codecVersion === "number" && r.excerpt.codecVersion !== 1 || unknown(r.confirmation, ["observed", "retained-unconfirmed"]) || unknown(r.authoredUrlState, ["exact", "not-url", "unknown"]) || unknown(r.locator?.role, ["user", "assistant"]) || unknown(r.provenance?.origin, ["builtin", "contributed"]) || unknown(r.provenance?.confidence, ["high", "medium", "low"]) || unknown(r.provenance?.recognition?.basis, ["explicit", "text-url", "existing-link", "git-remote", "context"]) || r.excerpt?.state === "unavailable" && unknown(r.excerpt.reason, ["not-materialized", "indivisible-word", "no-eligible-context"])) || r.kind === "brief-occurrence" && (unknown(r.locator?.kind, ["thread-brief"]) || unknown(r.confirmation, ["producer-attested", "retained-unconfirmed"]) || unknown(r.authoredUrlState, ["exact", "not-url", "unknown", "withheld"]) || unknown(r.provenance?.state, ["safe", "withheld"]) || unknown(r.locator?.section?.heading?.state, ["named", "withheld"]) || unknown(r.locator?.section?.heading?.cause, ["policy", "unclassified"]) || unknown(r.provenance?.cause, ["policy", "unclassified"]) || unknown(r.authoredUrl?.state, ["exact", "not-url", "unknown", "withheld"]) || unknown(r.authoredUrl?.cause, ["policy", "unclassified"]) || unknown(r.frame?.codec, ["utf8-fatal-bom-consumed-v1"]) || unknown(r.frame?.lineMapping?.codec, ["native-file-lines-v1"]) || unknown(r.locator?.location?.kind, ["line"]) || unknown(r.locator?.span?.frame, ["file-utf16", "body-utf16"]) || unknown(r.excerpt?.state, ["unavailable"]) || unknown(r.excerpt?.reason, ["not-materialized"]) || typeof r.excerpt?.codecVersion === "number" && r.excerpt.codecVersion !== 1) || r.kind === "claim-without-evidence" && (unknown(r.reason, ["legacy", "producer-no-evidence", "not-yet-collected"]) || unknown(r.matchBasis, ["primary-resource", "primary-url-identity"])) || unknown(r.cap?.state, ["uncapped", "capped", "unknown"]));
1211
+ if (future && (!r.cap || !z3.object({ state: z3.string(), limit: z3.literal(100).nullable(), sourceHistoryUnknown: z3.boolean().nullable() }).safeParse(r.cap).success)) {
558
1212
  ctx.addIssue({ code: "custom", message: "Invalid required claim cap." });
559
- return z2.NEVER;
1213
+ return z3.NEVER;
560
1214
  }
561
1215
  const candidate = future ? {
562
1216
  source: r.source,
@@ -571,51 +1225,51 @@ var mentionItemV2Schema = z2.unknown().transform((raw, ctx) => {
571
1225
  if (parsed.success)
572
1226
  return parsed.data;
573
1227
  ctx.addIssue({ code: "custom", message: "Invalid mention item." });
574
- return z2.NEVER;
1228
+ return z3.NEVER;
575
1229
  });
576
- var mentionCountsV2Schema = z2.object({ retainedOccurrences: integer(), confirmedOccurrences: integer(), unconfirmedOccurrences: integer(), producerClaims: integer(), indexedSources: integer(), claimsWithoutLocations: integer(), excerptUnavailable: integer() }).passthrough().refine((v) => v.confirmedOccurrences + v.unconfirmedOccurrences === v.retainedOccurrences && v.claimsWithoutLocations <= v.producerClaims && v.indexedSources <= v.producerClaims && v.excerptUnavailable <= v.retainedOccurrences);
577
- var coverageV2Schema = z2.object({
578
- scope: z2.literal("known-sources"),
579
- collectionIncomplete: z2.boolean(),
580
- retentionLimited: z2.boolean(),
581
- capHistoryUnknown: z2.boolean(),
582
- legacyClaimsPresent: z2.boolean(),
583
- evidenceStateUnknown: z2.boolean(),
584
- authoredUrlCoverage: z2.object({ state: z2.enum(["complete-for-known-locations", "partial"]), unknownLocations: integer(), scope: z2.literal("known-locations"), watermark: digest }).passthrough(),
585
- reasons: z2.array(text(128)).max(32),
586
- reasonsClipped: z2.boolean(),
1230
+ var mentionCountsV2Schema = z3.object({ retainedOccurrences: integer2(), confirmedOccurrences: integer2(), unconfirmedOccurrences: integer2(), producerClaims: integer2(), indexedSources: integer2(), claimsWithoutLocations: integer2(), excerptUnavailable: integer2() }).passthrough().refine((v) => v.confirmedOccurrences + v.unconfirmedOccurrences === v.retainedOccurrences && v.claimsWithoutLocations <= v.producerClaims && v.indexedSources <= v.producerClaims && v.excerptUnavailable <= v.retainedOccurrences);
1231
+ var coverageV2Schema = z3.object({
1232
+ scope: z3.literal("known-sources"),
1233
+ collectionIncomplete: z3.boolean(),
1234
+ retentionLimited: z3.boolean(),
1235
+ capHistoryUnknown: z3.boolean(),
1236
+ legacyClaimsPresent: z3.boolean(),
1237
+ evidenceStateUnknown: z3.boolean(),
1238
+ authoredUrlCoverage: z3.object({ state: z3.enum(["complete-for-known-locations", "partial"]), unknownLocations: integer2(), scope: z3.literal("known-locations"), watermark: digest2 }).passthrough(),
1239
+ reasons: z3.array(text(128)).max(32),
1240
+ reasonsClipped: z3.boolean(),
587
1241
  checkedAt: time().nullable()
588
1242
  }).passthrough();
589
- var listMentionsOutputV2Schema = z2.discriminatedUnion("status", [
590
- z2.object({ version: z2.literal(2), status: z2.literal("page"), snapshot: digest, items: z2.array(mentionItemV2Schema).max(100), counts: mentionCountsV2Schema, coverage: coverageV2Schema, nextCursor: text(4096).nullable() }).passthrough(),
591
- z2.object({ version: z2.literal(2), status: z2.literal("not-modified"), snapshot: digest, coverage: coverageV2Schema }).passthrough(),
592
- z2.object({ version: z2.literal(2), status: z2.literal("restart"), reason: z2.literal("snapshot-changed"), snapshot: digest }).passthrough(),
593
- z2.object({ version: z2.literal(2), status: z2.literal("unavailable"), reason: z2.enum(["index-warming", "read-budget"]), retryable: z2.boolean() }).passthrough()
1243
+ var listMentionsOutputV2Schema = z3.discriminatedUnion("status", [
1244
+ z3.object({ version: z3.literal(2), status: z3.literal("page"), snapshot: digest2, items: z3.array(mentionItemV2Schema).max(100), counts: mentionCountsV2Schema, coverage: coverageV2Schema, nextCursor: text(4096).nullable() }).passthrough(),
1245
+ z3.object({ version: z3.literal(2), status: z3.literal("not-modified"), snapshot: digest2, coverage: coverageV2Schema }).passthrough(),
1246
+ z3.object({ version: z3.literal(2), status: z3.literal("restart"), reason: z3.literal("snapshot-changed"), snapshot: digest2 }).passthrough(),
1247
+ z3.object({ version: z3.literal(2), status: z3.literal("unavailable"), reason: z3.enum(["index-warming", "read-budget"]), retryable: z3.boolean() }).passthrough()
594
1248
  ]);
595
- var lookupContextV2Schema = ContextBundleV1Schema.omit({ consumer: true, links: true }).extend({ links: z2.array(z2.strictObject({ href: safeAuthoredHrefSchema })).max(16).optional() });
596
- var resolveLookupInputV2Schema = z2.strictObject({ version: z2.literal(2), text: z2.string().min(1).max(4096).refine((v) => utf8ByteLength(v) <= 16384), mode: z2.enum(["recognize", "exact-url"]), context: lookupContextV2Schema.optional() });
597
- var identityOutput = z2.object(identityShape).passthrough().superRefine((v, c) => {
1249
+ var lookupContextV2Schema = ContextBundleV1Schema.omit({ consumer: true, links: true }).extend({ links: z3.array(z3.strictObject({ href: safeAuthoredHrefSchema })).max(16).optional() });
1250
+ var resolveLookupInputV2Schema = z3.strictObject({ version: z3.literal(2), text: z3.string().min(1).max(4096).refine((v) => utf8ByteLength(v) <= 16384), mode: z3.enum(["recognize", "exact-url"]), context: lookupContextV2Schema.optional() });
1251
+ var identityOutput = z3.object(identityShape).passthrough().superRefine((v, c) => {
598
1252
  try {
599
1253
  canonicalizeIdentity({ provider: v.provider, keys: v.keys });
600
1254
  } catch {
601
1255
  c.addIssue({ code: "custom", message: "Invalid lookup identity." });
602
1256
  }
603
1257
  });
604
- var queryOutput = z2.discriminatedUnion("kind", [
605
- z2.object({ kind: z2.literal("resource"), target: identityOutput, relation: z2.enum(["self", "github-pr-family"]) }).passthrough(),
606
- z2.object({ kind: z2.literal("authored-url"), href: safeAuthoredHrefSchema }).passthrough()
1258
+ var queryOutput = z3.discriminatedUnion("kind", [
1259
+ z3.object({ kind: z3.literal("resource"), target: identityOutput, relation: z3.enum(["self", "github-pr-family"]) }).passthrough(),
1260
+ z3.object({ kind: z3.literal("authored-url"), href: safeAuthoredHrefSchema }).passthrough()
607
1261
  ]);
608
- var resolveLookupOutputV2Schema = z2.object({
609
- version: z2.literal(2),
610
- state: z2.enum(["ready", "ambiguous", "unrecognized", "incomplete"]),
611
- options: z2.array(z2.object({ query: queryOutput, label: text(256), inputSpan: spanOutputV2Schema, basis: z2.enum(["supplier", "native", "stored-codec"]), reasons: z2.array(text(128)).max(16) }).passthrough()).max(8),
612
- reasons: z2.array(text(128)).max(16)
1262
+ var resolveLookupOutputV2Schema = z3.object({
1263
+ version: z3.literal(2),
1264
+ state: z3.enum(["ready", "ambiguous", "unrecognized", "incomplete"]),
1265
+ options: z3.array(z3.object({ query: queryOutput, label: text(256), inputSpan: spanOutputV2Schema, basis: z3.enum(["supplier", "native", "stored-codec"]), reasons: z3.array(text(128)).max(16) }).passthrough()).max(8),
1266
+ reasons: z3.array(text(128)).max(16)
613
1267
  }).passthrough();
614
1268
  var crossReferencesV2RpcSchemas = {
615
1269
  crossReferencesV2ListMentions: { input: listMentionsInputV2Schema, output: listMentionsOutputV2Schema },
616
1270
  crossReferencesV2ResolveLookup: { input: resolveLookupInputV2Schema, output: resolveLookupOutputV2Schema }
617
1271
  };
618
- var mentionsChangedV2Schema = z2.object({ version: z2.literal(2), producerPluginId: producer, sourceIdentityDigest: digest, graphRevision: integer(), evidenceRevision: integer().nullable(), affectedIdentityDigests: z2.array(digest).max(512), scopeListClipped: z2.boolean() }).passthrough();
1272
+ var mentionsChangedV2Schema = z3.object({ version: z3.literal(2), producerPluginId: producer, sourceIdentityDigest: digest2, graphRevision: integer2(), evidenceRevision: integer2().nullable(), affectedIdentityDigests: z3.array(digest2).max(512), scopeListClipped: z3.boolean() }).passthrough();
619
1273
  var MENTIONS_V2_CHANNEL = "cross-references-mentions-v2-changed";
620
1274
  // src/lookup.ts
621
1275
  function githubLookup(value) {
@@ -636,7 +1290,6 @@ function githubLookup(value) {
636
1290
  const source = { provider: "github", id: `github.com/${repo}#${n}`, kind };
637
1291
  return { source, query: { kind: "resource", target: recognitionIdentity(source), relation: kind === "pull-request" ? "github-pr-family" : "self" }, label: `${repo}#${n}` };
638
1292
  }
639
-
640
1293
  // src/index.ts
641
1294
  var FORWARD_REFERENCE_CHECK_LIMIT = 10;
642
1295
  function assertInputRecord(value) {
@@ -711,130 +1364,130 @@ var namePattern = /^[a-z][a-z0-9._-]{0,63}$/;
711
1364
  var uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
712
1365
  var digestPattern = /^[0-9a-f]{64}$/;
713
1366
  var safeInteger = (schema) => schema.refine(Number.isSafeInteger, { message: "must be a safe integer" });
714
- var presentationSchema = z3.object({
715
- label: z3.string().max(MAX_PRESENTATION_LABEL_BYTES),
716
- detail: z3.string().max(MAX_PRESENTATION_DETAIL_BYTES).optional(),
717
- url: z3.string().max(MAX_PRESENTATION_URL_BYTES).optional()
1367
+ var presentationSchema = z4.object({
1368
+ label: z4.string().max(MAX_PRESENTATION_LABEL_BYTES),
1369
+ detail: z4.string().max(MAX_PRESENTATION_DETAIL_BYTES).optional(),
1370
+ url: z4.string().max(MAX_PRESENTATION_URL_BYTES).optional()
718
1371
  }).strict().superRefine((value, context) => {
719
1372
  try {
720
1373
  canonicalizeResource({ provider: "test", keys: { resource: "placeholder" }, presentation: value });
721
- } catch (cause) {
722
- context.addIssue({ code: "custom", message: cause instanceof Error ? cause.message : String(cause) });
1374
+ } catch (cause2) {
1375
+ context.addIssue({ code: "custom", message: cause2 instanceof Error ? cause2.message : String(cause2) });
723
1376
  }
724
1377
  });
725
- var resourceSchema = z3.object({
726
- provider: z3.string().max(64).regex(namePattern),
727
- keys: z3.record(z3.string().max(64), z3.string().max(MAX_KEY_VALUE_BYTES)),
1378
+ var resourceSchema = z4.object({
1379
+ provider: z4.string().max(64).regex(namePattern),
1380
+ keys: z4.record(z4.string().max(64), z4.string().max(MAX_KEY_VALUE_BYTES)),
728
1381
  presentation: presentationSchema
729
1382
  }).strict().superRefine((value, context) => {
730
1383
  try {
731
1384
  canonicalizeResource(value);
732
- } catch (cause) {
733
- context.addIssue({ code: "custom", message: cause instanceof Error ? cause.message : String(cause) });
1385
+ } catch (cause2) {
1386
+ context.addIssue({ code: "custom", message: cause2 instanceof Error ? cause2.message : String(cause2) });
734
1387
  }
735
1388
  });
736
- var resourceIdentitySchema = z3.object({
737
- provider: z3.string().max(64).regex(namePattern),
738
- keys: z3.record(z3.string().max(64), z3.string().max(MAX_KEY_VALUE_BYTES))
1389
+ var resourceIdentitySchema = z4.object({
1390
+ provider: z4.string().max(64).regex(namePattern),
1391
+ keys: z4.record(z4.string().max(64), z4.string().max(MAX_KEY_VALUE_BYTES))
739
1392
  }).strict().superRefine((value, context) => {
740
1393
  try {
741
1394
  canonicalizeIdentity(value);
742
- } catch (cause) {
743
- context.addIssue({ code: "custom", message: cause instanceof Error ? cause.message : String(cause) });
1395
+ } catch (cause2) {
1396
+ context.addIssue({ code: "custom", message: cause2 instanceof Error ? cause2.message : String(cause2) });
744
1397
  }
745
1398
  });
746
- var producerPluginIdSchema = z3.string().max(64).regex(namePattern);
747
- var mutationIdSchema = z3.string().max(MAX_MUTATION_ID_BYTES).regex(uuidPattern);
748
- var revisionSchema = safeInteger(z3.number().int());
749
- var applyProjectionInputSchema = z3.object({
750
- protocolVersion: z3.literal(PROTOCOL_VERSION),
1399
+ var producerPluginIdSchema = z4.string().max(64).regex(namePattern);
1400
+ var mutationIdSchema = z4.string().max(MAX_MUTATION_ID_BYTES).regex(uuidPattern);
1401
+ var revisionSchema = safeInteger(z4.number().int());
1402
+ var applyProjectionInputSchema = z4.object({
1403
+ protocolVersion: z4.literal(PROTOCOL_VERSION),
751
1404
  producerPluginId: producerPluginIdSchema,
752
1405
  mutationId: mutationIdSchema,
753
1406
  source: resourceSchema,
754
1407
  revision: revisionSchema.positive(),
755
1408
  expectedRevision: revisionSchema.nonnegative(),
756
- payloadDigest: z3.string().regex(digestPattern),
757
- tombstone: z3.boolean(),
758
- targets: z3.array(resourceSchema).max(MAX_TARGETS)
1409
+ payloadDigest: z4.string().regex(digestPattern),
1410
+ tombstone: z4.boolean(),
1411
+ targets: z4.array(resourceSchema).max(MAX_TARGETS)
759
1412
  }).strict().superRefine((value, context) => {
760
1413
  try {
761
1414
  normalizeProjectionCommand(value);
762
- } catch (cause) {
763
- context.addIssue({ code: "custom", message: cause instanceof Error ? cause.message : String(cause) });
1415
+ } catch (cause2) {
1416
+ context.addIssue({ code: "custom", message: cause2 instanceof Error ? cause2.message : String(cause2) });
764
1417
  }
765
1418
  });
766
- var applyProjectionResponseSchema = z3.object({
767
- outcome: z3.enum(["applied", "duplicate", "equal", "stale", "conflict", "cas-mismatch"]),
1419
+ var applyProjectionResponseSchema = z4.object({
1420
+ outcome: z4.enum(["applied", "duplicate", "equal", "stale", "conflict", "cas-mismatch"]),
768
1421
  currentRevision: revisionSchema.nonnegative(),
769
- currentDigest: z3.string().regex(digestPattern).nullable()
1422
+ currentDigest: z4.string().regex(digestPattern).nullable()
770
1423
  }).strict();
771
- var projectionSchema = z3.object({
1424
+ var projectionSchema = z4.object({
772
1425
  producerPluginId: producerPluginIdSchema,
773
1426
  source: resourceSchema,
774
1427
  revision: revisionSchema.nonnegative(),
775
1428
  mutationId: mutationIdSchema,
776
- payloadDigest: z3.string().regex(digestPattern),
777
- tombstone: z3.boolean(),
778
- targets: z3.array(resourceSchema).max(MAX_TARGETS)
1429
+ payloadDigest: z4.string().regex(digestPattern),
1430
+ tombstone: z4.boolean(),
1431
+ targets: z4.array(resourceSchema).max(MAX_TARGETS)
779
1432
  }).strict();
780
- var getProjectionInputSchema = z3.object({
1433
+ var getProjectionInputSchema = z4.object({
781
1434
  producerPluginId: producerPluginIdSchema,
782
1435
  source: resourceIdentitySchema
783
1436
  }).strict();
784
- var getProjectionOutputSchema = z3.object({ projection: projectionSchema.nullable() }).strict();
785
- var backlinkRowSchema = z3.object({
1437
+ var getProjectionOutputSchema = z4.object({ projection: projectionSchema.nullable() }).strict();
1438
+ var backlinkRowSchema = z4.object({
786
1439
  source: resourceSchema,
787
1440
  producerPluginId: producerPluginIdSchema,
788
1441
  revision: revisionSchema.nonnegative(),
789
1442
  targetPresentation: presentationSchema,
790
- position: z3.number().int().min(0).max(MAX_TARGETS - 1).refine(Number.isSafeInteger),
1443
+ position: z4.number().int().min(0).max(MAX_TARGETS - 1).refine(Number.isSafeInteger),
791
1444
  lastSeenAt: revisionSchema.nonnegative().nullable().optional()
792
1445
  }).strict();
793
- var listBacklinksInputSchema = z3.object({
1446
+ var listBacklinksInputSchema = z4.object({
794
1447
  target: resourceIdentitySchema,
795
- pageSize: z3.number().int().min(1).max(100).refine(Number.isSafeInteger).optional(),
796
- cursor: z3.string().max(4096).optional()
1448
+ pageSize: z4.number().int().min(1).max(100).refine(Number.isSafeInteger).optional(),
1449
+ cursor: z4.string().max(4096).optional()
797
1450
  }).strict();
798
- var listBacklinksOutputSchema = z3.object({
799
- rows: z3.array(backlinkRowSchema).max(100),
1451
+ var listBacklinksOutputSchema = z4.object({
1452
+ rows: z4.array(backlinkRowSchema).max(100),
800
1453
  total: revisionSchema.nonnegative(),
801
- nextCursor: z3.string().max(4096).nullable()
1454
+ nextCursor: z4.string().max(4096).nullable()
802
1455
  }).strict();
803
- var forwardReferenceRowSchema = z3.object({
1456
+ var forwardReferenceRowSchema = z4.object({
804
1457
  target: resourceSchema,
805
1458
  producerPluginId: producerPluginIdSchema,
806
1459
  revision: revisionSchema.nonnegative(),
807
- position: z3.number().int().min(0).max(MAX_TARGETS - 1).refine(Number.isSafeInteger),
1460
+ position: z4.number().int().min(0).max(MAX_TARGETS - 1).refine(Number.isSafeInteger),
808
1461
  lastSeenAt: revisionSchema.nonnegative().nullable().optional()
809
1462
  }).strict();
810
- var listForwardReferencesInputSchema = z3.object({
1463
+ var listForwardReferencesInputSchema = z4.object({
811
1464
  source: resourceIdentitySchema,
812
1465
  producerPluginId: producerPluginIdSchema.optional(),
813
- pageSize: z3.number().int().min(1).max(100).refine(Number.isSafeInteger).optional(),
814
- cursor: z3.string().max(4096).optional()
1466
+ pageSize: z4.number().int().min(1).max(100).refine(Number.isSafeInteger).optional(),
1467
+ cursor: z4.string().max(4096).optional()
815
1468
  }).strict();
816
- var listForwardReferencesOutputSchema = z3.object({
817
- rows: z3.array(forwardReferenceRowSchema).max(100),
1469
+ var listForwardReferencesOutputSchema = z4.object({
1470
+ rows: z4.array(forwardReferenceRowSchema).max(100),
818
1471
  total: revisionSchema.nonnegative(),
819
- nextCursor: z3.string().max(4096).nullable()
1472
+ nextCursor: z4.string().max(4096).nullable()
820
1473
  }).strict();
821
- var checkForwardReferencesInputSchema = z3.object({
1474
+ var checkForwardReferencesInputSchema = z4.object({
822
1475
  source: resourceIdentitySchema,
823
1476
  producerPluginId: producerPluginIdSchema.optional()
824
1477
  }).strict();
825
- var forwardReferenceStatusSchema = z3.object({
826
- url: z3.string().max(MAX_PRESENTATION_URL_BYTES),
827
- status: z3.number().int().min(100).max(599).nullable(),
828
- label: z3.string().min(1).max(128)
1478
+ var forwardReferenceStatusSchema = z4.object({
1479
+ url: z4.string().max(MAX_PRESENTATION_URL_BYTES),
1480
+ status: z4.number().int().min(100).max(599).nullable(),
1481
+ label: z4.string().min(1).max(128)
829
1482
  }).strict();
830
- var checkForwardReferencesOutputSchema = z3.array(forwardReferenceStatusSchema).max(FORWARD_REFERENCE_CHECK_LIMIT);
1483
+ var checkForwardReferencesOutputSchema = z4.array(forwardReferenceStatusSchema).max(FORWARD_REFERENCE_CHECK_LIMIT);
831
1484
  var CROSS_REFERENCES_PLUGIN_ID = "cross-references";
832
1485
  var CROSS_REFERENCES_PROTOCOL = "cross-references";
833
1486
  var LIMITS = Object.freeze({ callMs: 5000, describeMs: 1000, responseBytes: 1024 * 1024 });
834
- var describeInputSchema = z3.null();
835
- var describeOutputSchema = z3.object({
836
- protocol: z3.literal(CROSS_REFERENCES_PROTOCOL),
837
- versions: z3.array(z3.number().int().positive().refine(Number.isSafeInteger)).max(16)
1487
+ var describeInputSchema = z4.null();
1488
+ var describeOutputSchema = z4.object({
1489
+ protocol: z4.literal(CROSS_REFERENCES_PROTOCOL),
1490
+ versions: z4.array(z4.number().int().positive().refine(Number.isSafeInteger)).max(16)
838
1491
  });
839
1492
  var crossReferencesRpcSchemas = {
840
1493
  "crossReferences.describe": { input: describeInputSchema, output: describeOutputSchema },
@@ -844,11 +1497,12 @@ var crossReferencesRpcSchemas = {
844
1497
  listForwardReferences: { input: listForwardReferencesInputSchema, output: listForwardReferencesOutputSchema },
845
1498
  checkForwardReferences: { input: checkForwardReferencesInputSchema, output: checkForwardReferencesOutputSchema }
846
1499
  };
847
- var referenceSnapshotSchema = z3.object({
1500
+ var referenceSnapshotSchema = z4.object({
848
1501
  revision: revisionSchema.nonnegative(),
849
- targets: z3.array(resourceSchema).max(MAX_TARGETS),
850
- status: z3.object({ state: z3.enum(["synced", "pending", "degraded", "blocked"]), error: z3.string().max(4096).nullable() })
1502
+ targets: z4.array(resourceSchema).max(MAX_TARGETS),
1503
+ status: z4.object({ state: z4.enum(["synced", "pending", "degraded", "blocked"]), error: z4.string().max(4096).nullable() })
851
1504
  });
1505
+ var crossReferencesProducerRpcSchemas = createProducerSchemas(applyProjectionInputSchema);
852
1506
 
853
1507
  // src/react.tsx
854
1508
  import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
@@ -970,12 +1624,12 @@ function useThreadSearch(query, retry, api, connection, origin) {
970
1624
  apiRef.current.search(parsed.query).then((response) => {
971
1625
  if (active)
972
1626
  setState({ status: "ready", input, threads: response.threads.slice(0, MAX_SEARCH_RESULTS) });
973
- }, (cause) => {
1627
+ }, (cause2) => {
974
1628
  if (active)
975
1629
  setState({
976
1630
  status: "error",
977
1631
  input,
978
- message: cause instanceof Error ? cause.message : "Could not search BB threads."
1632
+ message: cause2 instanceof Error ? cause2.message : "Could not search BB threads."
979
1633
  });
980
1634
  });
981
1635
  }, 180);
@@ -1012,32 +1666,32 @@ function useAttachments(api, connection, refreshToken) {
1012
1666
  };
1013
1667
  }, []);
1014
1668
  const refresh = useCallback(async () => {
1015
- const control = readControl.current;
1016
- control.pending = true;
1017
- if (!mounted.current || mutationInFlight.current || control.inFlight)
1669
+ const control2 = readControl.current;
1670
+ control2.pending = true;
1671
+ if (!mounted.current || mutationInFlight.current || control2.inFlight)
1018
1672
  return;
1019
- control.inFlight = true;
1673
+ control2.inFlight = true;
1020
1674
  try {
1021
- while (mounted.current && !mutationInFlight.current && readControl.current === control && control.pending) {
1022
- control.pending = false;
1675
+ while (mounted.current && !mutationInFlight.current && readControl.current === control2 && control2.pending) {
1676
+ control2.pending = false;
1023
1677
  try {
1024
1678
  const next = await apiRef.current.get();
1025
- if (mounted.current && readControl.current === control && !mutationInFlight.current) {
1679
+ if (mounted.current && readControl.current === control2 && !mutationInFlight.current) {
1026
1680
  applySnapshot(next);
1027
1681
  setReadError(null);
1028
1682
  setStale(false);
1029
1683
  setLoading(false);
1030
1684
  }
1031
- } catch (cause) {
1032
- if (mounted.current && readControl.current === control && !mutationInFlight.current) {
1033
- setReadError(cause instanceof Error ? cause.message : "Could not read saved references.");
1685
+ } catch (cause2) {
1686
+ if (mounted.current && readControl.current === control2 && !mutationInFlight.current) {
1687
+ setReadError(cause2 instanceof Error ? cause2.message : "Could not read saved references.");
1034
1688
  setLoading(false);
1035
1689
  }
1036
1690
  }
1037
1691
  }
1038
1692
  } finally {
1039
- if (readControl.current === control)
1040
- control.inFlight = false;
1693
+ if (readControl.current === control2)
1694
+ control2.inFlight = false;
1041
1695
  }
1042
1696
  }, [applySnapshot]);
1043
1697
  useEffect(() => {
@@ -1094,9 +1748,9 @@ function useAttachments(api, connection, refreshToken) {
1094
1748
  return false;
1095
1749
  }
1096
1750
  return true;
1097
- } catch (cause) {
1751
+ } catch (cause2) {
1098
1752
  if (mounted.current) {
1099
- setMutationError(cause instanceof Error ? cause.message : "Could not save this thread link.");
1753
+ setMutationError(cause2 instanceof Error ? cause2.message : "Could not save this thread link.");
1100
1754
  }
1101
1755
  return false;
1102
1756
  } finally {
@@ -1220,9 +1874,9 @@ function ThreadPicker({
1220
1874
  if (restoreKeyboardFocus)
1221
1875
  setReturnFocus({ trigger });
1222
1876
  }
1223
- } catch (cause) {
1877
+ } catch (cause2) {
1224
1878
  if (sequence === selectionSequence.current) {
1225
- setSelectionError(cause instanceof Error ? cause.message : "Could not attach this thread.");
1879
+ setSelectionError(cause2 instanceof Error ? cause2.message : "Could not attach this thread.");
1226
1880
  }
1227
1881
  } finally {
1228
1882
  if (sequence === selectionSequence.current)