Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 | 1x 1x 1x 1x | /**
* Workspace API Handlers
*
* Handles workspace operations like listing, mounting, and getting details.
* TODO: These handlers need full implementation once WorkspaceService is migrated.
*/
import type { AppContainer } from '../../config/container.js';
import { SiteService } from '../../services/site/site-service.js';
import fs from 'fs-extra';
import { globSync } from 'glob';
import path from 'path';
import matter from 'gray-matter';
import { createWorkspaceServiceForParams, getCurrentWorkspaceService } from './helpers/workspace-helper.js';
import { processPromptTemplate, buildSelfObject, buildPageSelfObject, buildFieldSelfObject, buildParentPageObject } from '../../utils/prompt-template-processor.js';
import { callLLM, getProviderDisplayName } from '../../utils/llm-service.js';
import { type WorkspaceConfig, type CollectionConfig, type SingleConfig, type MergeableConfigItem, type Field, promptItemConfigSchema, readonlyFieldSchema } from '@quiqr/types';
/**
* Helper function to find a template file with either .yaml or .yml extension
* @param basePath - The directory containing the template
* @param templateKey - The template key (filename without extension)
* @returns The full path to the template file, or null if not found
*/
function findTemplateFile(basePath: string, templateKey: string): string | null {
const yamlPath = path.join(basePath, `${templateKey}.yaml`);
const ymlPath = path.join(basePath, `${templateKey}.yml`);
if (fs.existsSync(yamlPath)) {
return yamlPath;
}
if (fs.existsSync(ymlPath)) {
return ymlPath;
}
return null;
}
/**
* List all workspaces for a site
*/
export function createListWorkspacesHandler(container: AppContainer) {
return async ({ siteKey }: { siteKey: string }) => {
// Get site configuration
const siteConfig = await container.libraryService.getSiteConf(siteKey);
// Create SiteService instance
const siteService = new SiteService(
siteConfig,
container.siteSourceFactory,
container.syncFactory
);
// List workspaces
return await siteService.listWorkspaces();
};
}
/**
* Get workspace details and configuration
*/
export function createGetWorkspaceDetailsHandler(container: AppContainer) {
return async ({ siteKey, workspaceKey }: { siteKey: string; workspaceKey: string }) => {
// Use the container's getWorkspaceService which handles caching and model watcher setup
const workspaceService = await container.getWorkspaceService(siteKey, workspaceKey);
// Get configuration - delegates to WorkspaceService
const config = await workspaceService.getConfigurationsData();
// Get workspace path for state update
const workspacePath = workspaceService.getWorkspacePath();
// Update state - delegates to AppState
container.state.setCurrentSite(siteKey, workspaceKey, workspacePath);
// Save last opened - delegates to UnifiedConfigService
await container.unifiedConfig.setUserState('lastOpenedSite', {
siteKey,
workspaceKey,
sitePath: workspacePath,
});
// Update menu to reflect that a site is now selected
container.adapters.menu.createMainMenu();
return config;
};
}
/**
* Mount a workspace (make it active)
*/
export function createMountWorkspaceHandler(container: AppContainer) {
return async ({
siteKey,
workspaceKey,
}: {
siteKey: string;
workspaceKey: string;
}) => {
// Get site configuration
const siteConfig = await container.libraryService.getSiteConf(siteKey);
// Create SiteService instance
const siteService = new SiteService(
siteConfig,
container.siteSourceFactory,
container.syncFactory
);
// Mount the workspace
await siteService.mountWorkspace(workspaceKey);
// Get the workspace head to find the path
const workspaceHead = await siteService.getWorkspaceHead(workspaceKey);
// Update container state (similar to old backend's global state)
container.state.currentSiteKey = siteKey;
container.state.currentWorkspaceKey = workspaceKey;
container.state.currentSitePath = workspaceHead?.path || '';
// Save last opened site to config
await container.unifiedConfig.setUserState('lastOpenedSite', {
siteKey,
workspaceKey,
sitePath: workspaceHead?.path || null,
});
// Update menu to reflect that a site is now selected
container.adapters.menu.createMainMenu();
// Return workspace path as string (matches frontend schema)
return workspaceHead?.path || '';
};
}
/**
* Get workspace model parse information
*/
export function createGetWorkspaceModelParseInfoHandler(container: AppContainer) {
return async ({
siteKey,
workspaceKey,
}: {
siteKey: string;
workspaceKey: string;
}) => {
const workspaceService = await createWorkspaceServiceForParams(
container,
siteKey,
workspaceKey
);
return await workspaceService.getModelParseInfo();
};
}
/**
* Get creator message for a workspace
*/
export function createGetCreatorMessageHandler(container: AppContainer) {
return async ({
siteKey,
workspaceKey,
}: {
siteKey: string;
workspaceKey: string;
}) => {
const workspaceService = await createWorkspaceServiceForParams(
container,
siteKey,
workspaceKey
);
return await workspaceService.getCreatorMessage();
};
}
/**
* Get languages from Hugo config
*/
export function createGetLanguagesHandler(container: AppContainer) {
return async ({
siteKey,
workspaceKey,
}: {
siteKey: string;
workspaceKey: string;
}) => {
const workspaceService = await createWorkspaceServiceForParams(
container,
siteKey,
workspaceKey
);
return await workspaceService.getHugoConfigLanguages();
};
}
/**
* Get files from an absolute path
*/
export function createGetFilesFromAbsolutePathHandler(container: AppContainer) {
return async ({ path }: { path: string }) => {
const workspaceService = getCurrentWorkspaceService(container);
return await workspaceService.getFilesFromAbsolutePath(path);
};
}
/**
* Keys in WorkspaceConfig that contain searchable arrays of config items
*/
type DynFormArrayKey = 'collections' | 'singles' | 'dynamics';
/**
* Union of all config item types that can be searched
*/
type DynFormConfigItem = CollectionConfig | SingleConfig | MergeableConfigItem;
/**
* Type guard to check if a key is a valid array property in WorkspaceConfig
*/
function isDynFormArrayKey(
config: WorkspaceConfig,
key: string
): key is DynFormArrayKey {
return (
(key === 'collections' || key === 'singles' || key === 'dynamics') &&
key in config
);
}
/**
* Get a property value from a config item by dynamic key
* This is needed because config item types don't have index signatures
*/
function getConfigItemProperty(
item: DynFormConfigItem,
key: string
): unknown {
// All config items are plain objects, safe to access by key
return (item as Record<string, unknown>)[key];
}
/**
* Get dynamic form fields
*/
export function createGetDynFormFieldsHandler(container: AppContainer) {
return async ({
searchRootNode,
searchLevelKeyVal,
}: {
searchRootNode: string;
searchLevelKeyVal: { key: string; val: string };
}): Promise<DynFormConfigItem | null> => {
const workspaceService = getCurrentWorkspaceService(container);
const configuration = await workspaceService.getConfigurationsData();
if (!isDynFormArrayKey(configuration, searchRootNode)) {
return null;
}
const configArray = configuration[searchRootNode];
if (!configArray) {
return null;
}
const dynConf = configArray.find(
(item) => getConfigItemProperty(item, searchLevelKeyVal.key) === searchLevelKeyVal.val
);
return dynConf ?? null;
};
}
/**
* Type guard to check if a value is a Field with a matching key
*/
function isFieldWithKey(value: unknown, key: string): value is Field {
return (
typeof value === 'object' &&
value !== null &&
'key' in value &&
value.key === key
);
}
/**
* Get value by config path
*/
export function createGetValueByConfigPathHandler(container: AppContainer) {
return async ({
searchRootNode,
path,
}: {
searchRootNode: string;
path: string;
}): Promise<Field | null> => {
const workspaceService = getCurrentWorkspaceService(container);
const configuration = await workspaceService.getConfigurationsData();
if (!isDynFormArrayKey(configuration, searchRootNode)) {
return null;
}
const configArray = configuration[searchRootNode];
if (!configArray) {
return null;
}
const confObj = configArray.find((item) => item.key === 'mainConfig');
if (!confObj) {
return null;
}
const fields = getConfigItemProperty(confObj, 'fields');
if (!Array.isArray(fields)) {
return null;
}
const value = fields.find((field) => isFieldWithKey(field, path));
return value ?? null;
};
}
/**
* Get preview check configuration
*/
export function createGetPreviewCheckConfigurationHandler(container: AppContainer) {
return async () => {
const { state } = container;
if (!state.currentSitePath) {
throw new Error('No workspace is currently mounted');
}
const filePath = path.join(state.currentSitePath, 'quiqr', 'previewchecksettings.json');
if (!fs.existsSync(filePath)) {
return null;
}
try {
const strData = await fs.readFile(filePath, { encoding: 'utf-8' });
const formatProvider = container.formatResolver.resolveForFilePath(filePath);
if (!formatProvider) {
throw new Error(`Could not resolve a format provider for file ${filePath}.`);
}
const obj = formatProvider.parse(strData);
return obj;
} catch (e) {
console.error('Error reading preview check configuration:', e);
return null;
}
};
}
/**
* Parse a file to an object (file path is relative to current workspace)
*/
export function createParseFileToObjectHandler(container: AppContainer) {
return async ({ file }: { file: string }) => {
const { state } = container;
// Resolve file path relative to current workspace if not absolute
const filePath = path.isAbsolute(file)
? file
: path.join(state.currentSitePath || process.cwd(), file);
// Read the file contents
const fileContent = await fs.readFile(filePath, 'utf-8');
// Resolve the format provider based on file extension
const formatProvider = container.formatResolver.resolveForFilePath(filePath);
if (!formatProvider) {
throw new Error(`Unsupported file format for file: ${filePath}`);
}
// Parse the file content
const parsed = formatProvider.parse(fileContent);
return parsed;
};
}
/**
* Run a glob pattern sync relative to the current workspace
*/
export function createGlobSyncHandler(container: AppContainer) {
return async ({
pattern,
options,
}: {
pattern: string;
options?: string[];
}) => {
const { state } = container;
// Use the current workspace path as the cwd if available
const cwd = state.currentSitePath || process.cwd();
// Run glob pattern with workspace as cwd
const matches = globSync(pattern, { ...options, cwd });
return matches;
};
}
/**
* Check if a Hugo version is installed
* @deprecated Use createCheckSSGVersionHandler instead
*/
export function createCheckHugoVersionHandler(container: AppContainer) {
return async ({ version }: { version: string }) => {
const installed = container.hugoDownloader.isVersionInstalled(version);
return { installed, version };
};
}
/**
* Check if an SSG version is installed
*/
export function createCheckSSGVersionHandler(container: AppContainer) {
return async ({ ssgType, version }: { ssgType: string; version: string }) => {
const provider = await container.providerFactory.getProvider(ssgType);
const binaryManager = provider.getBinaryManager();
if (!binaryManager) {
// If no binary manager, consider it "installed" (doesn't require installation)
return { installed: true, version, ssgType };
}
const installed = binaryManager.isVersionInstalled(version);
return { installed, version, ssgType };
};
}
/**
* Get prompt template configuration by key
* Loads and parses the YAML file from quiqr/model/includes/page_prompt_templates/{templateKey}.yaml
* Falls back to old prompts_templates/ directory if new one doesn't exist
*/
export function createGetPromptTemplateConfigHandler(container: AppContainer) {
return async ({
siteKey,
workspaceKey,
templateKey,
}: {
siteKey: string;
workspaceKey: string;
templateKey: string;
}) => {
// Get the workspace path
const siteConfig = await container.libraryService.getSiteConf(siteKey);
const siteService = new SiteService(
siteConfig,
container.siteSourceFactory,
container.syncFactory
);
const workspace = await siteService.getWorkspaceHead(workspaceKey);
if (!workspace) {
throw new Error('Workspace not found');
}
const baseIncludePath = path.join(workspace.path, 'quiqr', 'model', 'includes');
// Try new directory first, then fall back to old directory
let templatePath = findTemplateFile(
path.join(baseIncludePath, 'page_prompt_templates'),
templateKey
);
let usingFallback = false;
if (!templatePath) {
// Try old directory
const oldTemplatePath = findTemplateFile(
path.join(baseIncludePath, 'prompts_templates'),
templateKey
);
if (oldTemplatePath) {
templatePath = oldTemplatePath;
usingFallback = true;
console.warn(
`⚠️ Using deprecated 'prompts_templates/' directory. Please rename to 'page_prompt_templates/' for page-level templates.`
);
}
}
// Check if the file exists
if (!templatePath) {
throw new Error(`Prompt template not found: ${templateKey}`);
}
// Read and parse the file
const fileContent = await fs.readFile(templatePath, 'utf-8');
const formatProvider = container.formatResolver.resolveForFilePath(templatePath);
if (!formatProvider) {
throw new Error(`Unsupported file format for prompt template: ${templatePath}`);
}
const parsed = formatProvider.parse(fileContent);
console.log(parsed)
return parsed;
};
}
/**
* Process AI prompt with variable replacement
* Takes form values and current file context, processes the prompt template
*/
export function createProcessAiPromptHandler(container: AppContainer) {
return async ({
siteKey,
workspaceKey,
templateKey,
formValues,
context,
}: {
siteKey: string;
workspaceKey: string;
templateKey: string;
formValues: Record<string, unknown>;
context: {
collectionKey?: string;
collectionItemKey?: string;
singleKey?: string;
};
}) => {
// Get workspace service and path
const workspaceService = await createWorkspaceServiceForParams(
container,
siteKey,
workspaceKey
);
const siteConfig = await container.libraryService.getSiteConf(siteKey);
const siteService = new SiteService(
siteConfig,
container.siteSourceFactory,
container.syncFactory
);
const workspace = await siteService.getWorkspaceHead(workspaceKey);
if (!workspace) {
throw new Error('Workspace not found');
}
const workspacePath = workspace.path;
const baseIncludePath = path.join(workspacePath, 'quiqr', 'model', 'includes');
// Try new directory first, then fall back to old directory
let templatePath = findTemplateFile(
path.join(baseIncludePath, 'page_prompt_templates'),
templateKey
);
if (!templatePath) {
// Try old directory
const oldTemplatePath = findTemplateFile(
path.join(baseIncludePath, 'prompts_templates'),
templateKey
);
if (oldTemplatePath) {
templatePath = oldTemplatePath;
console.warn(
`⚠️ Using deprecated 'prompts_templates/' directory. Please rename to 'page_prompt_templates/' for page-level templates.`
);
}
}
if (!templatePath) {
throw new Error(`Prompt template not found: ${templateKey}`);
}
const fileContent = await fs.readFile(templatePath, 'utf-8');
const formatProvider = container.formatResolver.resolveForFilePath(templatePath);
if (!formatProvider) {
throw new Error(`Unsupported file format for prompt template: ${templatePath}`);
}
const rawConfig = formatProvider.parse(fileContent);
const validationResult = promptItemConfigSchema.safeParse(rawConfig);
let templateConfig;
if (validationResult.success) {
templateConfig = validationResult.data
} else {
throw new Error('Schema validation failed: ' + validationResult.error)
}
// Build self object if we have context
let selfObject = null;
if (context.singleKey || context.collectionItemKey) {
try {
const config = await workspaceService.getConfigurationsData();
let filePath = '';
if (context.singleKey) {
// Get file path for single
const single = config.singles.find((x) => x.key === context.singleKey);
if (single && single.file) {
filePath = single.file;
}
} else if (context.collectionItemKey && context.collectionKey) {
// Get file path for collection item
const collection = config.collections.find((x) => x.key === context.collectionKey);
if (collection) {
filePath = path.join(collection.folder, context.collectionItemKey);
}
}
if (filePath) {
selfObject = await buildPageSelfObject(workspacePath, filePath);
}
} catch (error) {
console.error('Failed to build self object:', error);
// Continue without self object
}
}
// Find the prompt template text (usually in a readonly field named 'promptTemplate')
let templateText = '';
if (templateConfig.fields) {
const templateField = templateConfig.fields.find(
(f: Field) => f.type === 'readonly' && f.key === 'promptTemplate'
);
const validationResult = readonlyFieldSchema.safeParse(templateField)
if (validationResult.data && validationResult.data.default) {
templateText = validationResult.data.default;
}
}
if (!templateText) {
throw new Error('No prompt template text found in configuration');
}
// Process the template with variable replacement
const finalPrompt = await processPromptTemplate(templateText, {
self: selfObject,
field: formValues,
workspacePath,
contextType: 'page',
});
// Log the prompt to console
console.log('\n=== AI ASSIST PROMPT ===');
console.log('Template:', templateKey);
console.log('LLM Settings:', JSON.stringify(templateConfig.llm_settings, null, 2));
console.log('\n--- Final Prompt ---');
console.log(finalPrompt);
console.log('\n--- Calling LLM ---');
// Call the LLM
try {
const llmResponse = await callLLM({
model: templateConfig.llm_settings.model,
prompt: finalPrompt,
temperature: templateConfig.llm_settings.temperature,
maxTokens: 4096,
});
// Log the response
console.log('\n--- LLM Response ---');
console.log(llmResponse.text);
if (llmResponse.usage) {
console.log('\n--- Usage Stats ---');
console.log(`Prompt tokens: ${llmResponse.usage.promptTokens}`);
console.log(`Completion tokens: ${llmResponse.usage.completionTokens}`);
console.log(`Total tokens: ${llmResponse.usage.totalTokens}`);
}
console.log('\n======================\n');
// Return both prompt and response
return {
status: 'ok',
prompt: finalPrompt,
response: llmResponse.text,
llm_settings: templateConfig.llm_settings,
usage: llmResponse.usage,
provider: getProviderDisplayName(llmResponse.provider),
};
} catch (error: unknown) {
if (error instanceof Error) {
console.error('\n--- LLM Error ---');
console.error(error.message);
console.log('\n======================\n');
// Re-throw with context
throw new Error(`Failed to process AI prompt: ${error.message}`);
}
const msg =
typeof error === "string"
? error
: "Failed to process AI prompt";
throw new Error(msg);
}
};
}
/**
* Update page content from AI response
* Parses the AI response (markdown with frontmatter) and updates the Single or CollectionItem
*/
export function createUpdatePageFromAiResponseHandler(container: AppContainer) {
return async ({
siteKey,
workspaceKey,
aiResponse,
context,
}: {
siteKey: string;
workspaceKey: string;
aiResponse: string;
context: {
collectionKey?: string;
collectionItemKey?: string;
singleKey?: string;
};
}) => {
// Get workspace service
const workspaceService = await createWorkspaceServiceForParams(
container,
siteKey,
workspaceKey
);
// Parse the AI response with gray-matter
const parsed = matter(aiResponse);
const frontmatter = parsed.data;
const content = parsed.content;
// Create document object
const document = {
...frontmatter,
mainContent: content,
};
console.log('Updating page with AI response:', {
singleKey: context.singleKey,
collectionKey: context.collectionKey,
collectionItemKey: context.collectionItemKey,
frontmatterKeys: Object.keys(frontmatter),
contentLength: content.length,
});
// Update based on context
if (context.singleKey) {
await workspaceService.updateSingle(context.singleKey, document);
return { success: true, type: 'single' };
} else if (context.collectionKey && context.collectionItemKey) {
await workspaceService.updateCollectionItem(
context.collectionKey,
context.collectionItemKey,
document
);
return { success: true, type: 'collection' };
} else {
throw new Error('No valid context for updating (missing singleKey or collectionKey)');
}
};
}
/**
* Get field prompt template configuration by key
* Loads and parses the YAML file from quiqr/model/includes/field_prompt_templates/{templateKey}.yaml
*/
export function createGetFieldPromptTemplateConfigHandler(container: AppContainer) {
return async ({
siteKey,
workspaceKey,
templateKey,
}: {
siteKey: string;
workspaceKey: string;
templateKey: string;
}) => {
// Get the workspace path
const siteConfig = await container.libraryService.getSiteConf(siteKey);
const siteService = new SiteService(
siteConfig,
container.siteSourceFactory,
container.syncFactory
);
const workspace = await siteService.getWorkspaceHead(workspaceKey);
if (!workspace) {
throw new Error('Workspace not found');
}
// Construct the path to the field prompt template file
const templatePath = findTemplateFile(
path.join(workspace.path, 'quiqr', 'model', 'includes', 'field_prompt_templates'),
templateKey
);
// Check if the file exists
if (!templatePath) {
throw new Error(`Field prompt template not found: ${templateKey}`);
}
// Read and parse the file
const fileContent = await fs.readFile(templatePath, 'utf-8');
const formatProvider = container.formatResolver.resolveForFilePath(templatePath);
if (!formatProvider) {
throw new Error(`Unsupported file format for field prompt template: ${templatePath}`);
}
const rawConfig = formatProvider.parse(fileContent);
// Validate the schema
const validationResult = promptItemConfigSchema.safeParse(rawConfig);
if (!validationResult.success) {
throw new Error(
`Field prompt template validation failed: ${validationResult.error.message}`
);
}
// Return the validated configuration
return validationResult.data;
};
}
/**
* Process field AI prompt
* Similar to page AI prompt but works with field context
*/
export function createProcessFieldAiPromptHandler(container: AppContainer) {
return async ({
siteKey,
workspaceKey,
templateKey,
formValues,
fieldContext,
}: {
siteKey: string;
workspaceKey: string;
templateKey: string;
formValues: Record<string, unknown>;
fieldContext: {
fieldKey: string;
fieldType: string;
fieldContent: string;
collectionKey?: string;
collectionItemKey?: string;
singleKey?: string;
};
}) => {
// Get workspace service and path
const workspaceService = await createWorkspaceServiceForParams(
container,
siteKey,
workspaceKey
);
const siteConfig = await container.libraryService.getSiteConf(siteKey);
const siteService = new SiteService(
siteConfig,
container.siteSourceFactory,
container.syncFactory
);
const workspace = await siteService.getWorkspaceHead(workspaceKey);
if (!workspace) {
throw new Error('Workspace not found');
}
const workspacePath = workspace.path;
// Load the field prompt template configuration
const templatePath = findTemplateFile(
path.join(workspacePath, 'quiqr', 'model', 'includes', 'field_prompt_templates'),
templateKey
);
if (!templatePath) {
throw new Error(`Field prompt template not found: ${templateKey}`);
}
const fileContent = await fs.readFile(templatePath, 'utf-8');
const formatProvider = container.formatResolver.resolveForFilePath(templatePath);
if (!formatProvider) {
throw new Error(`Unsupported file format for field prompt template: ${templatePath}`);
}
const rawConfig = formatProvider.parse(fileContent);
const validationResult = promptItemConfigSchema.safeParse(rawConfig);
let templateConfig;
if (validationResult.success) {
templateConfig = validationResult.data;
} else {
throw new Error('Schema validation failed: ' + validationResult.error);
}
// Build field self object
const fieldSelfObject = buildFieldSelfObject(
fieldContext.fieldKey,
fieldContext.fieldType,
fieldContext.fieldContent
);
// Build parent page object if we have context
let parentPageObject = null;
if (fieldContext.singleKey || fieldContext.collectionItemKey) {
try {
const config = await workspaceService.getConfigurationsData();
let filePath = '';
if (fieldContext.singleKey) {
// Get file path for single
const single = config.singles.find((x) => x.key === fieldContext.singleKey);
if (single && single.file) {
filePath = single.file;
}
} else if (fieldContext.collectionItemKey && fieldContext.collectionKey) {
// Get file path for collection item
const collection = config.collections.find(
(x) => x.key === fieldContext.collectionKey
);
if (collection) {
filePath = path.join(collection.folder, fieldContext.collectionItemKey);
}
}
if (filePath) {
parentPageObject = await buildParentPageObject(workspacePath, filePath);
}
} catch (error) {
console.error('Failed to build parent page object:', error);
// Continue without parent page object
}
}
// Find the prompt template text
let templateText = '';
if (templateConfig.fields) {
const templateField = templateConfig.fields.find(
(f: Field) => f.type === 'readonly' && f.key === 'promptTemplate'
);
const validationResult = readonlyFieldSchema.safeParse(templateField);
if (validationResult.data && validationResult.data.default) {
templateText = validationResult.data.default;
}
}
if (!templateText) {
throw new Error('No prompt template text found in configuration');
}
// Process the template with field variable context
const finalPrompt = await processPromptTemplate(templateText, {
self: fieldSelfObject,
parent_page: parentPageObject,
field: formValues,
workspacePath,
contextType: 'field',
});
// Log the prompt to console
console.log('\n=== FIELD AI ASSIST PROMPT ===');
console.log('Template:', templateKey);
console.log('Field:', fieldContext.fieldKey, `(${fieldContext.fieldType})`);
console.log('LLM Settings:', JSON.stringify(templateConfig.llm_settings, null, 2));
console.log('\n--- Final Prompt ---');
console.log(finalPrompt);
console.log('\n--- Calling LLM ---');
// Call the LLM
try {
const llmResponse = await callLLM({
model: templateConfig.llm_settings.model,
prompt: finalPrompt,
temperature: templateConfig.llm_settings.temperature,
maxTokens: 4096,
});
// Log the response
console.log('\n--- LLM Response ---');
console.log(llmResponse.text);
if (llmResponse.usage) {
console.log('\n--- Usage Stats ---');
console.log(`Prompt tokens: ${llmResponse.usage.promptTokens}`);
console.log(`Completion tokens: ${llmResponse.usage.completionTokens}`);
console.log(`Total tokens: ${llmResponse.usage.totalTokens}`);
}
console.log('\n============================\n');
// Return both prompt and response
return {
status: 'ok',
prompt: finalPrompt,
response: llmResponse.text,
llm_settings: templateConfig.llm_settings,
usage: llmResponse.usage || null,
};
} catch (error) {
console.error('LLM call failed:', error);
throw new Error(`Failed to generate AI response: ${(error as Error).message}`);
}
};
}
/**
* Create all workspace-related handlers
*/
export function createWorkspaceHandlers(container: AppContainer) {
return {
listWorkspaces: createListWorkspacesHandler(container),
getWorkspaceDetails: createGetWorkspaceDetailsHandler(container),
mountWorkspace: createMountWorkspaceHandler(container),
getWorkspaceModelParseInfo: createGetWorkspaceModelParseInfoHandler(container),
getCreatorMessage: createGetCreatorMessageHandler(container),
getLanguages: createGetLanguagesHandler(container),
getFilesFromAbsolutePath: createGetFilesFromAbsolutePathHandler(container),
getDynFormFields: createGetDynFormFieldsHandler(container),
getValueByConfigPath: createGetValueByConfigPathHandler(container),
getPreviewCheckConfiguration: createGetPreviewCheckConfigurationHandler(container),
parseFileToObject: createParseFileToObjectHandler(container),
globSync: createGlobSyncHandler(container),
checkHugoVersion: createCheckHugoVersionHandler(container),
checkSSGVersion: createCheckSSGVersionHandler(container),
getPromptTemplateConfig: createGetPromptTemplateConfigHandler(container),
processAiPrompt: createProcessAiPromptHandler(container),
updatePageFromAiResponse: createUpdatePageFromAiResponseHandler(container),
getFieldPromptTemplateConfig: createGetFieldPromptTemplateConfigHandler(container),
processFieldAiPrompt: createProcessFieldAiPromptHandler(container),
};
}
|