```ts
export function canonicalTagQuery(text: string): string {
  const decodeEscape = (escaped: string) => {
    if (!escaped.startsWith('~')) return escaped;
    const codeStr = escaped.slice(1, 3);
    if (/^[0-9A-F]{2}$/.test(codeStr)) {
      const code = parseInt(codeStr, 16);
      if (code >= 0x20 && code <= 0x7E) return String.fromCharCode(code);
    }
    throw new Error('Invalid escape sequence');
  };

  const encodeEscape = (glyph: string) => {
    if (!/[!-~]/.test(glyph)) return `~${glyph.charCodeAt(0).toString(16).padStart(2, '0')}`;
    return glyph;
  };

  const items = text.split(';').map(item => {
    const [key, value] = item.split(':', 2);
    if (!key || (value !== undefined && value.includes(':'))) throw new Error('Invalid item format');
    return { key: decodeEscape(key), value: value ? decodeEscape(value) : '' };
  });

  items.sort((a, b) => {
    const keyComparison = a.key.localeCompare(b.key);
    if (keyComparison === 0) return a.value.localeCompare(b.value);
    return keyComparison;
  });

  const uniqueItems = [];
  for (let i = 0; i < items.length; i++) {
    const { key, value } = items[i];
    if (i === 0 || items[i - 1].key !== key || items[i - 1].value !== value) {
      uniqueItems.push({ key, value });
    }
  }

  return uniqueItems.map(({ key, value }) => `${encodeEscape(key)}:${encodeEscape(value)}`).join(';');
}
```