pi-muse-tether 0.1.0 → 0.2.0
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/CHANGELOG.md +19 -0
- package/README.md +24 -8
- package/docs/DETAILS.md +10 -6
- package/index.ts +26 -6
- package/package.json +4 -4
- package/src/catalog.ts +34 -29
- package/src/cli-version.ts +62 -14
- package/src/doctor.ts +3 -2
- package/src/host.ts +91 -18
- package/src/model-route.ts +23 -12
- package/src/provider.ts +132 -82
- package/src/request-ledger.ts +5 -2
- package/src/settings.ts +18 -7
- package/src/tool-result-receipt.ts +278 -119
|
@@ -1,86 +1,198 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import type { BridgeResult } from "pi-tether-core/mcp/bridge";
|
|
3
3
|
|
|
4
|
-
/**
|
|
5
|
-
* an
|
|
6
|
-
export type UnverifiableImage = { partIndex: number; sha256: string; byteLen: number; mimeType: string };
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
4
|
+
/** MSP folds text chunks with LF boundaries and emits image metadata,
|
|
5
|
+
* never an attestation of pixels. Keep original parts for the Pi journal. */
|
|
6
|
+
export type UnverifiableImage = { partIndex: number; sha256: string; byteLen: number; mimeType: string; modelVisibility?: "omitted-error-result" };
|
|
7
|
+
const imageMagic: Record<string, (b: Buffer) => boolean> = {
|
|
8
|
+
"image/png": b => b.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])),
|
|
9
|
+
"image/jpeg": b => b[0] === 255 && b[1] === 216 && b[2] === 255,
|
|
10
|
+
"image/gif": b => ["GIF87a", "GIF89a"].includes(b.subarray(0,6).toString("ascii")),
|
|
11
|
+
"image/webp": b => b.subarray(0,4).toString("ascii") === "RIFF" && b.subarray(8,12).toString("ascii") === "WEBP",
|
|
12
|
+
};
|
|
13
|
+
function imageDeclarations(sent: BridgeResult): UnverifiableImage[] {
|
|
14
|
+
const images: UnverifiableImage[] = [];
|
|
15
|
+
for (const [partIndex, part] of sent.content.entries()) {
|
|
16
|
+
if (part.type === "text" && typeof part.text === "string") continue;
|
|
17
|
+
if (part.type !== "image" || !part.data || !imageMagic[part.mimeType])
|
|
18
|
+
throw new Error("Muse tool result cannot verify MCP parts: unsupported image or content type");
|
|
19
|
+
const bytes = Buffer.from(part.data, "base64");
|
|
20
|
+
if (bytes.toString("base64") !== part.data || !imageMagic[part.mimeType](bytes))
|
|
21
|
+
throw new Error("Muse tool result cannot verify MCP parts: malformed image encoding or MIME signature");
|
|
22
|
+
images.push({ partIndex, sha256: createHash("sha256").update(bytes).digest("hex"), byteLen: bytes.length, mimeType: part.mimeType,
|
|
23
|
+
...(sent.isError === true ? {modelVisibility: "omitted-error-result" as const} : {}) });
|
|
24
|
+
}
|
|
25
|
+
return images;
|
|
16
26
|
}
|
|
17
27
|
export function assertToolResultVerifiable(sent: BridgeResult): void {
|
|
18
|
-
|
|
19
|
-
const multiText = sent.isError !== true && sent.content.length > 1 && sent.content.every(p => p.type === "text" && p.text.length > 0);
|
|
20
|
-
if (!singleText && !multiText && !imageDeclaration(sent)) {
|
|
21
|
-
const kinds = sent.content.map(p => p.type).join(",");
|
|
22
|
-
throw new Error(`Muse tool result cannot verify MCP parts [${kinds}]: MSP visibleOutput flattens text; modelVisibleContent exposes image metadata, not bytes or part boundaries`);
|
|
23
|
-
}
|
|
28
|
+
imageDeclarations(sent);
|
|
24
29
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
30
|
+
/** visibleBytes includes any displayed ellipsis; candidate offsets address the original projection. */
|
|
31
|
+
export type TruncatedView = { visibleBytes: number; projectionBytes: number; omittedOffsetBytes: number; omittedByteLen: number; sha256: string; ellipsisIdentity: "not-present" | "generated" | "ambiguous"; candidateOmittedOffsetsBytes: number[]; sources: {partIndex:number;partOffsetBytes:number;byteLen:number}[] };
|
|
32
|
+
/** MSP 1.4.14 live capture: 65,536 view bytes ended with U+2026, after an
|
|
33
|
+
* exact 65,533-byte original prefix. These observed lengths are not limits. */
|
|
34
|
+
function viewPrefixes(visible: string, full: string): string[] {
|
|
35
|
+
const candidates = [visible, ...(visible.endsWith("…") ? [visible.slice(0,-1)] : [])];
|
|
36
|
+
return candidates.filter(prefix => !(prefix.length && /[\uD800-\uDBFF]/.test(prefix.at(-1)!)) && full.startsWith(prefix));
|
|
37
|
+
}
|
|
38
|
+
export function toolResultReceipt(item: any, sent: BridgeResult, stored?: string, onRedactions?: (spans: VendorRedaction[]) => void, onImages?: (images: UnverifiableImage[]) => void, onTruncatedView?: (view: TruncatedView) => void): BridgeResult {
|
|
39
|
+
const images = imageDeclarations(sent);
|
|
40
|
+
if (images.length && !onImages) throw new Error("Muse image receipt requires declared-unverifiable reporting");
|
|
28
41
|
if (typeof item.visibleOutput !== "string") throw new Error("Muse tool result missing visibleOutput");
|
|
29
|
-
if (item.truncated
|
|
42
|
+
if (item.truncated !== undefined && typeof item.truncated !== "boolean")
|
|
43
|
+
throw new Error("Muse tool result truncated flag must be boolean");
|
|
44
|
+
const partial = item.truncated === true && stored === undefined;
|
|
45
|
+
if (partial && item.outputRef !== undefined && (!item.outputRef || !["missing","unsupported","accessFailed"].includes(item.outputRef.availability)))
|
|
46
|
+
throw new Error("Muse truncated view outputRef requires strict readback or known unavailability");
|
|
47
|
+
if (partial && (!onTruncatedView || sent.isError === true || images.length))
|
|
48
|
+
throw new Error("Muse truncated view requires full readback for this result shape");
|
|
30
49
|
const output = stored ?? item.visibleOutput;
|
|
31
|
-
if (stored !== undefined)
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
50
|
+
if (stored !== undefined && (item.truncated ? viewPrefixes(item.visibleOutput,stored).length === 0 : stored !== item.visibleOutput))
|
|
51
|
+
throw new Error("Muse stored tool output differs from visibleOutput");
|
|
52
|
+
let actual = output;
|
|
35
53
|
if (sent.isError === true) {
|
|
36
|
-
// ENOENT-style error frame: failed + verbatim failureReason; the display adds this prefix.
|
|
37
54
|
if (item.status !== "failed" || item.failureKind !== undefined || typeof item.failureReason !== "string")
|
|
38
55
|
throw new Error("Muse MCP error receipt requires failed status and verbatim failureReason without a host failureKind");
|
|
39
56
|
if (output !== `tool failed: ${item.failureReason}`) throw new Error("Muse MCP error visibleOutput differs from failureReason");
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
if (item.status !== "completed" || item.failureReason !== undefined || item.failureKind !== undefined)
|
|
57
|
+
actual = item.failureReason;
|
|
58
|
+
} else if (item.status !== "completed" || item.failureReason !== undefined || item.failureKind !== undefined) {
|
|
43
59
|
throw new Error("Muse successful MCP receipt has non-completed status or failure fields");
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
60
|
+
}
|
|
61
|
+
// Construct the ordered native projection from Pi parts. Never search/remove
|
|
62
|
+
// placeholder-shaped strings: literal tool text and leading LF remain bytes.
|
|
63
|
+
let expected = "";
|
|
64
|
+
const protectedImages: { start: number; end: number }[] = [];
|
|
65
|
+
const textSources: {partIndex:number; start:number; end:number}[] = [];
|
|
66
|
+
for (const [index, part] of sent.content.entries()) {
|
|
67
|
+
if (part.type === "text") {
|
|
68
|
+
// Native string folding ignores leading empty chunks but preserves a
|
|
69
|
+
// separator before an empty chunk after nonempty output (captured live).
|
|
70
|
+
if (expected) expected += "\n";
|
|
71
|
+
const start = Buffer.byteLength(expected);
|
|
72
|
+
expected += part.text;
|
|
73
|
+
textSources.push({partIndex:index,start,end:Buffer.byteLength(expected)});
|
|
74
|
+
} else {
|
|
75
|
+
// The official client's failed MCP path projects text only. Images were
|
|
76
|
+
// delivered to MCP, NOT exposed to the model; declare that known loss.
|
|
77
|
+
if (sent.isError === true) continue;
|
|
78
|
+
const image = images.find(image => image.partIndex === index)!;
|
|
79
|
+
if (expected) expected += "\n";
|
|
80
|
+
const start = expected.length;
|
|
81
|
+
expected += `[MCP image content: media_type=${image.mimeType}, bytes=${image.byteLen}]`;
|
|
82
|
+
protectedImages.push({ start, end: expected.length });
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
// Failed MCP results use a separate native codec: all text parts are
|
|
86
|
+
// LF-joined (including leading empties), and images are dropped.
|
|
87
|
+
if (sent.isError === true) {
|
|
88
|
+
expected = sent.content.filter(part => part.type === "text").map(part => (part as {text:string}).text).join("\n");
|
|
89
|
+
if (!expected) expected = "MCP tool returned an error";
|
|
90
|
+
textSources.length=0;
|
|
91
|
+
let offset=0;
|
|
92
|
+
for(const [partIndex,part] of sent.content.entries()) if(part.type==="text") {
|
|
93
|
+
textSources.push({partIndex,start:offset,end:offset+Buffer.byteLength(part.text)});
|
|
94
|
+
offset+=Buffer.byteLength(part.text)+1;
|
|
95
|
+
}
|
|
96
|
+
} else if (!expected) expected = "[MCP tool returned no content]";
|
|
97
|
+
const locateSources=(redactions:VendorRedaction[])=>{
|
|
98
|
+
for(const span of redactions) span.sources=textSources.filter(s=>s.start<span.piOffsetBytes+span.piByteLen && s.end>span.piOffsetBytes).map(s=>({partIndex:s.partIndex,partOffsetBytes:Math.max(s.start,span.piOffsetBytes)-s.start,byteLen:Math.min(s.end,span.piOffsetBytes+span.piByteLen)-Math.max(s.start,span.piOffsetBytes)}));
|
|
99
|
+
};
|
|
100
|
+
if (partial) {
|
|
101
|
+
// The captured combined codec preserves line boundaries. Reconcile
|
|
102
|
+
// complete lines normally and the final line with the same v4 positional
|
|
103
|
+
// alignment in prefix mode, retaining every viable original cut.
|
|
104
|
+
const visibleEnd=actual.lastIndexOf("\n")+1;
|
|
105
|
+
let originalEnd=0;
|
|
106
|
+
for(let at=0;at<visibleEnd;at++) if(actual[at]==="\n") {
|
|
107
|
+
const next=expected.indexOf("\n",originalEnd);
|
|
108
|
+
if(next<0) throw new Error("Muse truncated view has more lines than native projection");
|
|
109
|
+
originalEnd=next+1;
|
|
110
|
+
}
|
|
111
|
+
const completeExpected=expected.slice(0,originalEnd),completeVisible=actual.slice(0,visibleEnd);
|
|
112
|
+
const projected:BridgeResult={content:[{type:"text",text:completeExpected}],isError:false};
|
|
113
|
+
let redactions:VendorRedaction[]=[];
|
|
114
|
+
const observed=reconcileVendorRedactions(projected,{content:[{type:"text",text:completeVisible}],isError:false},spans=>{redactions=spans;});
|
|
115
|
+
if ((observed.content[0] as {text:string}).text!==completeExpected)
|
|
116
|
+
throw new Error("Muse truncated view complete lines differ from native projection");
|
|
117
|
+
if(redactions.length && !onRedactions) throw new Error("Muse truncated view requires declared-redaction reporting");
|
|
118
|
+
const finalVisible=actual.slice(visibleEnd),finalExpected=expected.slice(originalEnd).split("\n",1)[0];
|
|
119
|
+
let finalSpans:VendorRedaction[]=[],prefix:PrefixAlignment|undefined;
|
|
120
|
+
reconcileVendorRedactions({content:[{type:"text",text:finalExpected}],isError:false},
|
|
121
|
+
{content:[{type:"text",text:finalVisible}],isError:false},spans=>{finalSpans=spans;},alignment=>{prefix=alignment;});
|
|
122
|
+
if(!prefix) throw new Error("Muse truncated view differs from native projection prefix");
|
|
123
|
+
const baseBytes=Buffer.byteLength(completeExpected),viewBaseBytes=Buffer.byteLength(completeVisible);
|
|
124
|
+
for(const span of finalSpans) {
|
|
125
|
+
span.piOffsetBytes+=baseBytes;span.museOffsetBytes+=viewBaseBytes;
|
|
126
|
+
if(span.candidateStartBytes)span.candidateStartBytes=span.candidateStartBytes.map(offset=>offset+baseBytes);
|
|
127
|
+
if(span.candidateEndBytes)span.candidateEndBytes=span.candidateEndBytes.map(offset=>offset+baseBytes);
|
|
128
|
+
}
|
|
129
|
+
redactions.push(...finalSpans);
|
|
130
|
+
if(redactions.length && !onRedactions) throw new Error("Muse truncated view requires declared-redaction reporting");
|
|
131
|
+
const candidateOmittedOffsetsBytes=prefix.cuts.map(cut=>baseBytes+Buffer.byteLength(finalExpected.slice(0,cut))).sort((a,b)=>a-b);
|
|
132
|
+
const omittedOffsetBytes=candidateOmittedOffsetsBytes[0], projectionBytes=Buffer.byteLength(expected);
|
|
133
|
+
const ellipsisIdentity=prefix.ellipsisIdentity;
|
|
134
|
+
const omitted = Buffer.from(expected, "utf8").subarray(omittedOffsetBytes);
|
|
135
|
+
locateSources(redactions);
|
|
136
|
+
// Both checks succeeded; publish no partial evidence on a rejected view.
|
|
137
|
+
if(redactions.length) onRedactions!(redactions);
|
|
138
|
+
onTruncatedView!({visibleBytes:Buffer.byteLength(item.visibleOutput),projectionBytes,omittedOffsetBytes,
|
|
139
|
+
omittedByteLen:omitted.length,sha256:createHash("sha256").update(omitted).digest("hex"),ellipsisIdentity,candidateOmittedOffsetsBytes,
|
|
140
|
+
sources:textSources.filter(s=>s.end>omittedOffsetBytes).map(s=>({partIndex:s.partIndex,
|
|
141
|
+
partOffsetBytes:Math.max(s.start,omittedOffsetBytes)-s.start,byteLen:s.end-Math.max(s.start,omittedOffsetBytes)}))});
|
|
142
|
+
return sent;
|
|
143
|
+
}
|
|
144
|
+
const projected: BridgeResult = { content: [{ type: "text", text: expected }], isError: sent.isError === true };
|
|
54
145
|
let redactions: VendorRedaction[] = [];
|
|
55
|
-
const
|
|
56
|
-
if ((
|
|
57
|
-
|
|
58
|
-
|
|
146
|
+
const observed = reconcileVendorRedactions(projected, { content: [{ type: "text", text: actual }], isError: sent.isError === true }, spans => { redactions = spans; });
|
|
147
|
+
if ((observed.content[0] as { text: string }).text !== expected) {
|
|
148
|
+
let at=0;
|
|
149
|
+
while(at<expected.length && at<actual.length && expected[at]===actual[at])at++;
|
|
150
|
+
throw new Error(`Muse tool result text projection mismatch (image placeholder differs or text changed) at projection byte ${Buffer.byteLength(expected.slice(0,at))}, receipt byte ${Buffer.byteLength(actual.slice(0,at))}`);
|
|
151
|
+
}
|
|
152
|
+
for (const span of redactions) {
|
|
153
|
+
if (protectedImages.some(range => span.piOffsetBytes < Buffer.byteLength(expected.slice(0, range.end)) &&
|
|
154
|
+
span.piOffsetBytes + span.piByteLen > Buffer.byteLength(expected.slice(0, range.start))))
|
|
155
|
+
throw new Error("Muse image placeholder differs: redaction cannot hide image metadata");
|
|
156
|
+
}
|
|
157
|
+
locateSources(redactions);
|
|
59
158
|
if (redactions.length) onRedactions?.(redactions);
|
|
60
|
-
if (
|
|
61
|
-
//
|
|
62
|
-
//
|
|
159
|
+
if (images.length) onImages?.(images);
|
|
160
|
+
// modelVisibleContent may contain image derivatives or metadata. It is useful
|
|
161
|
+
// evidence of delivery but never upgrades these declarations to exact pixels.
|
|
63
162
|
return sent;
|
|
64
163
|
}
|
|
65
164
|
|
|
66
|
-
/**
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
|
|
70
|
-
|
|
165
|
+
/** Offsets address UTF-8 bytes in the native projection and vendor receipt.
|
|
166
|
+
* Ambiguous spans cover the union of viable alignments, not an invented exact
|
|
167
|
+
* removal. Hashes describe that source range; removed bytes are never logged. */
|
|
168
|
+
export type VendorRedaction = {
|
|
169
|
+
piOffsetBytes: number; museOffsetBytes: number; piByteLen: number; sha256: string;
|
|
170
|
+
reason: "vendor-redaction" | "ambiguous-vendor-redaction" | "vendor-bearer-prefix";
|
|
171
|
+
alignment: "unique" | "ambiguous";
|
|
172
|
+
ambiguityReason?: "multiple-alignments" | "literal-marker-identity";
|
|
173
|
+
sources?: {partIndex:number;partOffsetBytes:number;byteLen:number}[];
|
|
174
|
+
candidateStartBytes?: number[]; candidateEndBytes?: number[];
|
|
175
|
+
};
|
|
71
176
|
const marker = "[REDACTED]";
|
|
72
|
-
|
|
177
|
+
type PrefixAlignment={cuts:number[];ellipsisIdentity:TruncatedView["ellipsisIdentity"]};
|
|
178
|
+
function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, report?: (spans: VendorRedaction[]) => void, onPrefix?: (alignment:PrefixAlignment)=>void): BridgeResult {
|
|
73
179
|
const pi = (sent.content[0] as {text:string}).text;
|
|
74
180
|
const muse = (observed.content[0] as {text:string}).text;
|
|
75
|
-
if
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const invalid = () => new Error(
|
|
83
|
-
|
|
181
|
+
if(onPrefix && !muse.includes(marker)) {
|
|
182
|
+
const prefixes=viewPrefixes(muse,pi);
|
|
183
|
+
if(!prefixes.length) throw new Error("Muse truncated view differs from native projection prefix");
|
|
184
|
+
onPrefix({cuts:prefixes.map(p=>p.length),ellipsisIdentity:muse.endsWith("…") ? prefixes.length===2 ? "ambiguous" : "generated" : "not-present"});
|
|
185
|
+
return sent;
|
|
186
|
+
}
|
|
187
|
+
if (!onPrefix && (pi === muse || !muse.includes(marker))) return observed;
|
|
188
|
+
const invalid = (piAt: number, museAt: number) => new Error(`Muse tool result mismatch: invalid vendor redaction at projection byte ${Buffer.byteLength(pi.slice(0, piAt))}, receipt byte ${Buffer.byteLength(muse.slice(0, museAt))}`);
|
|
189
|
+
const spans: VendorRedaction[] = [];
|
|
190
|
+
function record(start: number, end: number, visible: number, reason: VendorRedaction["reason"], alignment: VendorRedaction["alignment"], candidates?: {starts:number[];ends:number[]}) {
|
|
191
|
+
spans.push({piOffsetBytes:Buffer.byteLength(pi.slice(0,start)),museOffsetBytes:Buffer.byteLength(muse.slice(0,visible)),
|
|
192
|
+
piByteLen:Buffer.byteLength(pi.slice(start,end)),sha256:createHash("sha256").update(pi.slice(start,end)).digest("hex"),reason,alignment,
|
|
193
|
+
...(candidates ? {candidateStartBytes:candidates.starts.map(a=>Buffer.byteLength(pi.slice(0,a))),candidateEndBytes:candidates.ends.map(a=>Buffer.byteLength(pi.slice(0,a)))} : {})});
|
|
194
|
+
}
|
|
195
|
+
// KMP keeps literal matching linear in the source length per marker.
|
|
84
196
|
function starts(text: string, chunk: string): Uint8Array {
|
|
85
197
|
const found = new Uint8Array(text.length + 1);
|
|
86
198
|
if (!chunk.length) { found.fill(1); return found; }
|
|
@@ -97,70 +209,117 @@ function reconcileVendorRedactions(sent: BridgeResult, observed: BridgeResult, r
|
|
|
97
209
|
}
|
|
98
210
|
return found;
|
|
99
211
|
}
|
|
100
|
-
function
|
|
101
|
-
const pieces =
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
const
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
212
|
+
function line(text: string, visible: string, piBase: number, museBase: number) {
|
|
213
|
+
const pieces: string[] = [], widths: number[] = [], positions: number[] = [];
|
|
214
|
+
let cursor = 0, at: number;
|
|
215
|
+
while ((at = visible.indexOf(marker, cursor)) !== -1) {
|
|
216
|
+
pieces.push(visible.slice(cursor, at)); positions.push(at); cursor = at;
|
|
217
|
+
let width = 0;
|
|
218
|
+
while (visible.startsWith(marker, cursor)) { width++; cursor += marker.length; }
|
|
219
|
+
widths.push(width);
|
|
220
|
+
}
|
|
221
|
+
pieces.push(visible.slice(cursor));
|
|
222
|
+
const n = text.length, count = widths.length;
|
|
223
|
+
const boundary=(at:number)=>!(at>0 && at<n && /[\uD800-\uDBFF]/.test(text[at-1]) && /[\uDC00-\uDFFF]/.test(text[at]));
|
|
224
|
+
if (!count || !boundary(pieces[0].length)) throw invalid(piBase, museBase);
|
|
225
|
+
const matches = pieces.map((chunk,i) => {
|
|
226
|
+
const exact = starts(text, chunk);
|
|
227
|
+
// Captured official-client codec: `bearer permission.` becomes
|
|
228
|
+
// `Bearer [REDACTED]`. ONLY the prefix immediately before a marker is
|
|
229
|
+
// case-folded; no other text/case/status/metadata normalization is allowed.
|
|
230
|
+
if (i < count && chunk.endsWith("Bearer ")) {
|
|
231
|
+
const prefix = chunk.slice(0,-7), candidates = starts(text,prefix);
|
|
232
|
+
for(let a=0;a+chunk.length<=n;a++)
|
|
233
|
+
if(candidates[a] && text.slice(a+prefix.length,a+chunk.length).toLowerCase()==="bearer ") exact[a]=1;
|
|
118
234
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
235
|
+
return exact;
|
|
236
|
+
});
|
|
237
|
+
if (!matches[0][0]) throw invalid(piBase, museBase);
|
|
238
|
+
// Backward feasibility. A marker declares a nonempty single-line hole.
|
|
239
|
+
// Literal marker text is allowed inside a hole: when that loses identity,
|
|
240
|
+
// the evidence is ambiguous, never silently claimed exact or made fatal.
|
|
241
|
+
const layers: Uint8Array[] = [];
|
|
242
|
+
let next = new Uint8Array(n+1); if(onPrefix)next.fill(1);else next[n]=1;
|
|
243
|
+
const last=pieces[count],shortLast=onPrefix && last.endsWith("…") ? last.slice(0,-1) : undefined;
|
|
244
|
+
const shortMatches=shortLast===undefined ? undefined : starts(text,shortLast);
|
|
245
|
+
for(let i=count-1;i>=0;i--) {
|
|
246
|
+
const chunk=pieces[i+1], viable=new Uint8Array(n+1);
|
|
247
|
+
for(let end=0;end<=n;end++)
|
|
248
|
+
viable[end]=boundary(end) && ((end+chunk.length<=n && matches[i+1][end] && boundary(end+chunk.length) && next[end+chunk.length]) ||
|
|
249
|
+
(i===count-1 && shortLast!==undefined && end+shortLast.length<=n && shortMatches![end] && boundary(end+shortLast.length) && next[end+shortLast.length])) ? 1 : 0;
|
|
250
|
+
layers[i]=viable;
|
|
251
|
+
const current=new Uint8Array(n+1); let found=false;
|
|
252
|
+
for(let a=n;a>=0;a--) {
|
|
253
|
+
// CR is a line boundary too, not something a declared hole may hide.
|
|
254
|
+
if(text[a]==="\r") found=false;
|
|
255
|
+
current[a]=found?1:0;
|
|
256
|
+
if(viable[a]) found=true;
|
|
130
257
|
}
|
|
131
|
-
|
|
258
|
+
next=current;
|
|
132
259
|
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
260
|
+
if(!next[pieces[0].length]) throw invalid(piBase, museBase);
|
|
261
|
+
// Forward reachable starts plus backward viable ends give all candidate
|
|
262
|
+
// boundaries without enumerating exponentially many complete parses.
|
|
263
|
+
let reachable=new Uint8Array(n+1);reachable[pieces[0].length]=1;
|
|
264
|
+
for(let i=0;i<count;i++) {
|
|
265
|
+
const viable=layers[i], chunk=pieces[i+1];
|
|
266
|
+
const candidateStarts:number[]=[], candidateEnds:number[]=[];
|
|
267
|
+
let lastEnd=-1;
|
|
268
|
+
for(let a=n;a>=0;a--) {
|
|
269
|
+
if(text[a]==="\r") lastEnd=-1;
|
|
270
|
+
if(reachable[a] && lastEnd>a) candidateStarts.push(a);
|
|
271
|
+
if(viable[a]) lastEnd=a;
|
|
272
|
+
}
|
|
273
|
+
candidateStarts.reverse();
|
|
274
|
+
let seen=false;
|
|
275
|
+
const following=new Uint8Array(n+1);let fullCut=false,shortCut=false;
|
|
276
|
+
for(let end=0;end<=n;end++) {
|
|
277
|
+
if(text[end-1]==="\r") seen=false;
|
|
278
|
+
if(end>0 && reachable[end-1] && text[end-1]!=="\r") seen=true;
|
|
279
|
+
if(seen && viable[end]) {
|
|
280
|
+
candidateEnds.push(end);
|
|
281
|
+
if(i===count-1 && onPrefix) {
|
|
282
|
+
if(end+chunk.length<=n && matches[i+1][end] && boundary(end+chunk.length) && !(end+chunk.length>0 && /[\uD800-\uDBFF]/.test(text[end+chunk.length-1]))) {following[end+chunk.length]=1;fullCut=true;}
|
|
283
|
+
if(shortLast!==undefined && end+shortLast.length<=n && shortMatches![end] && boundary(end+shortLast.length) && !(end+shortLast.length>0 && /[\uD800-\uDBFF]/.test(text[end+shortLast.length-1]))) {following[end+shortLast.length]=1;shortCut=true;}
|
|
284
|
+
} else following[end+chunk.length]=1;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
const multiple=candidateStarts.length!==1 || candidateEnds.length!==1;
|
|
288
|
+
const start=candidateStarts[0], end=candidateEnds.at(-1)!;
|
|
289
|
+
const literal=!multiple && text.slice(start,end)===marker.repeat(widths[i]);
|
|
290
|
+
const literalIdentity=!literal && text.slice(start,end).includes(marker);
|
|
291
|
+
const ambiguous=multiple || literalIdentity;
|
|
292
|
+
if(!literal)record(piBase+start,piBase+end,museBase+positions[i],ambiguous?"ambiguous-vendor-redaction":"vendor-redaction",ambiguous?"ambiguous":"unique",
|
|
293
|
+
ambiguous?{starts:candidateStarts.map(a=>piBase+a),ends:candidateEnds.map(a=>piBase+a)}:undefined);
|
|
294
|
+
if(!literal && ambiguous)spans.at(-1)!.ambiguityReason=multiple?"multiple-alignments":"literal-marker-identity";
|
|
295
|
+
// A canonicalized Bearer prefix belongs to the same declared codec loss,
|
|
296
|
+
// with its own exact source range (not hidden in the redaction's hash).
|
|
297
|
+
const prior=pieces[i];
|
|
298
|
+
if(prior.endsWith("Bearer ")) {
|
|
299
|
+
for(const a of candidateStarts) {
|
|
300
|
+
const p=a-7;
|
|
301
|
+
if(text.slice(p,a)!=="Bearer ")record(piBase+p,piBase+a,museBase+positions[i]-7,"vendor-bearer-prefix",ambiguous?"ambiguous":"unique");
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
reachable=following;
|
|
305
|
+
if(i===count-1 && onPrefix) {
|
|
306
|
+
const cuts:number[]=[];
|
|
307
|
+
for(let cut=0;cut<=n;cut++)if(following[cut] && !(cut>0 && /[\uD800-\uDBFF]/.test(text[cut-1])))cuts.push(cut);
|
|
308
|
+
if(!cuts.length)throw invalid(piBase,museBase);
|
|
309
|
+
onPrefix({cuts,ellipsisIdentity:shortLast===undefined ? "not-present" : fullCut && shortCut ? "ambiguous" : shortCut ? "generated" : "ambiguous"});
|
|
310
|
+
}
|
|
141
311
|
}
|
|
142
|
-
return spans;
|
|
143
312
|
}
|
|
144
|
-
const piLines
|
|
145
|
-
if
|
|
146
|
-
|
|
147
|
-
for
|
|
148
|
-
if
|
|
149
|
-
|
|
150
|
-
piBase += piLines[i].length + 1; museBase += museLines[i].length + 1;
|
|
313
|
+
const piLines=pi.split("\n"), museLines=muse.split("\n");
|
|
314
|
+
if(piLines.length!==museLines.length)throw invalid(0,0);
|
|
315
|
+
let piBase=0,museBase=0;
|
|
316
|
+
for(let i=0;i<piLines.length;i++) {
|
|
317
|
+
if(onPrefix || piLines[i]!==museLines[i])line(piLines[i],museLines[i],piBase,museBase);
|
|
318
|
+
piBase+=piLines[i].length+1;museBase+=museLines[i].length+1;
|
|
151
319
|
}
|
|
152
|
-
if
|
|
153
|
-
const spans = aligned.map(s => ({
|
|
154
|
-
piOffsetBytes: Buffer.byteLength(pi.slice(0, s.piStart)),
|
|
155
|
-
museOffsetBytes: Buffer.byteLength(muse.slice(0, s.museStart)),
|
|
156
|
-
piByteLen: Buffer.byteLength(pi.slice(s.piStart, s.piEnd)),
|
|
157
|
-
sha256: createHash("sha256").update(pi.slice(s.piStart, s.piEnd)).digest("hex"),
|
|
158
|
-
}));
|
|
159
|
-
// Reconstruct only after proving every byte outside the declared holes. The
|
|
160
|
-
// bridge's original journal hash remains exact; the separate ledger records
|
|
161
|
-
// that the actual vendor receipt contained holes, never exact consumption.
|
|
320
|
+
if(!spans.length && !onPrefix)throw invalid(0,0);
|
|
162
321
|
report?.(spans);
|
|
163
|
-
return {
|
|
322
|
+
return {content:[{type:"text",text:pi}],isError:observed.isError};
|
|
164
323
|
}
|
|
165
324
|
|
|
166
325
|
export type OutputPage = { byteLen: number; content: string; encoding: string; eof: boolean; mediaType: string; offsetBytes: number };
|