File size: 30,352 Bytes
096d5ee |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 |
/**
* universal-symbolics-registry.ts
*
* Core registry for unified symbolic operations across all LLM vendors.
* This registry enables transformation between different symbolic grammars.
*/
// Import core schema definitions
import {
ModelVendor,
SymbolicPrimitive,
GrammarStyle,
SymbolicOperation,
VendorImplementation,
SYMBOLIC_RUNTIME_SCHEMA
} from './universal-symbolics-runtime';
/**
* Symbol Mapping Record Types
*/
export interface GlyphMapping {
glyph: string;
primitive: SymbolicPrimitive;
description: string;
}
export interface TagMapping {
tag: string;
primitive: SymbolicPrimitive;
vendor: ModelVendor;
description: string;
}
export interface SlashMapping {
slash: string;
primitive: SymbolicPrimitive;
vendor: ModelVendor;
description: string;
}
export interface DotMapping {
dot: string;
primitive: SymbolicPrimitive;
description: string;
}
export interface OperatorMapping {
operator: string;
primitive: SymbolicPrimitive;
description: string;
}
/**
* Universal Symbolics Registry
*
* Maintains mappings between different symbolic representations
* and provides transformation functions for converting between them.
*/
export class SymbolicsRegistry {
// Mapping collections
private glyphMappings: Map<string, GlyphMapping>;
private tagMappings: Map<string, TagMapping>;
private slashMappings: Map<string, SlashMapping>;
private dotMappings: Map<string, DotMapping>;
private operatorMappings: Map<string, OperatorMapping>;
// Vendor capabilities
private vendorCapabilities: Map<ModelVendor, Set<SymbolicPrimitive>>;
// Custom extensions
private customSymbols: Map<string, SymbolicOperation>;
constructor() {
// Initialize maps
this.glyphMappings = new Map();
this.tagMappings = new Map();
this.slashMappings = new Map();
this.dotMappings = new Map();
this.operatorMappings = new Map();
this.vendorCapabilities = new Map();
this.customSymbols = new Map();
// Initialize registry with built-in mappings
this.initializeRegistry();
}
/**
* Initialize the registry with all built-in mappings
*/
private initializeRegistry(): void {
// Initialize vendor capabilities
for (const vendor of Object.values(ModelVendor)) {
this.vendorCapabilities.set(vendor, new Set());
}
// Process schema to populate maps
for (const operation of SYMBOLIC_RUNTIME_SCHEMA) {
// Register glyph mappings
if (operation.glyphs) {
for (const glyph of operation.glyphs) {
this.registerGlyph(glyph, operation.type, `Glyph for ${operation.name}`);
}
}
// Register tag mappings
if (operation.tags) {
for (const tag of operation.tags) {
for (const impl of operation.vendorImplementations) {
if (impl.style === GrammarStyle.XML_TAGS) {
this.registerTag(tag, operation.type, impl.vendor, `XML tag for ${operation.name}`);
}
}
}
}
// Register slash mappings
if (operation.slashes) {
for (const slash of operation.slashes) {
for (const impl of operation.vendorImplementations) {
if (impl.style === GrammarStyle.SLASH_COMMANDS) {
this.registerSlash(slash, operation.type, impl.vendor, `Slash command for ${operation.name}`);
}
}
}
}
// Register dot mappings
const dotCommand = operation.universalSyntax.split('{')[0];
this.registerDot(dotCommand, operation.type, `Universal syntax for ${operation.name}`);
// Register vendor capabilities
for (const impl of operation.vendorImplementations) {
const capabilities = this.vendorCapabilities.get(impl.vendor);
if (capabilities) {
capabilities.add(operation.type);
}
}
}
}
/**
* Register a glyph mapping
*/
public registerGlyph(glyph: string, primitive: SymbolicPrimitive, description: string): void {
this.glyphMappings.set(glyph, { glyph, primitive, description });
}
/**
* Register a tag mapping
*/
public registerTag(tag: string, primitive: SymbolicPrimitive, vendor: ModelVendor, description: string): void {
this.tagMappings.set(`${vendor}:${tag}`, { tag, primitive, vendor, description });
}
/**
* Register a slash mapping
*/
public registerSlash(slash: string, primitive: SymbolicPrimitive, vendor: ModelVendor, description: string): void {
this.slashMappings.set(`${vendor}:${slash}`, { slash, primitive, vendor, description });
}
/**
* Register a dot mapping
*/
public registerDot(dot: string, primitive: SymbolicPrimitive, description: string): void {
this.dotMappings.set(dot, { dot, primitive, description });
}
/**
* Register an operator mapping
*/
public registerOperator(operator: string, primitive: SymbolicPrimitive, description: string): void {
this.operatorMappings.set(operator, { operator, primitive, description });
}
/**
* Register a custom symbolic operation
*/
public registerCustomSymbol(operation: SymbolicOperation): void {
this.customSymbols.set(operation.name, operation);
}
/**
* Get all glyph mappings
*/
public getAllGlyphMappings(): GlyphMapping[] {
return Array.from(this.glyphMappings.values());
}
/**
* Get all tag mappings
*/
public getAllTagMappings(): TagMapping[] {
return Array.from(this.tagMappings.values());
}
/**
* Get all slash mappings
*/
public getAllSlashMappings(): SlashMapping[] {
return Array.from(this.slashMappings.values());
}
/**
* Get all dot mappings
*/
public getAllDotMappings(): DotMapping[] {
return Array.from(this.dotMappings.values());
}
/**
* Get all operator mappings
*/
public getAllOperatorMappings(): OperatorMapping[] {
return Array.from(this.operatorMappings.values());
}
/**
* Get symbolic primitive by glyph
*/
public getPrimitiveByGlyph(glyph: string): SymbolicPrimitive | undefined {
const mapping = this.glyphMappings.get(glyph);
return mapping?.primitive;
}
/**
* Get symbolic primitive by tag
*/
public getPrimitiveByTag(tag: string, vendor: ModelVendor): SymbolicPrimitive | undefined {
const mapping = this.tagMappings.get(`${vendor}:${tag}`);
return mapping?.primitive;
}
/**
* Get symbolic primitive by slash command
*/
public getPrimitiveBySlash(slash: string, vendor: ModelVendor): SymbolicPrimitive | undefined {
const mapping = this.slashMappings.get(`${vendor}:${slash}`);
return mapping?.primitive;
}
/**
* Get symbolic primitive by dot command
*/
public getPrimitiveByDot(dot: string): SymbolicPrimitive | undefined {
const mapping = this.dotMappings.get(dot);
return mapping?.primitive;
}
/**
* Get symbolic primitive by operator
*/
public getPrimitiveByOperator(operator: string): SymbolicPrimitive | undefined {
const mapping = this.operatorMappings.get(operator);
return mapping?.primitive;
}
/**
* Get symbolic operation by primitive
*/
public getOperationByPrimitive(primitive: SymbolicPrimitive): SymbolicOperation | undefined {
// Check built-in operations
const builtIn = SYMBOLIC_RUNTIME_SCHEMA.find(op => op.type === primitive);
if (builtIn) return builtIn;
// Check custom operations
for (const operation of this.customSymbols.values()) {
if (operation.type === primitive) return operation;
}
return undefined;
}
/**
* Get vendor implementation for a primitive
*/
public getVendorImplementation(primitive: SymbolicPrimitive, vendor: ModelVendor): VendorImplementation | undefined {
const operation = this.getOperationByPrimitive(primitive);
if (!operation) return undefined;
return operation.vendorImplementations.find(impl => impl.vendor === vendor);
}
/**
* Check if a vendor supports a primitive
*/
public vendorSupports(vendor: ModelVendor, primitive: SymbolicPrimitive): boolean {
const capabilities = this.vendorCapabilities.get(vendor);
if (!capabilities) return false;
return capabilities.has(primitive);
}
/**
* Get all primitives supported by a vendor
*/
public getVendorSupportedPrimitives(vendor: ModelVendor): SymbolicPrimitive[] {
const capabilities = this.vendorCapabilities.get(vendor);
if (!capabilities) return [];
return Array.from(capabilities);
}
/**
* Get support level for a primitive across all vendors
*/
public getPrimitiveSupportMap(primitive: SymbolicPrimitive): Record<ModelVendor, boolean> {
const result: Record<ModelVendor, boolean> = {} as Record<ModelVendor, boolean>;
for (const vendor of Object.values(ModelVendor)) {
result[vendor] = this.vendorSupports(vendor, primitive);
}
return result;
}
/**
* Transform universal syntax to vendor-specific syntax
*/
public transformToVendor(universalSyntax: string, vendor: ModelVendor): string {
// Parse universal syntax
const match = universalSyntax.match(/^(.+?)\{(.+)\}$/);
if (!match) return universalSyntax; // Not a valid universal syntax
const [_, command, paramsString] = match;
// Parse parameters
let params: Record<string, any> = {};
try {
// Simple parsing for demonstration - in production, would need a more robust parser
paramsString.split(',').forEach(pair => {
const [key, value] = pair.split(':').map(s => s.trim());
params[key] = value;
});
} catch (error) {
return universalSyntax; // Invalid parameters
}
// Get primitive from command
const primitive = this.getPrimitiveByDot(command);
if (!primitive) return universalSyntax; // Unknown command
// Get vendor implementation
const implementation = this.getVendorImplementation(primitive, vendor);
if (!implementation) return universalSyntax; // Vendor doesn't support this primitive
// Transform to vendor syntax
switch (implementation.style) {
case GrammarStyle.XML_TAGS:
if (implementation.prefix && implementation.suffix) {
return `${implementation.prefix}${params.content || ''}${implementation.suffix}`;
}
break;
case GrammarStyle.SLASH_COMMANDS:
if (implementation.prefix) {
return `${implementation.prefix} ${params.content || ''}`;
}
break;
case GrammarStyle.API_PARAMETERS:
// Would be handled at API level, not string transformation
return `API parameter: ${JSON.stringify(params)}`;
case GrammarStyle.SYSTEM_PROMPTS:
// Transform to system prompt format
const operation = this.getOperationByPrimitive(primitive);
return `System instruction for ${operation?.name || primitive}: ${params.content || ''}`;
// Add more cases for other grammar styles
}
return universalSyntax; // Default fallback
}
/**
* Transform vendor-specific syntax to universal syntax
*/
public transformToUniversal(vendorSyntax: string, vendor: ModelVendor): string {
// XML tags
if (vendor === ModelVendor.ANTHROPIC ||
vendor === ModelVendor.UNIVERSAL) {
const tagMatches = vendorSyntax.match(/<(\w+)>([\s\S]*?)<\/\1>/);
if (tagMatches) {
const [_, tag, content] = tagMatches;
const primitive = this.getPrimitiveByTag(tag, vendor);
if (primitive) {
const operation = this.getOperationByPrimitive(primitive);
if (operation) {
return `${operation.universalSyntax.split('{')[0]}{content: "${content}"}`;
}
}
}
}
// Slash commands
if (vendor === ModelVendor.OPENAI ||
vendor === ModelVendor.QWEN ||
vendor === ModelVendor.UNIVERSAL) {
const slashMatches = vendorSyntax.match(/^\/(\w+)\s+([\s\S]*)$/);
if (slashMatches) {
const [_, slash, content] = slashMatches;
const primitive = this.getPrimitiveBySlash(slash, vendor);
if (primitive) {
const operation = this.getOperationByPrimitive(primitive);
if (operation) {
return `${operation.universalSyntax.split('{')[0]}{content: "${content}"}`;
}
}
}
}
// Add more parsing for other grammar styles
return vendorSyntax; // Default fallback
}
/**
* Parse symbolic operations from text
*/
public parseSymbolicOperations(text: string, vendor: ModelVendor): Array<{ primitive: SymbolicPrimitive, params: any }> {
const operations: Array<{ primitive: SymbolicPrimitive, params: any }> = [];
// Parse based on vendor's grammar style
switch (vendor) {
case ModelVendor.ANTHROPIC:
// Parse XML tags
const tagRegex = /<(\w+)>([\s\S]*?)<\/\1>/g;
let tagMatch;
while ((tagMatch = tagRegex.exec(text)) !== null) {
const tag = tagMatch[1];
const content = tagMatch[2];
const primitive = this.getPrimitiveByTag(tag, vendor);
if (primitive) {
operations.push({
primitive,
params: { content }
});
}
}
break;
case ModelVendor.QWEN:
case ModelVendor.OPENAI:
// Parse slash commands
const slashRegex = /\/(\w+)\s+([\s\S]*?)(?=\/\w+\s+|$)/g;
let slashMatch;
while ((slashMatch = slashRegex.exec(text)) !== null) {
const slash = slashMatch[1];
const content = slashMatch[2].trim();
const primitive = this.getPrimitiveBySlash(slash, vendor);
if (primitive) {
operations.push({
primitive,
params: { content }
});
}
}
break;
// Add cases for other vendors
}
return operations;
}
/**
* Generate symbolic content in vendor-specific format
*/
public generateSymbolicContent(operations: Array<{ primitive: SymbolicPrimitive, params: any }>, vendor: ModelVendor): string {
let content = '';
for (const { primitive, params } of operations) {
const implementation = this.getV
/**
* Generate symbolic content in vendor-specific format
*/
public generateSymbolicContent(operations: Array<{ primitive: SymbolicPrimitive, params: any }>, vendor: ModelVendor): string {
let content = '';
for (const { primitive, params } of operations) {
const implementation = this.getVendorImplementation(primitive, vendor);
if (!implementation) continue; // Skip if vendor doesn't support this primitive
switch (implementation.style) {
case GrammarStyle.XML_TAGS:
if (implementation.prefix && implementation.suffix) {
content += `${implementation.prefix}${params.content || ''}${implementation.suffix}\n`;
}
break;
case GrammarStyle.SLASH_COMMANDS:
if (implementation.prefix) {
content += `${implementation.prefix} ${params.content || ''}\n`;
}
break;
case GrammarStyle.API_PARAMETERS:
// Would typically be handled at API level, not string transformation
content += `[API Parameter] ${JSON.stringify(params)}\n`;
break;
case GrammarStyle.SYSTEM_PROMPTS:
// Transform to system prompt format
const operation = this.getOperationByPrimitive(primitive);
content += `System instruction for ${operation?.name || primitive}: ${params.content || ''}\n`;
break;
case GrammarStyle.FUNCTION_CALLS:
// Function call format
content += `${params.name || primitive}(${JSON.stringify(params.params || {})});\n`;
break;
case GrammarStyle.DOT_PREFIXED:
// Universal format itself
const opName = primitive.toLowerCase();
let paramsStr = '';
if (params && Object.keys(params).length > 0) {
paramsStr = JSON.stringify(params);
}
content += `.p/${opName}{${paramsStr}}\n`;
break;
case GrammarStyle.GLYPH_MARKERS:
// Find appropriate glyph
const glyphs = this.findGlyphsForPrimitive(primitive);
if (glyphs.length > 0) {
content += `${glyphs[0]} ${params.content || ''}\n`;
}
break;
// Add more cases for other grammar styles
}
}
return content;
}
/**
* Find glyphs for a symbolic primitive
*/
private findGlyphsForPrimitive(primitive: SymbolicPrimitive): string[] {
const glyphs: string[] = [];
for (const [glyph, mapping] of this.glyphMappings.entries()) {
if (mapping.primitive === primitive) {
glyphs.push(glyph);
}
}
return glyphs;
}
/**
* Extract parameters from vendor-specific symbolic content
*/
public extractParameters(content: string, primitive: SymbolicPrimitive, vendor: ModelVendor): any {
const implementation = this.getVendorImplementation(primitive, vendor);
if (!implementation) return {}; // Vendor doesn't support this primitive
switch (implementation.style) {
case GrammarStyle.XML_TAGS:
if (implementation.prefix && implementation.suffix) {
const regex = new RegExp(`${escapeRegExp(implementation.prefix)}([\\s\\S]*?)${escapeRegExp(implementation.suffix)}`);
const match = content.match(regex);
if (match) {
return { content: match[1] };
}
}
break;
case GrammarStyle.SLASH_COMMANDS:
if (implementation.prefix) {
const regex = new RegExp(`${escapeRegExp(implementation.prefix)}\\s+([\\s\\S]*)`);
const match = content.match(regex);
if (match) {
return { content: match[1] };
}
}
break;
case GrammarStyle.FUNCTION_CALLS:
const functionRegex = /(\w+)\(({[\s\S]*?})\)/;
const functionMatch = content.match(functionRegex);
if (functionMatch) {
try {
const name = functionMatch[1];
const params = JSON.parse(functionMatch[2]);
return { name, params };
} catch (error) {
return {};
}
}
break;
// Add more cases for other grammar styles
}
return {}; // Default fallback
}
/**
* Check if content contains a specific symbolic operation
*/
public containsSymbolicOperation(content: string, primitive: SymbolicPrimitive, vendor: ModelVendor): boolean {
const implementation = this.getVendorImplementation(primitive, vendor);
if (!implementation) return false; // Vendor doesn't support this primitive
switch (implementation.style) {
case GrammarStyle.XML_TAGS:
if (implementation.prefix && implementation.suffix) {
const regex = new RegExp(`${escapeRegExp(implementation.prefix)}[\\s\\S]*?${escapeRegExp(implementation.suffix)}`);
return regex.test(content);
}
break;
case GrammarStyle.SLASH_COMMANDS:
if (implementation.prefix) {
const regex = new RegExp(`${escapeRegExp(implementation.prefix)}\\s+`);
return regex.test(content);
}
break;
case GrammarStyle.FUNCTION_CALLS:
const functionRegex = /\w+\(.*?\)/;
return functionRegex.test(content);
// Add more cases for other grammar styles
}
return false; // Default fallback
}
/**
* Extract all symbolic operations from content
*/
public extractAllSymbolicOperations(content: string, vendor: ModelVendor): Array<{ primitive: SymbolicPrimitive, params: any }> {
const operations: Array<{ primitive: SymbolicPrimitive, params: any }> = [];
// Get all primitives supported by this vendor
const supportedPrimitives = this.getVendorSupportedPrimitives(vendor);
for (const primitive of supportedPrimitives) {
if (this.containsSymbolicOperation(content, primitive, vendor)) {
const params = this.extractParameters(content, primitive, vendor);
operations.push({ primitive, params });
}
}
return operations;
}
/**
* Find symbolic residue patterns in content
* These are partially formed or improperly terminated symbolic operations
*/
public findSymbolicResidue(content: string, vendor: ModelVendor): Array<{ pattern: string, position: number, possiblePrimitive?: SymbolicPrimitive }> {
const residue: Array<{ pattern: string, position: number, possiblePrimitive?: SymbolicPrimitive }> = [];
switch (vendor) {
case ModelVendor.ANTHROPIC:
// Look for unclosed XML tags
const unclosedTagRegex = /<(\w+)>(?![^<]*<\/\1>)/g;
let unclosedMatch;
while ((unclosedMatch = unclosedTagRegex.exec(content)) !== null) {
const tag = unclosedMatch[1];
const primitive = this.getPrimitiveByTag(tag, vendor);
residue.push({
pattern: unclosedMatch[0],
position: unclosedMatch.index,
possiblePrimitive: primitive
});
}
break;
case ModelVendor.QWEN:
case ModelVendor.OPENAI:
// Look for slash commands without content
const incompleteSlashRegex = /\/(\w+)$/g;
let incompleteSlashMatch;
while ((incompleteSlashMatch = incompleteSlashRegex.exec(content)) !== null) {
const slash = incompleteSlashMatch[1];
const primitive = this.getPrimitiveBySlash(slash, vendor);
residue.push({
pattern: incompleteSlashMatch[0],
position: incompleteSlashMatch.index,
possiblePrimitive: primitive
});
}
break;
// Add cases for other vendors
}
// Look for orphaned glyphs
for (const [glyph, mapping] of this.glyphMappings.entries()) {
const glyphRegex = new RegExp(escapeRegExp(glyph), 'g');
let glyphMatch;
while ((glyphMatch = glyphRegex.exec(content)) !== null) {
// Check if this is an isolated glyph (not part of another construct)
const isIsolated = (
(glyphMatch.index === 0 || /\s/.test(content[glyphMatch.index - 1])) &&
(glyphMatch.index + glyph.length === content.length || /\s/.test(content[glyphMatch.index + glyph.length]))
);
if (isIsolated) {
residue.push({
pattern: glyph,
position: glyphMatch.index,
possiblePrimitive: mapping.primitive
});
}
}
}
return residue;
}
/**
* Repair symbolic residue in content
*/
public repairSymbolicResidue(content: string, vendor: ModelVendor): string {
let repairedContent = content;
// Find residue
const residuePatterns = this.findSymbolicResidue(content, vendor);
// Sort by position in reverse to avoid index shifting
residuePatterns.sort((a, b) => b.position - a.position);
for (const residue of residuePatterns) {
if (!residue.possiblePrimitive) continue;
const implementation = this.getVendorImplementation(residue.possiblePrimitive, vendor);
if (!implementation) continue;
switch (implementation.style) {
case GrammarStyle.XML_TAGS:
if (implementation.prefix && implementation.suffix) {
// If we have an open tag without a close tag
if (residue.pattern.startsWith(implementation.prefix)) {
repairedContent =
repairedContent.substring(0, residue.position) +
residue.pattern + '[MISSING CONTENT]' + implementation.suffix +
repairedContent.substring(residue.position + residue.pattern.length);
}
}
break;
case GrammarStyle.SLASH_COMMANDS:
// If we have a slash command without content
if (residue.pattern.startsWith('/')) {
repairedContent =
repairedContent.substring(0, residue.position) +
residue.pattern + ' [MISSING CONTENT]' +
repairedContent.substring(residue.position + residue.pattern.length);
}
break;
// Add more cases for other grammar styles
}
}
return repairedContent;
}
/**
* Clean symbolic traces from content
*/
public cleanSymbolicTraces(content: string, vendor: ModelVendor): string {
let cleanedContent = content;
// List of primitives to clean
const primitivesToClean = [
SymbolicPrimitive.THINKING,
SymbolicPrimitive.REFLECTION,
// Add more as needed
];
for (const primitive of primitivesToClean) {
const implementation = this.getVendorImplementation(primitive, vendor);
if (!implementation) continue;
switch (implementation.style) {
case GrammarStyle.XML_TAGS:
if (implementation.prefix && implementation.suffix) {
const regex = new RegExp(`${escapeRegExp(implementation.prefix)}[\\s\\S]*?${escapeRegExp(implementation.suffix)}`, 'g');
cleanedContent = cleanedContent.replace(regex, '');
}
break;
case GrammarStyle.SLASH_COMMANDS:
if (implementation.prefix) {
const regex = new RegExp(`${escapeRegExp(implementation.prefix)}\\s+[^\\n]*\\n?`, 'g');
cleanedContent = cleanedContent.replace(regex, '');
}
break;
// Add more cases for other grammar styles
}
}
// Clean orphaned glyphs
for (const [glyph, mapping] of this.glyphMappings.entries()) {
if (primitivesToClean.includes(mapping.primitive)) {
const glyphRegex = new RegExp(`${escapeRegExp(glyph)}\\s+[^\\n]*\\n?`, 'g');
cleanedContent = cleanedContent.replace(glyphRegex, '');
}
}
return cleanedContent.trim();
}
/**
* Get information about a vendor's symbolic capabilities
*/
public getVendorCapabilitiesInfo(vendor: ModelVendor): {
supported: SymbolicPrimitive[];
emulated: SymbolicPrimitive[];
unsupported: SymbolicPrimitive[];
grammarStyle: GrammarStyle[];
} {
const supported: SymbolicPrimitive[] = [];
const emulated: SymbolicPrimitive[] = [];
const unsupported: SymbolicPrimitive[] = [];
const grammarStyle = new Set<GrammarStyle>();
// Check all primitives
for (const operation of SYMBOLIC_RUNTIME_SCHEMA) {
const implementation = operation.vendorImplementations.find(impl => impl.vendor === vendor);
if (implementation) {
grammarStyle.add(implementation.style);
if (implementation.isNative) {
supported.push(operation.type);
} else {
emulated.push(operation.type);
}
} else {
unsupported.push(operation.type);
}
}
return {
supported,
emulated,
unsupported,
grammarStyle: Array.from(grammarStyle)
};
}
/**
* Get compatibility matrix for all primitives across all vendors
*/
public getCompatibilityMatrix(): Record<SymbolicPrimitive, Record<ModelVendor, 'native' | 'emulated' | 'unsupported'>> {
const matrix: Record<SymbolicPrimitive, Record<ModelVendor, 'native' | 'emulated' | 'unsupported'>> = {} as any;
// Initialize matrix
for (const primitive of Object.values(SymbolicPrimitive)) {
matrix[primitive] = {} as Record<ModelVendor, 'native' | 'emulated' | 'unsupported'>;
for (const vendor of Object.values(ModelVendor)) {
matrix[primitive][vendor] = 'unsupported';
}
}
// Fill in matrix
for (const operation of SYMBOLIC_RUNTIME_SCHEMA) {
for (const implementation of operation.vendorImplementations) {
if (implementation.isNative) {
matrix[operation.type][implementation.vendor] = 'native';
} else {
matrix[operation.type][implementation.vendor] = 'emulated';
}
}
}
return matrix;
}
/**
* Get symbolic mapping table for all primitives across all vendors
*/
public getSymbolicMappingTable(): Record<SymbolicPrimitive, Record<ModelVendor, string>> {
const table: Record<SymbolicPrimitive, Record<ModelVendor, string>> = {} as any;
// Initialize table
for (const primitive of Object.values(SymbolicPrimitive)) {
table[primitive] = {} as Record<ModelVendor, string>;
for (const vendor of Object.values(ModelVendor)) {
table[primitive][vendor] = 'N/A';
}
}
// Fill in table
for (const operation of SYMBOLIC_RUNTIME_SCHEMA) {
// Always set universal format
table[operation.type][ModelVendor.UNIVERSAL] = operation.universalSyntax;
for (const implementation of operation.vendorImplementations) {
table[operation.type][implementation.vendor] = implementation.exampleSyntax;
}
}
return table;
}
/**
* Export registry data for documentation or debugging
*/
public exportRegistryData(): any {
return {
glyphMappings: Array.from(this.glyphMappings.values()),
tagMappings: Array.from(this.tagMappings.values()),
slashMappings: Array.from(this.slashMappings.values()),
dotMappings: Array.from(this.dotMappings.values()),
operatorMappings: Array.from(this.operatorMappings.values()),
vendorCapabilities: Array.from(this.vendorCapabilities.entries()).map(([vendor, capabilities]) => ({
vendor,
capabilities: Array.from(capabilities)
})),
customSymbols: Array.from(this.customSymbols.values()),
compatibilityMatrix: this.getCompatibilityMatrix(),
mappingTable: this.getSymbolicMappingTable()
};
}
}
/**
* Helper function to escape special characters in regex
*/
function escapeRegExp(string: string): string {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
|