farseer-cli 1.10.3 → 1.11.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.
Files changed (78) hide show
  1. package/README.md +5 -0
  2. package/dist/commands/app.js +15 -12
  3. package/dist/commands/app.js.map +2 -2
  4. package/dist/commands/apps.js +3 -3
  5. package/dist/commands/apps.js.map +2 -2
  6. package/dist/commands/cells.js +3 -3
  7. package/dist/commands/cells.js.map +2 -2
  8. package/dist/commands/config.js +23 -15
  9. package/dist/commands/config.js.map +2 -2
  10. package/dist/commands/dashboards.js +3 -3
  11. package/dist/commands/dashboards.js.map +2 -2
  12. package/dist/commands/dimensions.js +3 -3
  13. package/dist/commands/dimensions.js.map +2 -2
  14. package/dist/commands/files.js +5 -4
  15. package/dist/commands/files.js.map +2 -2
  16. package/dist/commands/formula.js +3 -3
  17. package/dist/commands/formula.js.map +2 -2
  18. package/dist/commands/list.js +5 -4
  19. package/dist/commands/list.js.map +2 -2
  20. package/dist/commands/login.js +6 -5
  21. package/dist/commands/login.js.map +2 -2
  22. package/dist/commands/model.js +5 -4
  23. package/dist/commands/model.js.map +2 -2
  24. package/dist/commands/push.js +5 -7
  25. package/dist/commands/push.js.map +2 -2
  26. package/dist/commands/run.js +3 -3
  27. package/dist/commands/run.js.map +2 -2
  28. package/dist/commands/sheets.js +3 -3
  29. package/dist/commands/sheets.js.map +2 -2
  30. package/dist/commands/variables.js +5 -4
  31. package/dist/commands/variables.js.map +2 -2
  32. package/dist/mcp/index.js +1 -1
  33. package/dist/mcp/index.js.map +2 -2
  34. package/dist/mcp/tools/appTools.js +3 -3
  35. package/dist/mcp/tools/appTools.js.map +2 -2
  36. package/dist/mcp/tools/dataTools.js +5 -2
  37. package/dist/mcp/tools/dataTools.js.map +2 -2
  38. package/dist/mcp/tools/modelTools.js +45 -48
  39. package/dist/mcp/tools/modelTools.js.map +2 -2
  40. package/dist/mcp/utils/session.js +2 -2
  41. package/dist/mcp/utils/session.js.map +2 -2
  42. package/dist/services/appSyncService.js.map +1 -1
  43. package/dist/services/apps.js +149 -0
  44. package/dist/services/apps.js.map +7 -0
  45. package/dist/services/authErrors.js +77 -0
  46. package/dist/services/authErrors.js.map +7 -0
  47. package/dist/services/configService.js +7 -4
  48. package/dist/services/configService.js.map +2 -2
  49. package/dist/services/credentials.js +87 -0
  50. package/dist/services/credentials.js.map +7 -0
  51. package/dist/services/farseerService.js +247 -112
  52. package/dist/services/farseerService.js.map +2 -2
  53. package/dist/services/httpError.js +35 -0
  54. package/dist/services/httpError.js.map +7 -0
  55. package/dist/services/modelExport.js +63 -0
  56. package/dist/services/modelExport.js.map +7 -0
  57. package/dist/services/organisation.js +88 -0
  58. package/dist/services/organisation.js.map +7 -0
  59. package/dist/services/preflight.js +10 -13
  60. package/dist/services/preflight.js.map +2 -2
  61. package/dist/services/syncService.js +2 -2
  62. package/dist/services/syncService.js.map +2 -2
  63. package/dist/utils/constants.js +2 -5
  64. package/dist/utils/constants.js.map +2 -2
  65. package/dist/utils/fileLogger.js +24 -1
  66. package/dist/utils/fileLogger.js.map +2 -2
  67. package/dist/utils/folderMatch.js +49 -0
  68. package/dist/utils/folderMatch.js.map +7 -0
  69. package/dist/utils/helpers.js +26 -0
  70. package/dist/utils/helpers.js.map +2 -2
  71. package/dist/utils/syncScope.js +44 -0
  72. package/dist/utils/syncScope.js.map +7 -0
  73. package/docs/api-reference.md +13 -1
  74. package/package.json +1 -1
  75. package/dist/services/farseerApi.js +0 -716
  76. package/dist/services/farseerApi.js.map +0 -7
  77. package/dist/services/farseerFactory.js +0 -276
  78. package/dist/services/farseerFactory.js.map +0 -7
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/mcp/tools/modelTools.ts"],
4
- "sourcesContent": ["/**\n * Model Inspection Tools\n *\n * Tools for exploring Farseer data models (dimensions, variables, formulas).\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { requireSession } from '../utils/session';\nimport { successResponse, errorResponse } from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\nimport * as farseer from 'farseer-client';\nimport { EntityType } from 'farseer-client';\n\n// Maps user-friendly rollup type names to API values\nconst ROLLUP_TYPE_MAP: Record<string, string> = {\n sum: 'SUM',\n average: 'AVERAGE',\n avg: 'AVERAGE',\n min: 'MIN',\n max: 'MAX',\n none: 'NONE',\n formula: 'FORMULA',\n closingstate: 'CLOSING STATE',\n 'closing state': 'CLOSING STATE',\n 'closing-state': 'CLOSING STATE',\n beginningstate: 'BEGINNING STATE',\n 'beginning state': 'BEGINNING STATE',\n 'beginning-state': 'BEGINNING STATE',\n};\n\nfunction normalizeRollupType(value: string): string {\n const normalized = ROLLUP_TYPE_MAP[value.toLowerCase()];\n if (!normalized) {\n const validTypes = [...new Set(Object.values(ROLLUP_TYPE_MAP))].join(', ');\n throw new Error(`Invalid rollupType \"${value}\". Valid types: ${validTypes}`);\n }\n return normalized;\n}\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst evaluateFormulaSchema = {\n formula: z.string().describe('Formula expression to evaluate (e.g., variable name or calculation)'),\n filters: z\n .array(z.array(z.string()).length(2))\n .optional()\n .describe('Dimension filters as [tableName, memberName] pairs (e.g., [[\"Years\",\"2024\"],[\"Months\",\"Jan\"]])'),\n};\n\nconst listDimensionMembersSchema = {\n tableName: z.string().describe('Dimension table name'),\n limit: z.number().optional().describe('Maximum number of members to return'),\n};\n\nconst manageDimensionMembersSchema = {\n action: z.enum(['create', 'delete']).describe('Action to perform'),\n tableName: z.string().describe('Dimension table name'),\n memberName: z.string().describe('Member name to create or delete'),\n parentMemberName: z.string().optional().describe('Parent member name (for create with hierarchy)'),\n compound: z\n .boolean()\n .optional()\n .describe('Set to true to create a compound (calculated) member. Use with formula param.'),\n formula: z\n .string()\n .optional()\n .describe('Formula for compound members (e.g., \"$M1+$M2\"). Only used with compound=true.'),\n};\n\nconst createVariableSchema = {\n name: z.string().describe('Variable name'),\n dimensions: z.array(z.string()).optional().describe('Dimension table names this variable spans'),\n formula: z.string().optional().describe('Formula expression'),\n rollupType: z\n .string()\n .optional()\n .describe('Rollup type (Sum, Average, Min, Max, None, Formula, Closing State, Beginning State)'),\n dataType: z.string().optional().describe('Data type (Decimal, Integer, Text)'),\n description: z.string().optional().describe('Variable description'),\n readonly: z.boolean().optional().describe('Whether the variable is read-only'),\n measure: z.boolean().optional().describe('Set to true for dimensionless formula variables (measure mode)'),\n numberFormat: z\n .record(z.any())\n .optional()\n .describe('Number format config (e.g., { type: \"PERCENTAGE\", decimals: 1 }). Saves a separate update call.'),\n folderPath: z\n .array(z.string())\n .optional()\n .describe('Folder path to place the variable in (e.g., [\"Variables\", \"Revenue\"]). Uses create + move.'),\n};\n\nconst updateVariableSchema = {\n name: z.string().describe('Variable name to update (used for lookup)'),\n newName: z.string().optional().describe('Rename the variable to this name'),\n dimensions: z.array(z.string()).optional().describe('New dimension table names (replaces all existing dimensions)'),\n formula: z\n .string()\n .optional()\n .describe(\n 'New formula expression. Supports $GID syntax for direct references (e.g., \"$155-$297\"). Pass the formula string as-is.',\n ),\n rollupType: z.string().optional().describe('New rollup type'),\n description: z.string().optional().describe('New description'),\n readonly: z.boolean().optional().describe('Set read-only status'),\n polarity: z.enum(['POSITIVE', 'NEGATIVE']).optional().describe('Number format polarity (POSITIVE or NEGATIVE)'),\n numberFormat: z\n .record(z.any())\n .optional()\n .describe(\n 'Full number format configuration object. Fields: type, custom, formatString, decimals, polarity, negatives, unit, currency. Use this for fine-grained control over number formatting.',\n ),\n};\n\nconst deleteVariableSchema = {\n variableName: z.string().describe('Variable name to delete'),\n};\n\nconst deleteVariableDataSchema = {\n variableName: z.string().describe('Variable name whose data to delete'),\n};\n\nconst exportModelSchema = {\n includeMembers: z\n .boolean()\n .optional()\n .describe(\n 'Include dimension member rows. Default false because the unscoped fetch can exceed the response ' +\n 'size limit on larger tenants and time out. Use farseer_get_table for member samples of a single table instead.',\n ),\n};\n\nconst listTablesSchema = {};\n\nconst listVariablesSchema = {};\n\nconst getTableSchema = {\n tableName: z.string().describe('Name of the dimension table'),\n};\n\nconst getVariableSchema = {\n variableName: z.string().describe('Name of the variable'),\n};\n\nexport function registerModelTools(server: McpServer): void {\n // farseer_export_model - Export complete model\n server.tool(\n 'farseer_export_model',\n `Export the complete data model structure from a Farseer tenant.\n\nReturns:\n- All dimension tables with member counts and foreign key relationships\n- All variables with their dimensions, formulas, and roll-up types\n\nThis is essential for understanding a tenant's data structure before writing import scripts.\n\nFor large models (20KB+), the full result is automatically saved to a temp JSON file\nand only a summary is returned. Use the Read tool to inspect the file if needed.\nFor a quick overview without the full export, use farseer_list_tables or farseer_list_variables.`,\n exportModelSchema,\n async (params: { includeMembers?: boolean }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n // Default to a member-less export \u2014 see schema notes.\n // Agents that genuinely need members opt in explicitly.\n const types = params.includeMembers ? ['DTAB', 'DMEM', 'VAR'] : ['DTAB', 'VAR'];\n const model = await client.exportModel({\n types: types as ('DTAB' | 'DMEM' | 'VAR')[],\n });\n\n // Process tables\n const tables = model.tables.map((t) => ({\n name: t.name,\n memberCount: t.rows?.length || 0,\n columns: t.columns.map((c) => ({\n type: c.type,\n name: c.name,\n foreignKeyTable: c.foreignKeyTableName,\n })),\n foreignKeys: t.columns.filter((c) => c.type === 'FOREIGN_KEY').map((c) => c.foreignKeyTableName!),\n folderPath: t.folderPath,\n }));\n\n // Process variables\n const variables = model.variables.map((v) => ({\n name: v.name,\n dimensions: v.tables || [],\n formula: v.formula || undefined,\n rollupType: v.rollupType,\n numberFormat: v.numberFormat,\n readonly: v.readonly,\n calculateOnDemand: v.calculateOnDemand,\n folderPath: v.folderPath,\n }));\n\n const result = {\n tenant,\n summary: {\n tableCount: tables.length,\n variableCount: variables.length,\n },\n tables,\n variables,\n };\n\n // If the model is large, save to a temp file to avoid overwhelming context\n const jsonStr = JSON.stringify(result, null, 2);\n const JSON_SIZE_THRESHOLD = 20_000; // ~20KB\n\n if (jsonStr.length > JSON_SIZE_THRESHOLD) {\n const tmpDir = os.tmpdir();\n const filePath = path.join(tmpDir, `farseer_${tenant}_model.json`);\n fs.writeFileSync(filePath, jsonStr, 'utf-8');\n\n return successResponse({\n tenant,\n summary: {\n tableCount: tables.length,\n variableCount: variables.length,\n },\n exportedToFile: filePath,\n message: `Model has ${tables.length} tables and ${variables.length} variables (${Math.round(jsonStr.length / 1024)}KB) \u2014 exported to file. Use Read tool to inspect.`,\n tableSummary: tables.map((t) => `${t.name} (${t.memberCount} members)`),\n variableSummary: variables.map((v) => `${v.name} [${v.dimensions.join(', ')}]`),\n });\n }\n\n return successResponse(result);\n } catch (error) {\n const formatted = await formatClientError(error);\n // The unscoped + members fetch is exactly the path\n // that socket-hangs on larger tenants. Steer the agent\n // toward the per-table tool instead of letting it\n // retry the same failing call.\n if (params.includeMembers && /socket hang up|timeout|ECONNRESET/i.test(formatted)) {\n return errorResponse(\n `Export model with members timed out \u2014 the response is too large for this tenant. ` +\n `Retry with includeMembers: false (default) for the structure, then call farseer_get_table for the specific tables you need members from.`,\n 'NETWORK_ERROR',\n );\n }\n return errorResponse(`Export model failed: ${formatted}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_list_tables - List dimension tables\n server.tool(\n 'farseer_list_tables',\n `List all dimension tables in a Farseer tenant model.\n\nDimension tables define the structure of data:\n- Product, Region, Customer (business dimensions)\n- Months, Years (time dimensions - built-in)\n- Versions (scenario dimension - built-in)\n\nReturns table names, member counts, and foreign key relationships.`,\n listTablesSchema,\n async () => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n // Tables-only \u2014 listing names+columns is a lightweight\n // request even on larger tenants. Member counts are\n // only available via farseer_get_table for the table\n // the agent actually needs.\n const model = await client.exportModel({ types: ['DTAB'] });\n\n const tables = model.tables.map((t) => ({\n name: t.name,\n foreignKeys: t.columns.filter((c) => c.type === 'FOREIGN_KEY').map((c) => c.foreignKeyTableName!),\n }));\n\n // Sort by name\n tables.sort((a, b) => a.name.localeCompare(b.name));\n\n return successResponse({\n tenant,\n totalTables: tables.length,\n tables,\n });\n } catch (error) {\n return errorResponse(`List tables failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_list_variables - List variables\n server.tool(\n 'farseer_list_variables',\n `List all variables defined in a Farseer tenant model.\n\nVariables store data and calculations - they are the core of the data model.\n\nEach variable has:\n- Dimensions it spans (Product, Region, Month, etc.)\n- Optional formula for calculated values\n- Roll-up type (how values aggregate up hierarchies)`,\n listVariablesSchema,\n async () => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client, native: nativeClient } = gate.session;\n\n try {\n // Variables-only \u2014 skip the dimension member matrix.\n // On larger tenants the unscoped fetch exceeds the\n // Cloud Run / proxy response limit and the agent sees\n // \"socket hang up\" before any data arrives.\n const model = await client.exportModel({ types: ['VAR'] });\n\n // Prefer entityGid from the export response (now\n // populated when /model/export is reachable). Fall back\n // to the tag map only when needed \u2014 that path is the\n // expensive one we're trying to avoid.\n const variables = model.variables.map((v) => ({\n name: v.name,\n entityGid: v.gid ?? null,\n dimensions: v.tables || [],\n hasFormula: !!v.formula,\n rollupType: v.rollupType,\n readonly: v.readonly,\n }));\n\n if (variables.some((v) => v.entityGid === null)) {\n // Some variables didn't carry a gid (older server\n // or initTagMap fallback path). Best-effort fill in\n // via the tag map; failures here are silent because\n // gid is only required for sheet-row writes.\n try {\n await nativeClient.initTagMap();\n for (const v of variables) {\n if (v.entityGid !== null) continue;\n try {\n const tag = await nativeClient.getVariable(v.name);\n v.entityGid = tag.id;\n } catch {\n // skip \u2014 variable already in list\n }\n }\n } catch {\n // Tag map optional\n }\n }\n\n // Sort by name\n variables.sort((a, b) => a.name.localeCompare(b.name));\n\n return successResponse({\n tenant,\n totalVariables: variables.length,\n variables,\n });\n } catch (error) {\n return errorResponse(`List variables failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_get_table - Get dimension table details\n server.tool(\n 'farseer_get_table',\n `Get detailed information about a specific dimension table.\n\nReturns:\n- Table columns with their types\n- Foreign key relationships to other tables\n- Sample members (first 20)\n- Total member count\n\nThis helps understand the structure needed for import scripts.`,\n getTableSchema,\n async (params: { tableName: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n // Single-table member fetch via entities API. Goes\n // through search \u2192 getRelations \u2192 getMany so it's\n // bounded to one table by construction. We tried\n // `/model/export` with `tableGids` first but rama 500s\n // for some tables on large tenants \u2014 separate backend\n // bug, this path routes around it.\n const table = await client.loadDimensionTableWithMembers(params.tableName);\n\n if (!table) {\n return errorResponse(`Table \"${params.tableName}\" not found`, 'NOT_FOUND');\n }\n\n // Get sample members (first column is usually the primary key / name)\n const primaryKeyColumn = table.columns.find((c) => c.type === 'PRIMARY_KEY');\n let sampleMembers: string[] = [];\n\n if (table.rows && table.rows.length > 0) {\n const pkIndex = primaryKeyColumn ? table.columns.indexOf(primaryKeyColumn) : 0;\n sampleMembers = table.rows.slice(0, 20).map((row) => String(row[pkIndex]));\n }\n\n return successResponse({\n tenant,\n table: {\n name: table.name,\n columns: table.columns.map((c) => ({\n type: c.type,\n name: c.name,\n foreignKeyTable: c.foreignKeyTableName,\n })),\n memberCount: table.rows?.length || 0,\n sampleMembers,\n folderPath: table.folderPath,\n },\n });\n } catch (error) {\n return errorResponse(`Get table failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_get_variable - Get variable details\n server.tool(\n 'farseer_get_variable',\n `Get detailed information about a specific variable.\n\nReturns:\n- Dimensions the variable spans\n- Formula (if calculated)\n- Roll-up type (SUM, AVERAGE, etc.)\n- Data type and format\n- Whether it's readonly or calculated on demand\n\nThis is essential for understanding what dimensions and values are needed for imports.`,\n getVariableSchema,\n async (params: { variableName: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client, native: nativeClient } = gate.session;\n\n try {\n // Variables-only \u2014 skips the dimension member matrix.\n const model = await client.exportModel({ types: ['VAR'] });\n\n const variable = model.variables.find(\n (v) => v.name.toLowerCase() === params.variableName.toLowerCase(),\n );\n\n if (!variable) {\n return errorResponse(`Variable \"${params.variableName}\" not found`, 'NOT_FOUND');\n }\n\n // Prefer the gid that came back with the export. Tag\n // map lookup is the slow path and only needed when the\n // server didn't include gid (older instance / fallback).\n let entityGid: number | null = variable.gid ?? null;\n if (entityGid === null) {\n try {\n await nativeClient.initTagMap();\n const tag = await nativeClient.getVariable(variable.name);\n entityGid = tag.id;\n } catch {\n // Tag map lookup optional \u2014 continue without GID\n }\n }\n\n return successResponse({\n tenant,\n variable: {\n name: variable.name,\n entityGid,\n description: variable.description,\n formula: variable.formula,\n dimensions: variable.tables || [],\n rollupType: variable.rollupType,\n dataType: variable.dataType,\n numberFormat: variable.numberFormat,\n readonly: variable.readonly,\n calculateOnDemand: variable.calculateOnDemand,\n folderPath: variable.folderPath,\n },\n });\n } catch (error) {\n return errorResponse(`Get variable failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_evaluate_formula - Evaluate a formula expression\n server.tool(\n 'farseer_evaluate_formula',\n `Evaluate a formula expression in a Farseer tenant.\n\nThe formula can be a variable name or a calculation expression.\nVariable names with spaces or special characters (e.g., \"P&L\", \"New Variable2\") are\nautomatically quoted for the backend formula parser \u2014 just pass the plain name.\nFilters narrow the evaluation to specific dimension members.\n\nExample: evaluate \"Revenue\" with filters [[\"Years\",\"Y2025\"],[\"Months\",\"M1\"]]\n\nReturns the computed value along with cell metadata (readonly, calculated, frozen).`,\n evaluateFormulaSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { formula: string; filters?: Array<Array<string>> }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n // Auto-wrap variable names that contain special characters (spaces, &, etc.)\n // but leave actual formula expressions (with operators, parentheses) untouched.\n // The backend formula parser requires double-quoted identifiers for names with special chars.\n let formula = params.formula;\n const isSimpleIdentifier = !formula.startsWith('\"') && !/[+\\-*/()>,<!=]/.test(formula);\n if (isSimpleIdentifier && /[\\s&]/.test(formula)) {\n formula = `\"${formula}\"`;\n }\n\n const evaluateRequest = {\n filters: params.filters || [],\n cellQueries: [{ type: 'VARIABLE' as const, formula }],\n };\n\n const results = await nativeClient.evaluator.evaluate(evaluateRequest);\n\n return successResponse({\n tenant,\n formula: params.formula,\n filters: params.filters || [],\n results: results.map((r) => ({\n value: r.value,\n readonly: r.readonly,\n calculated: r.calculated,\n frozen: r.frozen,\n goal: r.goal,\n })),\n });\n } catch (error) {\n return errorResponse(`Evaluate formula failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_list_dimension_members - List members of a dimension table\n server.tool(\n 'farseer_list_dimension_members',\n `List all members of a specific dimension table.\n\nUses initTagMap() to load the model's tag map, then retrieves members for the specified table.\nReturns member IDs, names, and parent relationships.\n\nFor large tables (500+ members), automatically exports to a CSV file and returns the file path\ninstead of inline data, to avoid overwhelming the context window.`,\n listDimensionMembersSchema,\n async (params: { tableName: string; limit?: number }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n const members = await nativeClient.getDimensionMembersForTable(params.tableName);\n\n const CSV_THRESHOLD = 500;\n const limit = params.limit || members.length;\n const sliced = members.slice(0, limit);\n\n // Large result \u2014 export to CSV file\n if (sliced.length >= CSV_THRESHOLD) {\n const csvLines = ['id,name,parentId'];\n for (const m of sliced) {\n const name =\n m.name.includes(',') || m.name.includes('\"') ? `\"${m.name.replace(/\"/g, '\"\"')}\"` : m.name;\n csvLines.push(`${m.id},${name},${m.ParentId ?? ''}`);\n }\n const tmpDir = os.tmpdir();\n const safeName = params.tableName.replace(/[^a-zA-Z0-9_-]/g, '_');\n const csvPath = path.join(tmpDir, `farseer_${tenant}_${safeName}_members.csv`);\n fs.writeFileSync(csvPath, csvLines.join('\\n'), 'utf-8');\n\n return successResponse({\n tenant,\n tableName: params.tableName,\n totalMembers: members.length,\n returned: sliced.length,\n exportedToCsv: csvPath,\n message: `Table has ${members.length} members \u2014 exported to CSV file. Use Read tool to inspect the file.`,\n sampleMembers: sliced.slice(0, 10).map((m) => ({\n id: m.id,\n name: m.name,\n parentId: m.ParentId,\n })),\n });\n }\n\n // Small result \u2014 return inline\n const result = sliced.map((m) => ({\n id: m.id,\n name: m.name,\n parentId: m.ParentId,\n }));\n\n return successResponse({\n tenant,\n tableName: params.tableName,\n totalMembers: members.length,\n returned: result.length,\n members: result,\n });\n } catch (error) {\n return errorResponse(\n `List dimension members failed: ${await formatClientError(error)}`,\n 'NETWORK_ERROR',\n );\n }\n },\n );\n\n // farseer_manage_dimension_members - Create or delete dimension members\n server.tool(\n 'farseer_manage_dimension_members',\n `Create or delete a dimension member in a Farseer tenant.\n\nActions:\n- \"create\": Creates a new member in the specified dimension table.\n Optionally set a parent member for hierarchical tables.\n Set compound=true with a formula to create a compound (calculated) member\n (e.g., for AC Period / FC Period filters on variance rows).\n- \"delete\": Deletes an existing member by name from the specified table.\n\nWARNING: Delete is destructive and may affect data. Use with caution.`,\n manageDimensionMembersSchema,\n async (params: {\n action: 'create' | 'delete';\n tableName: string;\n memberName: string;\n parentMemberName?: string;\n compound?: boolean;\n formula?: string;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n\n if (params.action === 'create') {\n const table = await nativeClient.getDimensionTable(params.tableName);\n\n const createEntity: any = {\n type: EntityType.DimensionMember,\n meta: { name: params.memberName },\n relations: {\n parent: {\n key: { id: table.id, type: EntityType.DimensionTable },\n order: 0,\n },\n },\n dimensionMember: { data: {} },\n };\n\n if (params.parentMemberName) {\n const parentMember = await nativeClient.getDimensionMember(\n params.tableName,\n params.parentMemberName,\n );\n createEntity.relations.parent = {\n key: { id: parentMember.id, type: EntityType.DimensionMember },\n order: 0,\n };\n }\n\n // Add compound calculation if requested\n if (params.compound) {\n createEntity.calculation = {\n type: 'COMPOUND',\n formula: params.formula || '',\n };\n }\n\n const result = await nativeClient.entities.mutate({ created: [createEntity] });\n\n return successResponse({\n tenant,\n action: 'created',\n tableName: params.tableName,\n memberName: params.memberName,\n parentMemberName: params.parentMemberName || null,\n result,\n });\n } else {\n const member = await nativeClient.getDimensionMember(params.tableName, params.memberName);\n\n await nativeClient.entities.mutate({\n deleted: [{ id: member.id, type: EntityType.DimensionMember }],\n });\n\n return successResponse({\n tenant,\n action: 'deleted',\n tableName: params.tableName,\n memberName: params.memberName,\n memberId: member.id,\n });\n }\n } catch (error) {\n return errorResponse(\n `Manage dimension member failed: ${await formatClientError(error)}`,\n 'NETWORK_ERROR',\n );\n }\n },\n );\n\n // farseer_create_table - Create a new dimension table\n server.tool(\n 'farseer_create_table',\n `Create a new dimension table in a Farseer tenant.\n\nDimension tables define the structure of data (e.g., Product, Region, Compound Members).\nCreates an empty table that you can then add members to with farseer_manage_dimension_members.`,\n {\n name: z.string().describe('Dimension table name'),\n folderPath: z\n .array(z.string())\n .optional()\n .describe('Folder path (e.g., [\"Dimensions\"]). Uses create + move.'),\n },\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { name: string; folderPath?: string[] }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n\n const createEntity: any = {\n type: EntityType.DimensionTable,\n meta: { name: params.name, description: null },\n };\n\n // Resolve target folder and set relations.folder for direct placement\n if (params.folderPath && params.folderPath.length > 0) {\n try {\n let currentFolderId: number | null = null;\n for (const segment of params.folderPath) {\n const parentItems = await nativeClient.folders.listItemsBatch([{ id: currentFolderId }]);\n const existing = parentItems[0]?.items?.find(\n (i: any) =>\n i.type === farseer.FolderItemType.Folder &&\n i.name.toLowerCase() === segment.toLowerCase(),\n );\n if (existing) {\n currentFolderId = existing.id;\n } else {\n const newFolder = await nativeClient.folders.create({\n parentId: currentFolderId,\n name: segment,\n allowedTypes: null,\n } as any);\n currentFolderId = (newFolder as any).id;\n }\n }\n if (currentFolderId) {\n createEntity.relations = {\n folder: { key: { id: currentFolderId, type: EntityType.Folder }, order: 0 },\n };\n }\n } catch {\n // Folder resolution is best-effort\n }\n }\n\n const result = await nativeClient.entities.mutate({ created: [createEntity] });\n const created = (result as any).created?.[0];\n\n return successResponse({\n tenant,\n action: 'created',\n table: {\n id: created?.id,\n name: params.name,\n },\n message: `Dimension table \"${params.name}\" created`,\n });\n } catch (error) {\n return errorResponse(`Create table failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_variable - Create a new variable\n server.tool(\n 'farseer_create_variable',\n `Create a new variable in a Farseer tenant.\n\nCreates a variable with the specified name, dimension tables, formula, rollup type, and data type.\nDimension table names are resolved to their internal IDs automatically.\n\nExample:\n{\n \"name\": \"Revenue Forecast\",\n \"dimensions\": [\"Product\", \"Years\", \"Months\"],\n \"formula\": \"Revenue * 1.1\",\n \"rollupType\": \"Sum\",\n \"dataType\": \"Decimal\"\n}`,\n createVariableSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: {\n name: string;\n dimensions?: string[];\n formula?: string;\n rollupType?: string;\n dataType?: string;\n description?: string;\n readonly?: boolean;\n measure?: boolean;\n numberFormat?: Record<string, any>;\n folderPath?: string[];\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n\n // Resolve dimension table names to IDs\n const tableGids: number[] = [];\n if (params.dimensions) {\n for (const tableName of params.dimensions) {\n const table = await nativeClient.getDimensionTable(tableName);\n tableGids.push(table.id);\n }\n }\n\n // Normalize rollupType and dataType to match API expected values\n const rollupType = normalizeRollupType(params.rollupType || 'SUM');\n const dataType = (params.dataType || 'DECIMAL').toUpperCase();\n\n const createEntity: any = {\n type: EntityType.Variable,\n meta: {\n name: params.name,\n description: params.description || null,\n },\n variable: {\n tableGids,\n rollupType,\n dataType,\n readonly: params.readonly || false,\n measure: params.measure || false,\n },\n };\n\n if (params.formula) {\n createEntity.calculation = { formula: params.formula };\n }\n\n if (params.numberFormat) {\n createEntity.numberFormat = params.numberFormat;\n }\n\n // Resolve target folder and set relations.folder for direct placement\n if (params.folderPath && params.folderPath.length > 0) {\n try {\n let currentFolderId: number | null = null;\n for (const segment of params.folderPath) {\n const parentItems = await nativeClient.folders.listItemsBatch([{ id: currentFolderId }]);\n const existing = parentItems[0]?.items?.find(\n (i: any) =>\n i.type === farseer.FolderItemType.Folder &&\n i.name.toLowerCase() === segment.toLowerCase(),\n );\n if (existing) {\n currentFolderId = existing.id;\n } else {\n const newFolder = await nativeClient.folders.create({\n parentId: currentFolderId,\n name: segment,\n allowedTypes: null,\n } as any);\n currentFolderId = (newFolder as any).id;\n }\n }\n if (currentFolderId) {\n createEntity.relations = {\n folder: { key: { id: currentFolderId, type: EntityType.Folder }, order: 0 },\n };\n }\n } catch {\n // Folder resolution is best-effort \u2014 variable creates in default folder\n }\n }\n\n const result = await nativeClient.entities.mutate({ created: [createEntity] });\n\n return successResponse({\n tenant,\n action: 'created',\n variable: params.name,\n dimensions: params.dimensions || [],\n result,\n });\n } catch (error) {\n return errorResponse(`Create variable failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_update_variable - Update an existing variable\n server.tool(\n 'farseer_update_variable',\n `Update an existing variable in a Farseer tenant.\n\nResolves the variable by name and updates the specified fields.\nOnly provided fields are updated; omitted fields remain unchanged.\n\nUpdatable fields:\n- newName: Rename the variable\n- dimensions: Change which dimension tables the variable spans (replaces all existing dimensions)\n- formula: Change the calculation formula (supports $GID syntax like \"$155-$297\")\n- rollupType: Change aggregation method (Sum, Average, Min, Max, etc.)\n- description: Change the variable description\n- readonly: Set or clear read-only status\n- polarity: Set number polarity (POSITIVE or NEGATIVE)\n- numberFormat: Full number format config (type, decimals, polarity, unit, currency, etc.)`,\n updateVariableSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: {\n name: string;\n newName?: string;\n dimensions?: string[];\n formula?: string;\n rollupType?: string;\n description?: string;\n readonly?: boolean;\n polarity?: 'POSITIVE' | 'NEGATIVE';\n numberFormat?: Record<string, any>;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n const variable = await nativeClient.getVariable(params.name);\n\n // Fetch full current entity - EntityUpdate requires ALL VariableComponent fields\n const currentEntity = await nativeClient.entities.getSingle(variable.id, EntityType.Variable);\n const current = currentEntity as any;\n\n // Build update with full variable component (backend requires all fields)\n const currentVar = current.variable || {};\n const updateEntity: any = {\n id: variable.id,\n type: EntityType.Variable,\n meta: {\n name: params.newName || variable.name,\n description:\n params.description !== undefined ? params.description : (current.meta?.description ?? null),\n },\n variable: {\n notes: currentVar.notes ?? null,\n tableGids: currentVar.tableGids || [],\n memberGids: currentVar.memberGids || [],\n rollupType: currentVar.rollupType || 'SUM',\n dataType: currentVar.dataType || 'DECIMAL',\n topDownMapping: currentVar.topDownMapping ?? null,\n measure: currentVar.measure || false,\n readonly: currentVar.readonly || false,\n calculateOnDemand: currentVar.calculateOnDemand || false,\n zConstraint: currentVar.zConstraint || false,\n optimizeCalculation: currentVar.optimizeCalculation ?? true,\n // referencedBy is readOnly - do NOT send in update requests\n },\n };\n\n // Override only changed fields\n if (params.dimensions) {\n const tableGids: number[] = [];\n for (const tableName of params.dimensions) {\n const table = await nativeClient.getDimensionTable(tableName);\n tableGids.push(table.id);\n }\n updateEntity.variable.tableGids = tableGids;\n }\n if (params.rollupType) {\n updateEntity.variable.rollupType = normalizeRollupType(params.rollupType);\n }\n if (params.readonly !== undefined) {\n updateEntity.variable.readonly = params.readonly;\n }\n\n // Preserve existing calculation unless explicitly changing formula.\n // Always include calculation.type (required by backend, e.g. 'VARIABLE').\n const currentCalc = current.calculation;\n if (params.formula !== undefined) {\n updateEntity.calculation = {\n formula: params.formula,\n type: currentCalc?.type || 'VARIABLE',\n };\n } else if (currentCalc) {\n updateEntity.calculation = currentCalc;\n }\n\n // Handle numberFormat / polarity updates\n if (params.numberFormat || params.polarity) {\n const currentFormat = current.numberFormat || {};\n updateEntity.numberFormat = {\n ...currentFormat,\n ...(params.numberFormat || {}),\n };\n // If polarity is set separately, override it in the format\n if (params.polarity) {\n updateEntity.numberFormat.polarity = params.polarity;\n }\n }\n\n const result = await nativeClient.entities.mutate({ updated: [updateEntity] });\n\n return successResponse({\n tenant,\n action: 'updated',\n variable: params.name,\n variableId: variable.id,\n result,\n });\n } catch (error) {\n return errorResponse(`Update variable failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_delete_variable_data - Delete all data for a variable\n server.tool(\n 'farseer_delete_variable_data',\n `Delete ALL data for a variable in a Farseer tenant.\n\nWARNING: This is destructive and cannot be undone. It removes all cell values\nfor the specified variable across all dimensions and time periods.\n\nUse this to clear old template data or reset a variable before re-importing.`,\n deleteVariableDataSchema,\n async (params: { variableName: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n const variable = await nativeClient.getVariable(params.variableName);\n\n await nativeClient.entities.deleteData({\n id: variable.id,\n type: EntityType.Variable,\n });\n\n return successResponse({\n tenant,\n action: 'deleted_data',\n variable: params.variableName,\n variableId: variable.id,\n message: `All data deleted for variable \"${params.variableName}\"`,\n });\n } catch (error) {\n return errorResponse(`Delete variable data failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_delete_variable - Delete a variable\n server.tool(\n 'farseer_delete_variable',\n `Delete a variable from a Farseer tenant.\n\nResolves the variable by name and permanently deletes it along with all its data.\n\nWARNING: This is destructive and cannot be undone.`,\n deleteVariableSchema,\n async (params: { variableName: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n const variable = await nativeClient.getVariable(params.variableName);\n\n await nativeClient.entities.mutate({\n deleted: [{ id: variable.id, type: EntityType.Variable }],\n });\n\n return successResponse({\n tenant,\n action: 'deleted',\n variable: params.variableName,\n variableId: variable.id,\n message: `Variable \"${params.variableName}\" deleted`,\n });\n } catch (error) {\n return errorResponse(`Delete variable failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AACpB,qBAA+B;AAC/B,qBAA+C;AAC/C,4BAAkC;AAClC,cAAyB;AACzB,4BAA2B;AAG3B,MAAM,kBAA0C;AAAA,EAC5C,KAAK;AAAA,EACL,SAAS;AAAA,EACT,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,MAAM;AAAA,EACN,SAAS;AAAA,EACT,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,gBAAgB;AAAA,EAChB,mBAAmB;AAAA,EACnB,mBAAmB;AACvB;AAEA,SAAS,oBAAoB,OAAuB;AAChD,QAAM,aAAa,gBAAgB,MAAM,YAAY,CAAC;AACtD,MAAI,CAAC,YAAY;AACb,UAAM,aAAa,CAAC,GAAG,IAAI,IAAI,OAAO,OAAO,eAAe,CAAC,CAAC,EAAE,KAAK,IAAI;AACzE,UAAM,IAAI,MAAM,uBAAuB,KAAK,mBAAmB,UAAU,EAAE;AAAA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,MACL,SAAS,OAAO;AACZ,mBAAO,8BAAc,2BAA2B,UAAM,yCAAkB,KAAK,CAAC,IAAI,eAAe;AAAA,MACrG;AAAA,IACJ;AAAA,EACJ;AACJ;",
4
+ "sourcesContent": ["/**\n * Model Inspection Tools\n *\n * Tools for exploring Farseer data models (dimensions, variables, formulas).\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\nimport { requireSession } from '../utils/session';\nimport { successResponse, errorResponse } from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\nimport { AmbiguousFolderError, matchFolderSegment } from '../../utils/folderMatch';\nimport * as farseer from 'farseer-client';\nimport { EntityType } from 'farseer-client';\n\n// Maps user-friendly rollup type names to API values\nconst ROLLUP_TYPE_MAP: Record<string, string> = {\n sum: 'SUM',\n average: 'AVERAGE',\n avg: 'AVERAGE',\n min: 'MIN',\n max: 'MAX',\n none: 'NONE',\n formula: 'FORMULA',\n closingstate: 'CLOSING STATE',\n 'closing state': 'CLOSING STATE',\n 'closing-state': 'CLOSING STATE',\n beginningstate: 'BEGINNING STATE',\n 'beginning state': 'BEGINNING STATE',\n 'beginning-state': 'BEGINNING STATE',\n};\n\nfunction normalizeRollupType(value: string): string {\n const normalized = ROLLUP_TYPE_MAP[value.toLowerCase()];\n if (!normalized) {\n const validTypes = [...new Set(Object.values(ROLLUP_TYPE_MAP))].join(', ');\n throw new Error(`Invalid rollupType \"${value}\". Valid types: ${validTypes}`);\n }\n return normalized;\n}\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst evaluateFormulaSchema = {\n formula: z.string().describe('Formula expression to evaluate (e.g., variable name or calculation)'),\n filters: z\n .array(z.array(z.string()).length(2))\n .optional()\n .describe('Dimension filters as [tableName, memberName] pairs (e.g., [[\"Years\",\"2024\"],[\"Months\",\"Jan\"]])'),\n};\n\nconst listDimensionMembersSchema = {\n tableName: z.string().describe('Dimension table name'),\n limit: z.number().optional().describe('Maximum number of members to return'),\n};\n\nconst manageDimensionMembersSchema = {\n action: z.enum(['create', 'delete']).describe('Action to perform'),\n tableName: z.string().describe('Dimension table name'),\n memberName: z.string().describe('Member name to create or delete'),\n parentMemberName: z.string().optional().describe('Parent member name (for create with hierarchy)'),\n compound: z\n .boolean()\n .optional()\n .describe('Set to true to create a compound (calculated) member. Use with formula param.'),\n formula: z\n .string()\n .optional()\n .describe('Formula for compound members (e.g., \"$M1+$M2\"). Only used with compound=true.'),\n};\n\nconst createVariableSchema = {\n name: z.string().describe('Variable name'),\n dimensions: z.array(z.string()).optional().describe('Dimension table names this variable spans'),\n formula: z.string().optional().describe('Formula expression'),\n rollupType: z\n .string()\n .optional()\n .describe('Rollup type (Sum, Average, Min, Max, None, Formula, Closing State, Beginning State)'),\n dataType: z.string().optional().describe('Data type (Decimal, Integer, Text)'),\n description: z.string().optional().describe('Variable description'),\n readonly: z.boolean().optional().describe('Whether the variable is read-only'),\n measure: z.boolean().optional().describe('Set to true for dimensionless formula variables (measure mode)'),\n numberFormat: z\n .record(z.any())\n .optional()\n .describe('Number format config (e.g., { type: \"PERCENTAGE\", decimals: 1 }). Saves a separate update call.'),\n folderPath: z\n .array(z.string())\n .optional()\n .describe('Folder path to place the variable in (e.g., [\"Variables\", \"Revenue\"]). Uses create + move.'),\n};\n\nconst updateVariableSchema = {\n name: z.string().describe('Variable name to update (used for lookup)'),\n newName: z.string().optional().describe('Rename the variable to this name'),\n dimensions: z.array(z.string()).optional().describe('New dimension table names (replaces all existing dimensions)'),\n formula: z\n .string()\n .optional()\n .describe(\n 'New formula expression. Supports $GID syntax for direct references (e.g., \"$155-$297\"). Pass the formula string as-is.',\n ),\n rollupType: z.string().optional().describe('New rollup type'),\n description: z.string().optional().describe('New description'),\n readonly: z.boolean().optional().describe('Set read-only status'),\n polarity: z.enum(['POSITIVE', 'NEGATIVE']).optional().describe('Number format polarity (POSITIVE or NEGATIVE)'),\n numberFormat: z\n .record(z.any())\n .optional()\n .describe(\n 'Full number format configuration object. Fields: type, custom, formatString, decimals, polarity, negatives, unit, currency. Use this for fine-grained control over number formatting.',\n ),\n};\n\nconst deleteVariableSchema = {\n variableName: z.string().describe('Variable name to delete'),\n};\n\nconst deleteVariableDataSchema = {\n variableName: z.string().describe('Variable name whose data to delete'),\n};\n\nconst exportModelSchema = {\n includeMembers: z\n .boolean()\n .optional()\n .describe(\n 'Include dimension member rows. Default false because the unscoped fetch can exceed the response ' +\n 'size limit on larger tenants and time out. Use farseer_get_table for member samples of a single table instead.',\n ),\n};\n\nconst listTablesSchema = {};\n\nconst listVariablesSchema = {};\n\nconst getTableSchema = {\n tableName: z.string().describe('Name of the dimension table'),\n};\n\nconst getVariableSchema = {\n variableName: z.string().describe('Name of the variable'),\n};\n\n/**\n * The folder to create a model entity in, walking `folderPath` and creating\n * what is missing.\n *\n * Placement is best-effort \u2014 a failed walk still creates the entity, in the\n * default folder \u2014 with one exception: two sibling folders whose names differ\n * only in case. Picking one by listing order would put the entity somewhere the\n * caller did not name, so that is refused rather than guessed.\n */\nasync function folderFor(\n nativeClient: farseer.FarseerClient,\n folderPath: string[],\n): Promise<{ folderId: number | null } | { error: ReturnType<typeof errorResponse> }> {\n try {\n let currentFolderId: number | null = null;\n for (const segment of folderPath) {\n const parentItems = await nativeClient.folders.listItemsBatch([{ id: currentFolderId }]);\n const folders = (parentItems[0]?.items ?? []).filter(\n (i: any) => i.type === farseer.FolderItemType.Folder,\n ) as { id: number; name: string }[];\n const existing = matchFolderSegment(folders, segment);\n if (existing) {\n currentFolderId = existing.id;\n } else {\n const newFolder = await nativeClient.folders.create({\n parentId: currentFolderId,\n name: segment,\n allowedTypes: null,\n } as any);\n currentFolderId = (newFolder as any).id;\n }\n }\n return { folderId: currentFolderId };\n } catch (error) {\n if (error instanceof AmbiguousFolderError) {\n return { error: errorResponse(error.message, 'VALIDATION_ERROR') };\n }\n return { folderId: null };\n }\n}\n\nexport function registerModelTools(server: McpServer): void {\n // farseer_export_model - Export complete model\n server.tool(\n 'farseer_export_model',\n `Export the complete data model structure from a Farseer tenant.\n\nReturns:\n- All dimension tables with member counts and foreign key relationships\n- All variables with their dimensions, formulas, and roll-up types\n\nThis is essential for understanding a tenant's data structure before writing import scripts.\n\nFor large models (20KB+), the full result is automatically saved to a temp JSON file\nand only a summary is returned. Use the Read tool to inspect the file if needed.\nFor a quick overview without the full export, use farseer_list_tables or farseer_list_variables.`,\n exportModelSchema,\n async (params: { includeMembers?: boolean }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n // Default to a member-less export \u2014 see schema notes.\n // Agents that genuinely need members opt in explicitly.\n const types = params.includeMembers ? ['DTAB', 'DMEM', 'VAR'] : ['DTAB', 'VAR'];\n const model = await client.exportModel({\n types: types as ('DTAB' | 'DMEM' | 'VAR')[],\n });\n\n // Process tables\n const tables = model.tables.map((t) => ({\n name: t.name,\n memberCount: t.rows?.length || 0,\n columns: t.columns.map((c) => ({\n type: c.type,\n name: c.name,\n foreignKeyTable: c.foreignKeyTableName,\n })),\n foreignKeys: t.columns.filter((c) => c.type === 'FOREIGN_KEY').map((c) => c.foreignKeyTableName!),\n folderPath: t.folderPath,\n }));\n\n // Process variables\n const variables = model.variables.map((v) => ({\n name: v.name,\n dimensions: v.tables || [],\n formula: v.formula || undefined,\n rollupType: v.rollupType,\n numberFormat: v.numberFormat,\n readonly: v.readonly,\n calculateOnDemand: v.calculateOnDemand,\n folderPath: v.folderPath,\n }));\n\n const result = {\n tenant,\n summary: {\n tableCount: tables.length,\n variableCount: variables.length,\n },\n tables,\n variables,\n };\n\n // If the model is large, save to a temp file to avoid overwhelming context\n const jsonStr = JSON.stringify(result, null, 2);\n const JSON_SIZE_THRESHOLD = 20_000; // ~20KB\n\n if (jsonStr.length > JSON_SIZE_THRESHOLD) {\n const tmpDir = os.tmpdir();\n const filePath = path.join(tmpDir, `farseer_${tenant}_model.json`);\n fs.writeFileSync(filePath, jsonStr, 'utf-8');\n\n return successResponse({\n tenant,\n summary: {\n tableCount: tables.length,\n variableCount: variables.length,\n },\n exportedToFile: filePath,\n message: `Model has ${tables.length} tables and ${variables.length} variables (${Math.round(jsonStr.length / 1024)}KB) \u2014 exported to file. Use Read tool to inspect.`,\n tableSummary: tables.map((t) => `${t.name} (${t.memberCount} members)`),\n variableSummary: variables.map((v) => `${v.name} [${v.dimensions.join(', ')}]`),\n });\n }\n\n return successResponse(result);\n } catch (error) {\n const formatted = await formatClientError(error);\n // The unscoped + members fetch is exactly the path\n // that socket-hangs on larger tenants. Steer the agent\n // toward the per-table tool instead of letting it\n // retry the same failing call.\n if (params.includeMembers && /socket hang up|timeout|ECONNRESET/i.test(formatted)) {\n return errorResponse(\n `Export model with members timed out \u2014 the response is too large for this tenant. ` +\n `Retry with includeMembers: false (default) for the structure, then call farseer_get_table for the specific tables you need members from.`,\n 'NETWORK_ERROR',\n );\n }\n return errorResponse(`Export model failed: ${formatted}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_list_tables - List dimension tables\n server.tool(\n 'farseer_list_tables',\n `List all dimension tables in a Farseer tenant model.\n\nDimension tables define the structure of data:\n- Product, Region, Customer (business dimensions)\n- Months, Years (time dimensions - built-in)\n- Versions (scenario dimension - built-in)\n\nReturns table names, member counts, and foreign key relationships.`,\n listTablesSchema,\n async () => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n // Tables-only \u2014 listing names+columns is a lightweight\n // request even on larger tenants. Member counts are\n // only available via farseer_get_table for the table\n // the agent actually needs.\n const model = await client.exportModel({ types: ['DTAB'] });\n\n const tables = model.tables.map((t) => ({\n name: t.name,\n foreignKeys: t.columns.filter((c) => c.type === 'FOREIGN_KEY').map((c) => c.foreignKeyTableName!),\n }));\n\n // Sort by name\n tables.sort((a, b) => a.name.localeCompare(b.name));\n\n return successResponse({\n tenant,\n totalTables: tables.length,\n tables,\n });\n } catch (error) {\n return errorResponse(`List tables failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_list_variables - List variables\n server.tool(\n 'farseer_list_variables',\n `List all variables defined in a Farseer tenant model.\n\nVariables store data and calculations - they are the core of the data model.\n\nEach variable has:\n- Dimensions it spans (Product, Region, Month, etc.)\n- Optional formula for calculated values\n- Roll-up type (how values aggregate up hierarchies)`,\n listVariablesSchema,\n async () => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client, native: nativeClient } = gate.session;\n\n try {\n // Variables-only \u2014 skip the dimension member matrix.\n // On larger tenants the unscoped fetch exceeds the\n // Cloud Run / proxy response limit and the agent sees\n // \"socket hang up\" before any data arrives.\n const model = await client.exportModel({ types: ['VAR'] });\n\n // Prefer entityGid from the export response (now\n // populated when /model/export is reachable). Fall back\n // to the tag map only when needed \u2014 that path is the\n // expensive one we're trying to avoid.\n const variables = model.variables.map((v) => ({\n name: v.name,\n entityGid: v.gid ?? null,\n dimensions: v.tables || [],\n hasFormula: !!v.formula,\n rollupType: v.rollupType,\n readonly: v.readonly,\n }));\n\n if (variables.some((v) => v.entityGid === null)) {\n // Some variables didn't carry a gid (older server\n // or initTagMap fallback path). Best-effort fill in\n // via the tag map; failures here are silent because\n // gid is only required for sheet-row writes.\n try {\n await nativeClient.initTagMap();\n for (const v of variables) {\n if (v.entityGid !== null) continue;\n try {\n const tag = await nativeClient.getVariable(v.name);\n v.entityGid = tag.id;\n } catch {\n // skip \u2014 variable already in list\n }\n }\n } catch {\n // Tag map optional\n }\n }\n\n // Sort by name\n variables.sort((a, b) => a.name.localeCompare(b.name));\n\n return successResponse({\n tenant,\n totalVariables: variables.length,\n variables,\n });\n } catch (error) {\n return errorResponse(`List variables failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_get_table - Get dimension table details\n server.tool(\n 'farseer_get_table',\n `Get detailed information about a specific dimension table.\n\nReturns:\n- Table columns with their types\n- Foreign key relationships to other tables\n- Sample members (first 20)\n- Total member count\n\nThis helps understand the structure needed for import scripts.`,\n getTableSchema,\n async (params: { tableName: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client } = gate.session;\n\n try {\n // Single-table member fetch via entities API. Goes\n // through search \u2192 getRelations \u2192 getMany so it's\n // bounded to one table by construction. We tried\n // `/model/export` with `tableGids` first but rama 500s\n // for some tables on large tenants \u2014 separate backend\n // bug, this path routes around it.\n const table = await client.loadDimensionTableWithMembers(params.tableName);\n\n if (!table) {\n return errorResponse(`Table \"${params.tableName}\" not found`, 'NOT_FOUND');\n }\n\n // Get sample members (first column is usually the primary key / name)\n const primaryKeyColumn = table.columns.find((c) => c.type === 'PRIMARY_KEY');\n let sampleMembers: string[] = [];\n\n if (table.rows && table.rows.length > 0) {\n const pkIndex = primaryKeyColumn ? table.columns.indexOf(primaryKeyColumn) : 0;\n sampleMembers = table.rows.slice(0, 20).map((row) => String(row[pkIndex]));\n }\n\n return successResponse({\n tenant,\n table: {\n name: table.name,\n columns: table.columns.map((c) => ({\n type: c.type,\n name: c.name,\n foreignKeyTable: c.foreignKeyTableName,\n })),\n memberCount: table.rows?.length || 0,\n sampleMembers,\n folderPath: table.folderPath,\n },\n });\n } catch (error) {\n return errorResponse(`Get table failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_get_variable - Get variable details\n server.tool(\n 'farseer_get_variable',\n `Get detailed information about a specific variable.\n\nReturns:\n- Dimensions the variable spans\n- Formula (if calculated)\n- Roll-up type (SUM, AVERAGE, etc.)\n- Data type and format\n- Whether it's readonly or calculated on demand\n\nThis is essential for understanding what dimensions and values are needed for imports.`,\n getVariableSchema,\n async (params: { variableName: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, client, native: nativeClient } = gate.session;\n\n try {\n // Variables-only \u2014 skips the dimension member matrix.\n const model = await client.exportModel({ types: ['VAR'] });\n\n const variable = model.variables.find(\n (v) => v.name.toLowerCase() === params.variableName.toLowerCase(),\n );\n\n if (!variable) {\n return errorResponse(`Variable \"${params.variableName}\" not found`, 'NOT_FOUND');\n }\n\n // Prefer the gid that came back with the export. Tag\n // map lookup is the slow path and only needed when the\n // server didn't include gid (older instance / fallback).\n let entityGid: number | null = variable.gid ?? null;\n if (entityGid === null) {\n try {\n await nativeClient.initTagMap();\n const tag = await nativeClient.getVariable(variable.name);\n entityGid = tag.id;\n } catch {\n // Tag map lookup optional \u2014 continue without GID\n }\n }\n\n return successResponse({\n tenant,\n variable: {\n name: variable.name,\n entityGid,\n description: variable.description,\n formula: variable.formula,\n dimensions: variable.tables || [],\n rollupType: variable.rollupType,\n dataType: variable.dataType,\n numberFormat: variable.numberFormat,\n readonly: variable.readonly,\n calculateOnDemand: variable.calculateOnDemand,\n folderPath: variable.folderPath,\n },\n });\n } catch (error) {\n return errorResponse(`Get variable failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_evaluate_formula - Evaluate a formula expression\n server.tool(\n 'farseer_evaluate_formula',\n `Evaluate a formula expression in a Farseer tenant.\n\nThe formula can be a variable name or a calculation expression.\nVariable names with spaces or special characters (e.g., \"P&L\", \"New Variable2\") are\nautomatically quoted for the backend formula parser \u2014 just pass the plain name.\nFilters narrow the evaluation to specific dimension members.\n\nExample: evaluate \"Revenue\" with filters [[\"Years\",\"Y2025\"],[\"Months\",\"M1\"]]\n\nReturns the computed value along with cell metadata (readonly, calculated, frozen).`,\n evaluateFormulaSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { formula: string; filters?: Array<Array<string>> }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n // Auto-wrap variable names that contain special characters (spaces, &, etc.)\n // but leave actual formula expressions (with operators, parentheses) untouched.\n // The backend formula parser requires double-quoted identifiers for names with special chars.\n let formula = params.formula;\n const isSimpleIdentifier = !formula.startsWith('\"') && !/[+\\-*/()>,<!=]/.test(formula);\n if (isSimpleIdentifier && /[\\s&]/.test(formula)) {\n formula = `\"${formula}\"`;\n }\n\n const evaluateRequest = {\n filters: params.filters || [],\n cellQueries: [{ type: 'VARIABLE' as const, formula }],\n };\n\n const results = await nativeClient.evaluator.evaluate(evaluateRequest);\n\n return successResponse({\n tenant,\n formula: params.formula,\n filters: params.filters || [],\n results: results.map((r) => ({\n value: r.value,\n readonly: r.readonly,\n calculated: r.calculated,\n frozen: r.frozen,\n goal: r.goal,\n })),\n });\n } catch (error) {\n return errorResponse(`Evaluate formula failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_list_dimension_members - List members of a dimension table\n server.tool(\n 'farseer_list_dimension_members',\n `List all members of a specific dimension table.\n\nUses initTagMap() to load the model's tag map, then retrieves members for the specified table.\nReturns member IDs, names, and parent relationships.\n\nFor large tables (500+ members), automatically exports to a CSV file and returns the file path\ninstead of inline data, to avoid overwhelming the context window.`,\n listDimensionMembersSchema,\n async (params: { tableName: string; limit?: number }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n const members = await nativeClient.getDimensionMembersForTable(params.tableName);\n\n const CSV_THRESHOLD = 500;\n const limit = params.limit || members.length;\n const sliced = members.slice(0, limit);\n\n // Large result \u2014 export to CSV file\n if (sliced.length >= CSV_THRESHOLD) {\n const csvLines = ['id,name,parentId'];\n for (const m of sliced) {\n const name =\n m.name.includes(',') || m.name.includes('\"') ? `\"${m.name.replace(/\"/g, '\"\"')}\"` : m.name;\n csvLines.push(`${m.id},${name},${m.ParentId ?? ''}`);\n }\n const tmpDir = os.tmpdir();\n const safeName = params.tableName.replace(/[^a-zA-Z0-9_-]/g, '_');\n const csvPath = path.join(tmpDir, `farseer_${tenant}_${safeName}_members.csv`);\n fs.writeFileSync(csvPath, csvLines.join('\\n'), 'utf-8');\n\n return successResponse({\n tenant,\n tableName: params.tableName,\n totalMembers: members.length,\n returned: sliced.length,\n exportedToCsv: csvPath,\n message: `Table has ${members.length} members \u2014 exported to CSV file. Use Read tool to inspect the file.`,\n sampleMembers: sliced.slice(0, 10).map((m) => ({\n id: m.id,\n name: m.name,\n parentId: m.ParentId,\n })),\n });\n }\n\n // Small result \u2014 return inline\n const result = sliced.map((m) => ({\n id: m.id,\n name: m.name,\n parentId: m.ParentId,\n }));\n\n return successResponse({\n tenant,\n tableName: params.tableName,\n totalMembers: members.length,\n returned: result.length,\n members: result,\n });\n } catch (error) {\n return errorResponse(\n `List dimension members failed: ${await formatClientError(error)}`,\n 'NETWORK_ERROR',\n );\n }\n },\n );\n\n // farseer_manage_dimension_members - Create or delete dimension members\n server.tool(\n 'farseer_manage_dimension_members',\n `Create or delete a dimension member in a Farseer tenant.\n\nActions:\n- \"create\": Creates a new member in the specified dimension table.\n Optionally set a parent member for hierarchical tables.\n Set compound=true with a formula to create a compound (calculated) member\n (e.g., for AC Period / FC Period filters on variance rows).\n- \"delete\": Deletes an existing member by name from the specified table.\n\nWARNING: Delete is destructive and may affect data. Use with caution.`,\n manageDimensionMembersSchema,\n async (params: {\n action: 'create' | 'delete';\n tableName: string;\n memberName: string;\n parentMemberName?: string;\n compound?: boolean;\n formula?: string;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n\n if (params.action === 'create') {\n const table = await nativeClient.getDimensionTable(params.tableName);\n\n const createEntity: any = {\n type: EntityType.DimensionMember,\n meta: { name: params.memberName },\n relations: {\n parent: {\n key: { id: table.id, type: EntityType.DimensionTable },\n order: 0,\n },\n },\n dimensionMember: { data: {} },\n };\n\n if (params.parentMemberName) {\n const parentMember = await nativeClient.getDimensionMember(\n params.tableName,\n params.parentMemberName,\n );\n createEntity.relations.parent = {\n key: { id: parentMember.id, type: EntityType.DimensionMember },\n order: 0,\n };\n }\n\n // Add compound calculation if requested\n if (params.compound) {\n createEntity.calculation = {\n type: 'COMPOUND',\n formula: params.formula || '',\n };\n }\n\n const result = await nativeClient.entities.mutate({ created: [createEntity] });\n\n return successResponse({\n tenant,\n action: 'created',\n tableName: params.tableName,\n memberName: params.memberName,\n parentMemberName: params.parentMemberName || null,\n result,\n });\n } else {\n const member = await nativeClient.getDimensionMember(params.tableName, params.memberName);\n\n await nativeClient.entities.mutate({\n deleted: [{ id: member.id, type: EntityType.DimensionMember }],\n });\n\n return successResponse({\n tenant,\n action: 'deleted',\n tableName: params.tableName,\n memberName: params.memberName,\n memberId: member.id,\n });\n }\n } catch (error) {\n return errorResponse(\n `Manage dimension member failed: ${await formatClientError(error)}`,\n 'NETWORK_ERROR',\n );\n }\n },\n );\n\n // farseer_create_table - Create a new dimension table\n server.tool(\n 'farseer_create_table',\n `Create a new dimension table in a Farseer tenant.\n\nDimension tables define the structure of data (e.g., Product, Region, Compound Members).\nCreates an empty table that you can then add members to with farseer_manage_dimension_members.`,\n {\n name: z.string().describe('Dimension table name'),\n folderPath: z\n .array(z.string())\n .optional()\n .describe('Folder path (e.g., [\"Dimensions\"]). Uses create + move.'),\n },\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { name: string; folderPath?: string[] }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n\n const createEntity: any = {\n type: EntityType.DimensionTable,\n meta: { name: params.name, description: null },\n };\n\n // Resolve target folder and set relations.folder for direct placement\n if (params.folderPath && params.folderPath.length > 0) {\n const placed = await folderFor(nativeClient, params.folderPath);\n if ('error' in placed) {\n return placed.error;\n }\n if (placed.folderId) {\n createEntity.relations = {\n folder: { key: { id: placed.folderId, type: EntityType.Folder }, order: 0 },\n };\n }\n }\n\n const result = await nativeClient.entities.mutate({ created: [createEntity] });\n const created = (result as any).created?.[0];\n\n return successResponse({\n tenant,\n action: 'created',\n table: {\n id: created?.id,\n name: params.name,\n },\n message: `Dimension table \"${params.name}\" created`,\n });\n } catch (error) {\n return errorResponse(`Create table failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_create_variable - Create a new variable\n server.tool(\n 'farseer_create_variable',\n `Create a new variable in a Farseer tenant.\n\nCreates a variable with the specified name, dimension tables, formula, rollup type, and data type.\nDimension table names are resolved to their internal IDs automatically.\n\nExample:\n{\n \"name\": \"Revenue Forecast\",\n \"dimensions\": [\"Product\", \"Years\", \"Months\"],\n \"formula\": \"Revenue * 1.1\",\n \"rollupType\": \"Sum\",\n \"dataType\": \"Decimal\"\n}`,\n createVariableSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: {\n name: string;\n dimensions?: string[];\n formula?: string;\n rollupType?: string;\n dataType?: string;\n description?: string;\n readonly?: boolean;\n measure?: boolean;\n numberFormat?: Record<string, any>;\n folderPath?: string[];\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n\n // Resolve dimension table names to IDs\n const tableGids: number[] = [];\n if (params.dimensions) {\n for (const tableName of params.dimensions) {\n const table = await nativeClient.getDimensionTable(tableName);\n tableGids.push(table.id);\n }\n }\n\n // Normalize rollupType and dataType to match API expected values\n const rollupType = normalizeRollupType(params.rollupType || 'SUM');\n const dataType = (params.dataType || 'DECIMAL').toUpperCase();\n\n const createEntity: any = {\n type: EntityType.Variable,\n meta: {\n name: params.name,\n description: params.description || null,\n },\n variable: {\n tableGids,\n rollupType,\n dataType,\n readonly: params.readonly || false,\n measure: params.measure || false,\n },\n };\n\n if (params.formula) {\n createEntity.calculation = { formula: params.formula };\n }\n\n if (params.numberFormat) {\n createEntity.numberFormat = params.numberFormat;\n }\n\n // Resolve target folder and set relations.folder for direct placement\n if (params.folderPath && params.folderPath.length > 0) {\n const placed = await folderFor(nativeClient, params.folderPath);\n if ('error' in placed) {\n return placed.error;\n }\n if (placed.folderId) {\n createEntity.relations = {\n folder: { key: { id: placed.folderId, type: EntityType.Folder }, order: 0 },\n };\n }\n }\n\n const result = await nativeClient.entities.mutate({ created: [createEntity] });\n\n return successResponse({\n tenant,\n action: 'created',\n variable: params.name,\n dimensions: params.dimensions || [],\n result,\n });\n } catch (error) {\n return errorResponse(`Create variable failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_update_variable - Update an existing variable\n server.tool(\n 'farseer_update_variable',\n `Update an existing variable in a Farseer tenant.\n\nResolves the variable by name and updates the specified fields.\nOnly provided fields are updated; omitted fields remain unchanged.\n\nUpdatable fields:\n- newName: Rename the variable\n- dimensions: Change which dimension tables the variable spans (replaces all existing dimensions)\n- formula: Change the calculation formula (supports $GID syntax like \"$155-$297\")\n- rollupType: Change aggregation method (Sum, Average, Min, Max, etc.)\n- description: Change the variable description\n- readonly: Set or clear read-only status\n- polarity: Set number polarity (POSITIVE or NEGATIVE)\n- numberFormat: Full number format config (type, decimals, polarity, unit, currency, etc.)`,\n updateVariableSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: {\n name: string;\n newName?: string;\n dimensions?: string[];\n formula?: string;\n rollupType?: string;\n description?: string;\n readonly?: boolean;\n polarity?: 'POSITIVE' | 'NEGATIVE';\n numberFormat?: Record<string, any>;\n }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n const variable = await nativeClient.getVariable(params.name);\n\n // Fetch full current entity - EntityUpdate requires ALL VariableComponent fields\n const currentEntity = await nativeClient.entities.getSingle(variable.id, EntityType.Variable);\n const current = currentEntity as any;\n\n // Build update with full variable component (backend requires all fields)\n const currentVar = current.variable || {};\n const updateEntity: any = {\n id: variable.id,\n type: EntityType.Variable,\n meta: {\n name: params.newName || variable.name,\n description:\n params.description !== undefined ? params.description : (current.meta?.description ?? null),\n },\n variable: {\n notes: currentVar.notes ?? null,\n tableGids: currentVar.tableGids || [],\n memberGids: currentVar.memberGids || [],\n rollupType: currentVar.rollupType || 'SUM',\n dataType: currentVar.dataType || 'DECIMAL',\n topDownMapping: currentVar.topDownMapping ?? null,\n measure: currentVar.measure || false,\n readonly: currentVar.readonly || false,\n calculateOnDemand: currentVar.calculateOnDemand || false,\n zConstraint: currentVar.zConstraint || false,\n optimizeCalculation: currentVar.optimizeCalculation ?? true,\n // referencedBy is readOnly - do NOT send in update requests\n },\n };\n\n // Override only changed fields\n if (params.dimensions) {\n const tableGids: number[] = [];\n for (const tableName of params.dimensions) {\n const table = await nativeClient.getDimensionTable(tableName);\n tableGids.push(table.id);\n }\n updateEntity.variable.tableGids = tableGids;\n }\n if (params.rollupType) {\n updateEntity.variable.rollupType = normalizeRollupType(params.rollupType);\n }\n if (params.readonly !== undefined) {\n updateEntity.variable.readonly = params.readonly;\n }\n\n // Preserve existing calculation unless explicitly changing formula.\n // Always include calculation.type (required by backend, e.g. 'VARIABLE').\n const currentCalc = current.calculation;\n if (params.formula !== undefined) {\n updateEntity.calculation = {\n formula: params.formula,\n type: currentCalc?.type || 'VARIABLE',\n };\n } else if (currentCalc) {\n updateEntity.calculation = currentCalc;\n }\n\n // Handle numberFormat / polarity updates\n if (params.numberFormat || params.polarity) {\n const currentFormat = current.numberFormat || {};\n updateEntity.numberFormat = {\n ...currentFormat,\n ...(params.numberFormat || {}),\n };\n // If polarity is set separately, override it in the format\n if (params.polarity) {\n updateEntity.numberFormat.polarity = params.polarity;\n }\n }\n\n const result = await nativeClient.entities.mutate({ updated: [updateEntity] });\n\n return successResponse({\n tenant,\n action: 'updated',\n variable: params.name,\n variableId: variable.id,\n result,\n });\n } catch (error) {\n return errorResponse(`Update variable failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_delete_variable_data - Delete all data for a variable\n server.tool(\n 'farseer_delete_variable_data',\n `Delete ALL data for a variable in a Farseer tenant.\n\nWARNING: This is destructive and cannot be undone. It removes all cell values\nfor the specified variable across all dimensions and time periods.\n\nUse this to clear old template data or reset a variable before re-importing.`,\n deleteVariableDataSchema,\n async (params: { variableName: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n const variable = await nativeClient.getVariable(params.variableName);\n\n await nativeClient.entities.deleteData({\n id: variable.id,\n type: EntityType.Variable,\n });\n\n return successResponse({\n tenant,\n action: 'deleted_data',\n variable: params.variableName,\n variableId: variable.id,\n message: `All data deleted for variable \"${params.variableName}\"`,\n });\n } catch (error) {\n return errorResponse(`Delete variable data failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_delete_variable - Delete a variable\n server.tool(\n 'farseer_delete_variable',\n `Delete a variable from a Farseer tenant.\n\nResolves the variable by name and permanently deletes it along with all its data.\n\nWARNING: This is destructive and cannot be undone.`,\n deleteVariableSchema,\n async (params: { variableName: string }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { tenant, native: nativeClient } = gate.session;\n\n try {\n await nativeClient.initTagMap();\n const variable = await nativeClient.getVariable(params.variableName);\n\n await nativeClient.entities.mutate({\n deleted: [{ id: variable.id, type: EntityType.Variable }],\n });\n\n return successResponse({\n tenant,\n action: 'deleted',\n variable: params.variableName,\n variableId: variable.id,\n message: `Variable \"${params.variableName}\" deleted`,\n });\n } catch (error) {\n return errorResponse(`Delete variable failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AACpB,qBAA+B;AAC/B,qBAA+C;AAC/C,4BAAkC;AAClC,yBAAyD;AACzD,cAAyB;AACzB,4BAA2B;AAG3B,MAAM,kBAA0C;AAAA,EAC5C,KAAK;AAAA,EACL,SAAS;AAA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AAM,WAAW,MAAM,aAAa,YAAY,OAAO,YAAY;AAEnE,cAAM,aAAa,SAAS,OAAO;AAAA,UAC/B,SAAS,CAAC,EAAE,IAAI,SAAS,IAAI,MAAM,iCAAW,SAAS,CAAC;AAAA,QAC5D,CAAC;AAED,mBAAO,gCAAgB;AAAA,UACnB;AAAA,UACA,QAAQ;AAAA,UACR,UAAU,OAAO;AAAA,UACjB,YAAY,SAAS;AAAA,UACrB,SAAS,aAAa,OAAO,YAAY;AAAA,QAC7C,CAAC;AAAA,MACL,SAAS,OAAO;AACZ,mBAAO,8BAAc,2BAA2B,UAAM,yCAAkB,KAAK,CAAC,IAAI,eAAe;AAAA,MACrG;AAAA,IACJ;AAAA,EACJ;AACJ;",
6
6
  "names": []
7
7
  }
@@ -25,7 +25,7 @@ __export(session_exports, {
25
25
  });
26
26
  module.exports = __toCommonJS(session_exports);
27
27
  var import_configService = require("../../services/configService");
28
- var import_farseerFactory = require("../../services/farseerFactory");
28
+ var import_credentials = require("../../services/credentials");
29
29
  var import_preflight = require("../../services/preflight");
30
30
  var import_helpers = require("./helpers");
31
31
  var import_tenantPin = require("./tenantPin");
@@ -58,7 +58,7 @@ async function requireSession() {
58
58
  return { ok: false, response: (0, import_helpers.tenantRequiredResponse)() };
59
59
  }
60
60
  if (validated?.pin === pin && validated.credentials === credentialState(pin.tenant, validated.passedOverLogin)) {
61
- const auth = await (0, import_farseerFactory.refreshAuth)(validated.auth);
61
+ const auth = await (0, import_credentials.refreshAuth)(validated.auth);
62
62
  if (!auth) {
63
63
  validated = void 0;
64
64
  return { ok: false, response: (0, import_helpers.authRequiredResponse)(pin.tenant) };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/mcp/utils/session.ts"],
4
- "sourcesContent": ["/**\n * The tenant guard for MCP tools: the checks a CLI command runs, minus the exit.\n *\n * The pin cannot change for the life of the process, so the verdict is reached\n * once per credential. What is kept is the verdict and the credential, not a\n * built client \u2014 a browser token expires long before a long-lived server does.\n */\nimport {\n getCredential,\n getUserAuth,\n isUserAuthValid,\n type CurrentCheckout,\n type UserAuth,\n} from '../../services/configService';\nimport { refreshAuth, type ResolvedAuth } from '../../services/farseerFactory';\nimport { openTenantSession, sessionFrom, type SessionWarning, type TenantSession } from '../../services/preflight';\nimport { authRequiredResponse, describeSessionFailure, tenantRequiredResponse } from './helpers';\nimport type { McpErrorResponse } from './helpers';\nimport { getTenantPin } from './tenantPin';\n\nexport type SessionResult = { ok: true; session: TenantSession } | { ok: false; response: McpErrorResponse };\n\n// Safe only because each server is a stdio process with a single client, on the\n// same terms as the pin it mirrors.\nlet validated:\n | {\n pin: CurrentCheckout;\n auth: ResolvedAuth;\n credentials: string;\n passedOverLogin: boolean;\n warning?: SessionWarning;\n }\n | undefined;\n\n/**\n * What the credential choice was made from, as one comparable value.\n *\n * A browser login is identified by its Keycloak session (`sid`), which token\n * rotation keeps and a new `farseer login` replaces \u2014 so the ordinary case, a\n * token renewed about once a minute, never re-runs the guard.\n *\n * A login the guard passed over for a key is the exception. Its refresh token\n * already failed, so nothing can rotate it, and a login made to recover can land\n * in the same Keycloak session when the browser still holds one. There the\n * refresh token itself is the identity: only replacing the login changes it.\n *\n * Without both, a key that stops working is reused until the process restarts,\n * while `farseer_whoami`, which reads the config directly, reports the new login\n * as valid.\n */\nfunction credentialState(tenant: string, passedOverLogin: boolean): string {\n const credential = getCredential(tenant);\n const key = credential ? `${credential.basePath}|${credential.tenantId}|${credential.apiKey}` : 'none';\n const login = getUserAuth();\n const who = !login ? 'none' : passedOverLogin ? `unusable:${login.refreshToken}` : `session:${loginSession(login)}`;\n return `${who}|${key}`;\n}\n\n/**\n * Read straight after a decision, when the guard has just tried to renew the\n * login: one that is still expired is one the refresh could not renew.\n */\nfunction passedOver(auth: ResolvedAuth): boolean {\n return auth.kind === 'apiKey' && !!getUserAuth() && !isUserAuthValid();\n}\n\nfunction loginSession(login: UserAuth): string {\n for (const token of [login.refreshToken, login.accessToken]) {\n try {\n const sid = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf-8')).sid;\n if (typeof sid === 'string' && sid) {\n return sid;\n }\n } catch {\n // Not a JWT; try the other token.\n }\n }\n // Unreadable, so the token itself: re-decides on every rotation \u2014 more often\n // than needed, never less.\n return login.refreshToken;\n}\n\n/** The gate every tool that talks to a tenant goes through. */\nexport async function requireSession(): Promise<SessionResult> {\n const pin = getTenantPin();\n if (!pin) {\n return { ok: false, response: tenantRequiredResponse() };\n }\n\n // Identity, not value: a different object means a different binding, and an\n // extra check is the safe way to be wrong. The credentials are part of the\n // key for the same reason \u2014 a verdict reached over one says nothing about\n // another. The pin survives either way; only the credential is re-decided.\n if (validated?.pin === pin && validated.credentials === credentialState(pin.tenant, validated.passedOverLogin)) {\n const auth = await refreshAuth(validated.auth);\n if (!auth) {\n // Drop the verdict rather than reuse a credential we can no longer mint.\n validated = undefined;\n return { ok: false, response: authRequiredResponse(pin.tenant) };\n }\n return { ok: true, session: sessionFrom(pin.organisation, pin.tenant, auth) };\n }\n\n const outcome = await openTenantSession(pin.organisation, pin.tenant);\n if (!outcome.ok) {\n return { ok: false, response: describeSessionFailure(outcome.failure, LOCKED_REMEDY) };\n }\n\n remember(pin, outcome.auth, outcome.warning);\n return { ok: true, session: sessionFrom(outcome.organisation, outcome.tenant, outcome.auth) };\n}\n\n/** Adopt a verdict reached elsewhere \u2014 `farseer_select_tenant` validates before it binds. */\nexport function rememberSession(pin: CurrentCheckout, auth: ResolvedAuth, warning?: SessionWarning): void {\n remember(pin, auth, warning);\n}\n\nfunction remember(pin: CurrentCheckout, auth: ResolvedAuth, warning?: SessionWarning): void {\n const passedOverLogin = passedOver(auth);\n validated = { pin, auth, credentials: credentialState(pin.tenant, passedOverLogin), passedOverLogin, warning };\n}\n\n/** Reported by `farseer_whoami`: true about this session, but not a failure. */\nexport function getSessionWarning(): SessionWarning | undefined {\n const pin = getTenantPin();\n return validated?.pin === pin ? validated?.warning : undefined;\n}\n\nexport function resetSessionCache(): void {\n validated = undefined;\n}\n\n// Past the lock there is no in-session fix.\nconst LOCKED_REMEDY =\n 'This session is locked to that pair for its lifetime \u2014 start a new server with the right organisation (--org, or FARSEER_ORG).';\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,2BAMO;AACP,4BAA+C;AAC/C,uBAAwF;AACxF,qBAAqF;AAErF,uBAA6B;AAM7B,IAAI;AA0BJ,SAAS,gBAAgB,QAAgB,iBAAkC;AACvE,QAAM,iBAAa,oCAAc,MAAM;AACvC,QAAM,MAAM,aAAa,GAAG,WAAW,QAAQ,IAAI,WAAW,QAAQ,IAAI,WAAW,MAAM,KAAK;AAChG,QAAM,YAAQ,kCAAY;AAC1B,QAAM,MAAM,CAAC,QAAQ,SAAS,kBAAkB,YAAY,MAAM,YAAY,KAAK,WAAW,aAAa,KAAK,CAAC;AACjH,SAAO,GAAG,GAAG,IAAI,GAAG;AACxB;AAMA,SAAS,WAAW,MAA6B;AAC7C,SAAO,KAAK,SAAS,YAAY,CAAC,KAAC,kCAAY,KAAK,KAAC,sCAAgB;AACzE;AAEA,SAAS,aAAa,OAAyB;AAC3C,aAAW,SAAS,CAAC,MAAM,cAAc,MAAM,WAAW,GAAG;AACzD,QAAI;AACA,YAAM,MAAM,KAAK,MAAM,OAAO,KAAK,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,WAAW,EAAE,SAAS,OAAO,CAAC,EAAE;AACxF,UAAI,OAAO,QAAQ,YAAY,KAAK;AAChC,eAAO;AAAA,MACX;AAAA,IACJ,QAAQ;AAAA,IAER;AAAA,EACJ;AAGA,SAAO,MAAM;AACjB;AAGA,eAAsB,iBAAyC;AAC3D,QAAM,UAAM,+BAAa;AACzB,MAAI,CAAC,KAAK;AACN,WAAO,EAAE,IAAI,OAAO,cAAU,uCAAuB,EAAE;AAAA,EAC3D;AAMA,MAAI,WAAW,QAAQ,OAAO,UAAU,gBAAgB,gBAAgB,IAAI,QAAQ,UAAU,eAAe,GAAG;AAC5G,UAAM,OAAO,UAAM,mCAAY,UAAU,IAAI;AAC7C,QAAI,CAAC,MAAM;AAEP,kBAAY;AACZ,aAAO,EAAE,IAAI,OAAO,cAAU,qCAAqB,IAAI,MAAM,EAAE;AAAA,IACnE;AACA,WAAO,EAAE,IAAI,MAAM,aAAS,8BAAY,IAAI,cAAc,IAAI,QAAQ,IAAI,EAAE;AAAA,EAChF;AAEA,QAAM,UAAU,UAAM,oCAAkB,IAAI,cAAc,IAAI,MAAM;AACpE,MAAI,CAAC,QAAQ,IAAI;AACb,WAAO,EAAE,IAAI,OAAO,cAAU,uCAAuB,QAAQ,SAAS,aAAa,EAAE;AAAA,EACzF;AAEA,WAAS,KAAK,QAAQ,MAAM,QAAQ,OAAO;AAC3C,SAAO,EAAE,IAAI,MAAM,aAAS,8BAAY,QAAQ,cAAc,QAAQ,QAAQ,QAAQ,IAAI,EAAE;AAChG;AAGO,SAAS,gBAAgB,KAAsB,MAAoB,SAAgC;AACtG,WAAS,KAAK,MAAM,OAAO;AAC/B;AAEA,SAAS,SAAS,KAAsB,MAAoB,SAAgC;AACxF,QAAM,kBAAkB,WAAW,IAAI;AACvC,cAAY,EAAE,KAAK,MAAM,aAAa,gBAAgB,IAAI,QAAQ,eAAe,GAAG,iBAAiB,QAAQ;AACjH;AAGO,SAAS,oBAAgD;AAC5D,QAAM,UAAM,+BAAa;AACzB,SAAO,WAAW,QAAQ,MAAM,WAAW,UAAU;AACzD;AAEO,SAAS,oBAA0B;AACtC,cAAY;AAChB;AAGA,MAAM,gBACF;",
4
+ "sourcesContent": ["/**\n * The tenant guard for MCP tools: the checks a CLI command runs, minus the exit.\n *\n * The pin cannot change for the life of the process, so the verdict is reached\n * once per credential. What is kept is the verdict and the credential, not a\n * built client \u2014 a browser token expires long before a long-lived server does.\n */\n\nimport {\n getCredential,\n getUserAuth,\n isUserAuthValid,\n type CurrentCheckout,\n type UserAuth,\n} from '../../services/configService';\nimport { refreshAuth } from '../../services/credentials';\nimport type { ResolvedAuth } from '../../services/farseerService';\nimport { openTenantSession, sessionFrom, type SessionWarning, type TenantSession } from '../../services/preflight';\nimport { authRequiredResponse, describeSessionFailure, tenantRequiredResponse } from './helpers';\nimport type { McpErrorResponse } from './helpers';\nimport { getTenantPin } from './tenantPin';\n\nexport type SessionResult = { ok: true; session: TenantSession } | { ok: false; response: McpErrorResponse };\n\n// Safe only because each server is a stdio process with a single client, on the\n// same terms as the pin it mirrors.\nlet validated:\n | {\n pin: CurrentCheckout;\n auth: ResolvedAuth;\n credentials: string;\n passedOverLogin: boolean;\n warning?: SessionWarning;\n }\n | undefined;\n\n/**\n * What the credential choice was made from, as one comparable value.\n *\n * A browser login is identified by its Keycloak session (`sid`), which token\n * rotation keeps and a new `farseer login` replaces \u2014 so the ordinary case, a\n * token renewed about once a minute, never re-runs the guard.\n *\n * A login the guard passed over for a key is the exception. Its refresh token\n * already failed, so nothing can rotate it, and a login made to recover can land\n * in the same Keycloak session when the browser still holds one. There the\n * refresh token itself is the identity: only replacing the login changes it.\n *\n * Without both, a key that stops working is reused until the process restarts,\n * while `farseer_whoami`, which reads the config directly, reports the new login\n * as valid.\n */\nfunction credentialState(tenant: string, passedOverLogin: boolean): string {\n const credential = getCredential(tenant);\n const key = credential ? `${credential.basePath}|${credential.tenantId}|${credential.apiKey}` : 'none';\n const login = getUserAuth();\n const who = !login ? 'none' : passedOverLogin ? `unusable:${login.refreshToken}` : `session:${loginSession(login)}`;\n return `${who}|${key}`;\n}\n\n/**\n * Read straight after a decision, when the guard has just tried to renew the\n * login: one that is still expired is one the refresh could not renew.\n */\nfunction passedOver(auth: ResolvedAuth): boolean {\n return auth.kind === 'apiKey' && !!getUserAuth() && !isUserAuthValid();\n}\n\nfunction loginSession(login: UserAuth): string {\n for (const token of [login.refreshToken, login.accessToken]) {\n try {\n const sid = JSON.parse(Buffer.from(token.split('.')[1], 'base64url').toString('utf-8')).sid;\n if (typeof sid === 'string' && sid) {\n return sid;\n }\n } catch {\n // Not a JWT; try the other token.\n }\n }\n // Unreadable, so the token itself: re-decides on every rotation \u2014 more often\n // than needed, never less.\n return login.refreshToken;\n}\n\n/** The gate every tool that talks to a tenant goes through. */\nexport async function requireSession(): Promise<SessionResult> {\n const pin = getTenantPin();\n if (!pin) {\n return { ok: false, response: tenantRequiredResponse() };\n }\n\n // Identity, not value: a different object means a different binding, and an\n // extra check is the safe way to be wrong. The credentials are part of the\n // key for the same reason \u2014 a verdict reached over one says nothing about\n // another. The pin survives either way; only the credential is re-decided.\n if (validated?.pin === pin && validated.credentials === credentialState(pin.tenant, validated.passedOverLogin)) {\n const auth = await refreshAuth(validated.auth);\n if (!auth) {\n // Drop the verdict rather than reuse a credential we can no longer mint.\n validated = undefined;\n return { ok: false, response: authRequiredResponse(pin.tenant) };\n }\n return { ok: true, session: sessionFrom(pin.organisation, pin.tenant, auth) };\n }\n\n const outcome = await openTenantSession(pin.organisation, pin.tenant);\n if (!outcome.ok) {\n return { ok: false, response: describeSessionFailure(outcome.failure, LOCKED_REMEDY) };\n }\n\n remember(pin, outcome.auth, outcome.warning);\n return { ok: true, session: sessionFrom(outcome.organisation, outcome.tenant, outcome.auth) };\n}\n\n/** Adopt a verdict reached elsewhere \u2014 `farseer_select_tenant` validates before it binds. */\nexport function rememberSession(pin: CurrentCheckout, auth: ResolvedAuth, warning?: SessionWarning): void {\n remember(pin, auth, warning);\n}\n\nfunction remember(pin: CurrentCheckout, auth: ResolvedAuth, warning?: SessionWarning): void {\n const passedOverLogin = passedOver(auth);\n validated = { pin, auth, credentials: credentialState(pin.tenant, passedOverLogin), passedOverLogin, warning };\n}\n\n/** Reported by `farseer_whoami`: true about this session, but not a failure. */\nexport function getSessionWarning(): SessionWarning | undefined {\n const pin = getTenantPin();\n return validated?.pin === pin ? validated?.warning : undefined;\n}\n\nexport function resetSessionCache(): void {\n validated = undefined;\n}\n\n// Past the lock there is no in-session fix.\nconst LOCKED_REMEDY =\n 'This session is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UAAU,IAAI;AAC7C,QAAI,CAAC,MAAM;AAEP,kBAAY;AACZ,aAAO,EAAE,IAAI,OAAO,cAAU,qCAAqB,IAAI,MAAM,EAAE;AAAA,IACnE;AACA,WAAO,EAAE,IAAI,MAAM,aAAS,8BAAY,IAAI,cAAc,IAAI,QAAQ,IAAI,EAAE;AAAA,EAChF;AAEA,QAAM,UAAU,UAAM,oCAAkB,IAAI,cAAc,IAAI,MAAM;AACpE,MAAI,CAAC,QAAQ,IAAI;AACb,WAAO,EAAE,IAAI,OAAO,cAAU,uCAAuB,QAAQ,SAAS,aAAa,EAAE;AAAA,EACzF;AAEA,WAAS,KAAK,QAAQ,MAAM,QAAQ,OAAO;AAC3C,SAAO,EAAE,IAAI,MAAM,aAAS,8BAAY,QAAQ,cAAc,QAAQ,QAAQ,QAAQ,IAAI,EAAE;AAChG;AAGO,SAAS,gBAAgB,KAAsB,MAAoB,SAAgC;AACtG,WAAS,KAAK,MAAM,OAAO;AAC/B;AAEA,SAAS,SAAS,KAAsB,MAAoB,SAAgC;AACxF,QAAM,kBAAkB,WAAW,IAAI;AACvC,cAAY,EAAE,KAAK,MAAM,aAAa,gBAAgB,IAAI,QAAQ,eAAe,GAAG,iBAAiB,QAAQ;AACjH;AAGO,SAAS,oBAAgD;AAC5D,QAAM,UAAM,+BAAa;AACzB,SAAO,WAAW,QAAQ,MAAM,WAAW,UAAU;AACzD;AAEO,SAAS,oBAA0B;AACtC,cAAY;AAChB;AAGA,MAAM,gBACF;",
6
6
  "names": []
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/services/appSyncService.ts"],
4
- "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { RemoteApp, AppArgument, AppArgumentDataType } from './farseerApi';\nimport { IFarseerClient } from './farseerFactory';\nimport { getTenantAppsDir, ensureDirectoryExists, fetchWithConcurrency } from '../utils/helpers';\nimport { logger } from '../utils/logger';\nimport { formatClientError } from '../utils/errorFormatter';\n\n// Local app config format (stored in apps/*.json) \u2014 mirrors AppArgument so\n// pull/push round-trips don't drop any axis.\nexport interface LocalAppConfig {\n name: string;\n description: string;\n entrypoint: string | null; // Script filename (e.g., \"index.ts\")\n arguments: {\n name: string;\n // `dataType` defaults to 'string' on legacy configs that pre-date typed\n // parameters. Without round-tripping the full axes (`dataType`,\n // `fixed`, `options`), a pull \u2192 push cycle silently demoted a boolean /\n // dropdown / locked arg back to a plain string variable.\n dataType?: AppArgumentDataType;\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n }[];\n _remote?: {\n id: number;\n reference: string;\n };\n}\n\nexport interface AppSyncResult {\n created: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n}\n\nexport interface AppSyncStatus {\n newLocal: string[]; // Local apps not on remote\n newRemote: string[]; // Remote apps not locally\n modified: string[]; // Apps that differ\n synced: string[]; // Apps in sync\n}\n\n/**\n * Sanitize Croatian diacritics and other special characters to ASCII equivalents\n */\nfunction sanitizeDiacritics(text: string): string {\n const diacriticMap: Record<string, string> = {\n // Croatian\n \u010D: 'c',\n \u010C: 'C',\n \u0107: 'c',\n \u0106: 'C',\n \u0161: 's',\n \u0160: 'S',\n \u017E: 'z',\n \u017D: 'Z',\n \u0111: 'd',\n \u0110: 'D',\n // German/Other common\n \u00E4: 'a',\n \u00C4: 'A',\n \u00F6: 'o',\n \u00D6: 'O',\n \u00FC: 'u',\n \u00DC: 'U',\n \u00DF: 'ss',\n // Polish\n \u0105: 'a',\n \u0104: 'A',\n \u0119: 'e',\n \u0118: 'E',\n \u0142: 'l',\n \u0141: 'L',\n \u0144: 'n',\n \u0143: 'N',\n \u00F3: 'o',\n \u00D3: 'O',\n \u015B: 's',\n \u015A: 'S',\n \u017A: 'z',\n \u0179: 'Z',\n \u017C: 'z',\n \u017B: 'Z',\n // French/Spanish\n \u00E0: 'a',\n \u00E1: 'a',\n \u00E2: 'a',\n \u00E8: 'e',\n \u00E9: 'e',\n \u00EA: 'e',\n \u00EB: 'e',\n \u00EC: 'i',\n \u00ED: 'i',\n \u00EE: 'i',\n \u00EF: 'i',\n \u00F2: 'o',\n \u00F4: 'o',\n \u00F9: 'u',\n \u00FA: 'u',\n \u00FB: 'u',\n \u00F1: 'n',\n \u00D1: 'N',\n \u00E7: 'c',\n \u00C7: 'C',\n };\n\n return text\n .split('')\n .map((char) => diacriticMap[char] || char)\n .join('');\n}\n\n/**\n * Migrate legacy `type: 'variable' | 'constant' | 'boolean' | 'dropdown'` on\n * pre-PR pulls to the orthogonal-axes shape used by `localToUpdate` and\n * `areAppsEqual`. Idempotent \u2014 leaves new-shape entries untouched.\n *\n * Without this, a push immediately after upgrade silently demoted locked\n * args (`type: 'constant'` \u2192 no `fixed`) because the new code ignores the\n * legacy `type` key when building the wire payload. `areAppsEqual` flagged\n * the diff but didn't block, so the silent demote slipped through.\n */\nfunction migrateLegacyArguments(config: { arguments?: unknown[] } & Record<string, unknown>): Record<string, unknown> {\n if (!Array.isArray(config.arguments)) return config as Record<string, unknown>;\n config.arguments = config.arguments.map((raw) => {\n if (raw === null || typeof raw !== 'object') return raw;\n const a = raw as Record<string, unknown>;\n if (a.dataType !== undefined || a.type === undefined) return a;\n const legacyType = a.type;\n const rest: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(a)) {\n if (k !== 'type') rest[k] = v;\n }\n switch (legacyType) {\n case 'constant':\n return { ...rest, dataType: 'string', fixed: true };\n case 'boolean':\n return { ...rest, dataType: 'boolean' };\n case 'dropdown':\n case 'variable':\n default:\n return { ...rest, dataType: 'string' };\n }\n });\n return config as Record<string, unknown>;\n}\n\n/**\n * Service for syncing app configurations between local JSON files and remote Farseer instance\n */\nexport class AppSyncService {\n private api: IFarseerClient;\n private appsDir: string;\n\n constructor(tenant: string, api: IFarseerClient) {\n this.api = api;\n this.appsDir = getTenantAppsDir(tenant);\n }\n\n /**\n * Get filename for an app (keep original name, just sanitize for filesystem)\n */\n private getAppFilename(name: string): string {\n return (\n sanitizeDiacritics(name)\n .replace(/[<>:\"/\\\\|?*]/g, '') // Remove invalid filename characters\n .trim() + '.json'\n );\n }\n\n /**\n * Names of locally-tracked apps the next `pull` would delete because\n * remote no longer has them. Uses only `listApps` (no per-app fetch),\n * so pull can preview deletions for the destructive-action prompt\n * without paying for getStatus's full per-app round-trip.\n *\n * Mirrors the deletion gate in `pull()` (`local._remote && !remoteApps.has(key)`):\n * apps the user never pulled (`_remote` undefined) are kept untouched\n * by pull, so they don't belong in this list.\n */\n async getRemoteDeletions(): Promise<string[]> {\n const localApps = this.loadLocalApps();\n const remoteAppList = await this.api.listApps();\n const remoteNames = new Set(remoteAppList.map((a) => a.name.toLowerCase()));\n const deleted: string[] = [];\n for (const [key, local] of localApps) {\n if (local._remote && !remoteNames.has(key)) {\n deleted.push(local.name);\n }\n }\n return deleted;\n }\n\n /**\n * Load all local app configs\n */\n loadLocalApps(): Map<string, LocalAppConfig> {\n const apps = new Map<string, LocalAppConfig>();\n\n if (!fs.existsSync(this.appsDir)) {\n return apps;\n }\n\n const files = fs.readdirSync(this.appsDir).filter((f) => f.endsWith('.json'));\n\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(this.appsDir, file), 'utf-8');\n const config = migrateLegacyArguments(JSON.parse(content)) as LocalAppConfig;\n apps.set(config.name.toLowerCase(), config);\n } catch {\n // Skip invalid files\n }\n }\n\n return apps;\n }\n\n /**\n * Save a local app config\n */\n saveLocalApp(config: LocalAppConfig): void {\n ensureDirectoryExists(this.appsDir);\n const filename = this.getAppFilename(config.name);\n const filePath = path.join(this.appsDir, filename);\n fs.writeFileSync(filePath, JSON.stringify(config, null, 2), 'utf-8');\n }\n\n /**\n * Delete a local app config\n */\n deleteLocalApp(name: string): boolean {\n const filename = this.getAppFilename(name);\n const filePath = path.join(this.appsDir, filename);\n\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n return true;\n }\n return false;\n }\n\n /**\n * Convert remote app to local config format\n */\n private remoteToLocal(remote: RemoteApp, reference: string): LocalAppConfig {\n const scriptFiles = remote.scriptFiles ?? [];\n const mainScript = scriptFiles.find((s) => s.id === remote.mainScriptFileId);\n\n // \"No default\" canonical shape locally is `defaultValue: ''` (empty\n // string), NOT an omitted key. The OpenAPI schema makes the field\n // optional, so the backend can emit either; if we passed `undefined`\n // through verbatim, a user who added `defaultValue: ''` locally\n // would see `areAppsEqual` say \"match\" (both normalise to '') but\n // the next pull would strip the key again \u2014 the on-disk JSON would\n // oscillate forever and never reach a steady state. type is treated\n // the same way ('variable' is the implicit default), secret only\n // appears when explicitly true on the backend (boolean is a clear\n // tri-state: true/false/unset, and \"unset\" reads as false anyway).\n return {\n name: remote.name,\n description: remote.description || '',\n entrypoint: mainScript?.name || null,\n arguments: remote.expectedArguments.map((a) => {\n // Pin a steady-state shape so two pulls back-to-back don't\n // oscillate. `defaultValue` is normalized to '' when omitted \u2014\n // a user-edited `defaultValue: ''` locally must compare equal\n // to a remote that omits the field. `dataType` defaults to\n // 'string' (the implicit pre-fix shape). All other axes\n // (`fixed`, `options`, `secret`) are only emitted when the\n // remote populated them, to keep the JSON minimal.\n const arg: LocalAppConfig['arguments'][number] = {\n name: a.name,\n defaultValue: a.defaultValue ?? '',\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n }),\n _remote: {\n id: remote.id,\n reference: reference,\n },\n };\n }\n\n /**\n * Check if local and remote app configs are equivalent\n */\n private areAppsEqual(local: LocalAppConfig, remote: RemoteApp): boolean {\n // Compare name\n if (local.name !== remote.name) return false;\n\n // Compare description\n if ((local.description || '') !== (remote.description || '')) return false;\n\n // Compare entrypoint\n const remoteScriptFiles = remote.scriptFiles ?? [];\n const remoteEntrypoint = remoteScriptFiles.find((s) => s.id === remote.mainScriptFileId)?.name || null;\n if (local.entrypoint !== remoteEntrypoint) return false;\n\n // Compare arguments. Order matters here: backend renders args in the\n // saved order in the UI, so we treat reordering as a real change.\n // Missing `dataType` defaults to 'string' (the implicit pre-fix value);\n // missing scalar defaults are normalized so '' vs undefined doesn't\n // show up as a spurious diff. All four axes (dataType, fixed, options,\n // defaultValue, secret) are compared so a pull\u2192push round-trip\n // detects changes on any of them.\n if (local.arguments.length !== remote.expectedArguments.length) return false;\n for (let i = 0; i < local.arguments.length; i++) {\n const l = local.arguments[i];\n const r = remote.expectedArguments[i];\n if (l.name !== r.name) return false;\n if ((l.dataType ?? 'string') !== (r.dataType ?? 'string')) return false;\n if (Boolean(l.fixed) !== Boolean(r.fixed)) return false;\n if (JSON.stringify(l.options ?? []) !== JSON.stringify(r.options ?? [])) return false;\n if ((l.defaultValue ?? '') !== (r.defaultValue ?? '')) return false;\n if (Boolean(l.secret) !== Boolean(r.secret)) return false;\n }\n\n return true;\n }\n\n /**\n * Pull apps from remote and save locally\n */\n async pull(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n logger.dim(`Fetching ${remoteAppList.length} apps in parallel...`);\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item, index) => {\n const app = await this.api.getApp(item.reference);\n // Show progress every 10 apps\n if ((index + 1) % 10 === 0 || index === remoteAppList.length - 1) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write(`\\r Progress: ${index + 1}/${remoteAppList.length} apps`);\n }\n return { app, reference: item.reference };\n },\n 15,\n );\n // Clear progress line\n if (remoteAppList.length > 0) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Process remote apps\n for (const [key, { app, reference }] of remoteApps) {\n const localConfig = this.remoteToLocal(app, reference);\n const existingLocal = localApps.get(key);\n\n if (!existingLocal) {\n // New app from remote\n this.saveLocalApp(localConfig);\n result.created.push(app.name);\n } else if (!this.areAppsEqual(existingLocal, app)) {\n // App changed on remote - update local\n this.saveLocalApp(localConfig);\n result.updated.push(app.name);\n } else {\n result.unchanged.push(app.name);\n }\n }\n\n // Check for apps deleted on remote\n for (const [key, local] of localApps) {\n if (!remoteApps.has(key) && local._remote) {\n // App was synced before but now deleted on remote\n this.deleteLocalApp(local.name);\n result.deleted.push(local.name);\n }\n }\n\n return result;\n }\n\n /**\n * Push local apps to remote\n */\n async push(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Get available scripts for ID lookup\n // Build maps for both path-based and filename-based lookup (backward compatibility)\n const availableScripts = await this.api.getScriptFiles();\n const scriptIdByPath = new Map<string, string>();\n const scriptIdByName = new Map<string, string>();\n\n for (const s of availableScripts) {\n // s.name now contains full path (e.g., \"Scripts/test.ts\")\n const pathKey = s.name.toLowerCase();\n const filenameKey = s.name.split('/').pop()?.toLowerCase() || pathKey;\n\n scriptIdByPath.set(pathKey, s.id);\n // For filename lookup, only set if not already set (first match wins for ambiguous names)\n if (!scriptIdByName.has(filenameKey)) {\n scriptIdByName.set(filenameKey, s.id);\n }\n }\n\n // Helper to find script ID by path or filename\n const findScriptId = (scriptRef: string): string | undefined => {\n const key = scriptRef.toLowerCase();\n // Try exact path match first\n const byPath = scriptIdByPath.get(key);\n if (byPath) return byPath;\n // Try with Scripts/ prefix\n const withPrefix = scriptIdByPath.get(`scripts/${key}`);\n if (withPrefix) return withPrefix;\n // Fall back to filename match\n return scriptIdByName.get(key.split('/').pop() || key);\n };\n\n // Process local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n // New local app - create on remote\n try {\n const created = await this.api.createApp(local.name);\n\n // Update with config (API requires name and description)\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n await this.api.updateApp(created.id.toString(), update, created);\n\n // Update local with remote ID\n local._remote = {\n id: created.id,\n reference: created.id.toString(),\n };\n this.saveLocalApp(local);\n\n result.created.push(local.name);\n } catch (error) {\n logger.error(`Failed to create app ${local.name}: ${await formatClientError(error)}`);\n }\n } else if (!this.areAppsEqual(local, remote.app)) {\n // App differs - update remote\n try {\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n\n await this.api.updateApp(remote.reference, update, remote.app);\n result.updated.push(local.name);\n } catch (error) {\n logger.error(`Failed to update app ${local.name}: ${await formatClientError(error)}`);\n }\n } else {\n result.unchanged.push(local.name);\n }\n }\n\n // Note: We don't auto-delete remote apps when deleted locally\n // User must use \"farseer app delete\" explicitly\n\n return result;\n }\n\n /**\n * Build update payload for API\n */\n private buildUpdatePayload(\n local: LocalAppConfig,\n findScriptId: (scriptRef: string) => string | undefined,\n ): {\n name?: string;\n description?: string;\n expectedArguments?: AppArgument[];\n mainScriptFileId?: string | null;\n } {\n const update: {\n name?: string;\n description?: string;\n expectedArguments?: AppArgument[];\n mainScriptFileId?: string | null;\n } = {};\n\n // Arguments \u2014 preserve all axes. `dataType` defaults to 'string' for\n // older app json files that pre-date typed parameters. Always sent\n // (even when empty): the local config is authoritative for the sync\n // path, so an app whose args were cleared locally must push that\n // emptiness through, otherwise `mergeAppUpdate` would keep the remote\n // args and `status` would report the app modified forever.\n update.expectedArguments = local.arguments.map((a) => {\n const arg: AppArgument = {\n name: a.name,\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.defaultValue !== undefined) arg.defaultValue = a.defaultValue;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n });\n\n // Entrypoint - lookup by path or filename\n if (local.entrypoint) {\n const entrypointId = findScriptId(local.entrypoint);\n if (entrypointId) {\n update.mainScriptFileId = entrypointId;\n }\n }\n\n return update;\n }\n\n /**\n * Get sync status without making changes\n */\n async getStatus(): Promise<AppSyncStatus> {\n const status: AppSyncStatus = {\n newLocal: [],\n newRemote: [],\n modified: [],\n synced: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Check local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n status.newLocal.push(local.name);\n } else if (!this.areAppsEqual(local, remote.app)) {\n status.modified.push(local.name);\n } else {\n status.synced.push(local.name);\n }\n }\n\n // Check for new remote apps\n for (const [key, { app }] of remoteApps) {\n if (!localApps.has(key)) {\n status.newRemote.push(app.name);\n }\n }\n\n return status;\n }\n}\n"],
4
+ "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { RemoteApp, AppArgument, AppArgumentDataType } from './apps';\nimport type { FarseerService } from './farseerService';\nimport { getTenantAppsDir, ensureDirectoryExists, fetchWithConcurrency } from '../utils/helpers';\nimport { logger } from '../utils/logger';\nimport { formatClientError } from '../utils/errorFormatter';\n\n// Local app config format (stored in apps/*.json) \u2014 mirrors AppArgument so\n// pull/push round-trips don't drop any axis.\nexport interface LocalAppConfig {\n name: string;\n description: string;\n entrypoint: string | null; // Script filename (e.g., \"index.ts\")\n arguments: {\n name: string;\n // `dataType` defaults to 'string' on legacy configs that pre-date typed\n // parameters. Without round-tripping the full axes (`dataType`,\n // `fixed`, `options`), a pull \u2192 push cycle silently demoted a boolean /\n // dropdown / locked arg back to a plain string variable.\n dataType?: AppArgumentDataType;\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n }[];\n _remote?: {\n id: number;\n reference: string;\n };\n}\n\nexport interface AppSyncResult {\n created: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n}\n\nexport interface AppSyncStatus {\n newLocal: string[]; // Local apps not on remote\n newRemote: string[]; // Remote apps not locally\n modified: string[]; // Apps that differ\n synced: string[]; // Apps in sync\n}\n\n/**\n * Sanitize Croatian diacritics and other special characters to ASCII equivalents\n */\nfunction sanitizeDiacritics(text: string): string {\n const diacriticMap: Record<string, string> = {\n // Croatian\n \u010D: 'c',\n \u010C: 'C',\n \u0107: 'c',\n \u0106: 'C',\n \u0161: 's',\n \u0160: 'S',\n \u017E: 'z',\n \u017D: 'Z',\n \u0111: 'd',\n \u0110: 'D',\n // German/Other common\n \u00E4: 'a',\n \u00C4: 'A',\n \u00F6: 'o',\n \u00D6: 'O',\n \u00FC: 'u',\n \u00DC: 'U',\n \u00DF: 'ss',\n // Polish\n \u0105: 'a',\n \u0104: 'A',\n \u0119: 'e',\n \u0118: 'E',\n \u0142: 'l',\n \u0141: 'L',\n \u0144: 'n',\n \u0143: 'N',\n \u00F3: 'o',\n \u00D3: 'O',\n \u015B: 's',\n \u015A: 'S',\n \u017A: 'z',\n \u0179: 'Z',\n \u017C: 'z',\n \u017B: 'Z',\n // French/Spanish\n \u00E0: 'a',\n \u00E1: 'a',\n \u00E2: 'a',\n \u00E8: 'e',\n \u00E9: 'e',\n \u00EA: 'e',\n \u00EB: 'e',\n \u00EC: 'i',\n \u00ED: 'i',\n \u00EE: 'i',\n \u00EF: 'i',\n \u00F2: 'o',\n \u00F4: 'o',\n \u00F9: 'u',\n \u00FA: 'u',\n \u00FB: 'u',\n \u00F1: 'n',\n \u00D1: 'N',\n \u00E7: 'c',\n \u00C7: 'C',\n };\n\n return text\n .split('')\n .map((char) => diacriticMap[char] || char)\n .join('');\n}\n\n/**\n * Migrate legacy `type: 'variable' | 'constant' | 'boolean' | 'dropdown'` on\n * pre-PR pulls to the orthogonal-axes shape used by `localToUpdate` and\n * `areAppsEqual`. Idempotent \u2014 leaves new-shape entries untouched.\n *\n * Without this, a push immediately after upgrade silently demoted locked\n * args (`type: 'constant'` \u2192 no `fixed`) because the new code ignores the\n * legacy `type` key when building the wire payload. `areAppsEqual` flagged\n * the diff but didn't block, so the silent demote slipped through.\n */\nfunction migrateLegacyArguments(config: { arguments?: unknown[] } & Record<string, unknown>): Record<string, unknown> {\n if (!Array.isArray(config.arguments)) return config as Record<string, unknown>;\n config.arguments = config.arguments.map((raw) => {\n if (raw === null || typeof raw !== 'object') return raw;\n const a = raw as Record<string, unknown>;\n if (a.dataType !== undefined || a.type === undefined) return a;\n const legacyType = a.type;\n const rest: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(a)) {\n if (k !== 'type') rest[k] = v;\n }\n switch (legacyType) {\n case 'constant':\n return { ...rest, dataType: 'string', fixed: true };\n case 'boolean':\n return { ...rest, dataType: 'boolean' };\n case 'dropdown':\n case 'variable':\n default:\n return { ...rest, dataType: 'string' };\n }\n });\n return config as Record<string, unknown>;\n}\n\n/**\n * Service for syncing app configurations between local JSON files and remote Farseer instance\n */\nexport class AppSyncService {\n private api: FarseerService;\n private appsDir: string;\n\n constructor(tenant: string, api: FarseerService) {\n this.api = api;\n this.appsDir = getTenantAppsDir(tenant);\n }\n\n /**\n * Get filename for an app (keep original name, just sanitize for filesystem)\n */\n private getAppFilename(name: string): string {\n return (\n sanitizeDiacritics(name)\n .replace(/[<>:\"/\\\\|?*]/g, '') // Remove invalid filename characters\n .trim() + '.json'\n );\n }\n\n /**\n * Names of locally-tracked apps the next `pull` would delete because\n * remote no longer has them. Uses only `listApps` (no per-app fetch),\n * so pull can preview deletions for the destructive-action prompt\n * without paying for getStatus's full per-app round-trip.\n *\n * Mirrors the deletion gate in `pull()` (`local._remote && !remoteApps.has(key)`):\n * apps the user never pulled (`_remote` undefined) are kept untouched\n * by pull, so they don't belong in this list.\n */\n async getRemoteDeletions(): Promise<string[]> {\n const localApps = this.loadLocalApps();\n const remoteAppList = await this.api.listApps();\n const remoteNames = new Set(remoteAppList.map((a) => a.name.toLowerCase()));\n const deleted: string[] = [];\n for (const [key, local] of localApps) {\n if (local._remote && !remoteNames.has(key)) {\n deleted.push(local.name);\n }\n }\n return deleted;\n }\n\n /**\n * Load all local app configs\n */\n loadLocalApps(): Map<string, LocalAppConfig> {\n const apps = new Map<string, LocalAppConfig>();\n\n if (!fs.existsSync(this.appsDir)) {\n return apps;\n }\n\n const files = fs.readdirSync(this.appsDir).filter((f) => f.endsWith('.json'));\n\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(this.appsDir, file), 'utf-8');\n const config = migrateLegacyArguments(JSON.parse(content)) as LocalAppConfig;\n apps.set(config.name.toLowerCase(), config);\n } catch {\n // Skip invalid files\n }\n }\n\n return apps;\n }\n\n /**\n * Save a local app config\n */\n saveLocalApp(config: LocalAppConfig): void {\n ensureDirectoryExists(this.appsDir);\n const filename = this.getAppFilename(config.name);\n const filePath = path.join(this.appsDir, filename);\n fs.writeFileSync(filePath, JSON.stringify(config, null, 2), 'utf-8');\n }\n\n /**\n * Delete a local app config\n */\n deleteLocalApp(name: string): boolean {\n const filename = this.getAppFilename(name);\n const filePath = path.join(this.appsDir, filename);\n\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n return true;\n }\n return false;\n }\n\n /**\n * Convert remote app to local config format\n */\n private remoteToLocal(remote: RemoteApp, reference: string): LocalAppConfig {\n const scriptFiles = remote.scriptFiles ?? [];\n const mainScript = scriptFiles.find((s) => s.id === remote.mainScriptFileId);\n\n // \"No default\" canonical shape locally is `defaultValue: ''` (empty\n // string), NOT an omitted key. The OpenAPI schema makes the field\n // optional, so the backend can emit either; if we passed `undefined`\n // through verbatim, a user who added `defaultValue: ''` locally\n // would see `areAppsEqual` say \"match\" (both normalise to '') but\n // the next pull would strip the key again \u2014 the on-disk JSON would\n // oscillate forever and never reach a steady state. type is treated\n // the same way ('variable' is the implicit default), secret only\n // appears when explicitly true on the backend (boolean is a clear\n // tri-state: true/false/unset, and \"unset\" reads as false anyway).\n return {\n name: remote.name,\n description: remote.description || '',\n entrypoint: mainScript?.name || null,\n arguments: remote.expectedArguments.map((a) => {\n // Pin a steady-state shape so two pulls back-to-back don't\n // oscillate. `defaultValue` is normalized to '' when omitted \u2014\n // a user-edited `defaultValue: ''` locally must compare equal\n // to a remote that omits the field. `dataType` defaults to\n // 'string' (the implicit pre-fix shape). All other axes\n // (`fixed`, `options`, `secret`) are only emitted when the\n // remote populated them, to keep the JSON minimal.\n const arg: LocalAppConfig['arguments'][number] = {\n name: a.name,\n defaultValue: a.defaultValue ?? '',\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n }),\n _remote: {\n id: remote.id,\n reference: reference,\n },\n };\n }\n\n /**\n * Check if local and remote app configs are equivalent\n */\n private areAppsEqual(local: LocalAppConfig, remote: RemoteApp): boolean {\n // Compare name\n if (local.name !== remote.name) return false;\n\n // Compare description\n if ((local.description || '') !== (remote.description || '')) return false;\n\n // Compare entrypoint\n const remoteScriptFiles = remote.scriptFiles ?? [];\n const remoteEntrypoint = remoteScriptFiles.find((s) => s.id === remote.mainScriptFileId)?.name || null;\n if (local.entrypoint !== remoteEntrypoint) return false;\n\n // Compare arguments. Order matters here: backend renders args in the\n // saved order in the UI, so we treat reordering as a real change.\n // Missing `dataType` defaults to 'string' (the implicit pre-fix value);\n // missing scalar defaults are normalized so '' vs undefined doesn't\n // show up as a spurious diff. All four axes (dataType, fixed, options,\n // defaultValue, secret) are compared so a pull\u2192push round-trip\n // detects changes on any of them.\n if (local.arguments.length !== remote.expectedArguments.length) return false;\n for (let i = 0; i < local.arguments.length; i++) {\n const l = local.arguments[i];\n const r = remote.expectedArguments[i];\n if (l.name !== r.name) return false;\n if ((l.dataType ?? 'string') !== (r.dataType ?? 'string')) return false;\n if (Boolean(l.fixed) !== Boolean(r.fixed)) return false;\n if (JSON.stringify(l.options ?? []) !== JSON.stringify(r.options ?? [])) return false;\n if ((l.defaultValue ?? '') !== (r.defaultValue ?? '')) return false;\n if (Boolean(l.secret) !== Boolean(r.secret)) return false;\n }\n\n return true;\n }\n\n /**\n * Pull apps from remote and save locally\n */\n async pull(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n logger.dim(`Fetching ${remoteAppList.length} apps in parallel...`);\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item, index) => {\n const app = await this.api.getApp(item.reference);\n // Show progress every 10 apps\n if ((index + 1) % 10 === 0 || index === remoteAppList.length - 1) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write(`\\r Progress: ${index + 1}/${remoteAppList.length} apps`);\n }\n return { app, reference: item.reference };\n },\n 15,\n );\n // Clear progress line\n if (remoteAppList.length > 0) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Process remote apps\n for (const [key, { app, reference }] of remoteApps) {\n const localConfig = this.remoteToLocal(app, reference);\n const existingLocal = localApps.get(key);\n\n if (!existingLocal) {\n // New app from remote\n this.saveLocalApp(localConfig);\n result.created.push(app.name);\n } else if (!this.areAppsEqual(existingLocal, app)) {\n // App changed on remote - update local\n this.saveLocalApp(localConfig);\n result.updated.push(app.name);\n } else {\n result.unchanged.push(app.name);\n }\n }\n\n // Check for apps deleted on remote\n for (const [key, local] of localApps) {\n if (!remoteApps.has(key) && local._remote) {\n // App was synced before but now deleted on remote\n this.deleteLocalApp(local.name);\n result.deleted.push(local.name);\n }\n }\n\n return result;\n }\n\n /**\n * Push local apps to remote\n */\n async push(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Get available scripts for ID lookup\n // Build maps for both path-based and filename-based lookup (backward compatibility)\n const availableScripts = await this.api.getScriptFiles();\n const scriptIdByPath = new Map<string, string>();\n const scriptIdByName = new Map<string, string>();\n\n for (const s of availableScripts) {\n // s.name now contains full path (e.g., \"Scripts/test.ts\")\n const pathKey = s.name.toLowerCase();\n const filenameKey = s.name.split('/').pop()?.toLowerCase() || pathKey;\n\n scriptIdByPath.set(pathKey, s.id);\n // For filename lookup, only set if not already set (first match wins for ambiguous names)\n if (!scriptIdByName.has(filenameKey)) {\n scriptIdByName.set(filenameKey, s.id);\n }\n }\n\n // Helper to find script ID by path or filename\n const findScriptId = (scriptRef: string): string | undefined => {\n const key = scriptRef.toLowerCase();\n // Try exact path match first\n const byPath = scriptIdByPath.get(key);\n if (byPath) return byPath;\n // Try with Scripts/ prefix\n const withPrefix = scriptIdByPath.get(`scripts/${key}`);\n if (withPrefix) return withPrefix;\n // Fall back to filename match\n return scriptIdByName.get(key.split('/').pop() || key);\n };\n\n // Process local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n // New local app - create on remote\n try {\n const created = await this.api.createApp(local.name);\n\n // Update with config (API requires name and description)\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n await this.api.updateApp(created.id.toString(), update, created);\n\n // Update local with remote ID\n local._remote = {\n id: created.id,\n reference: created.id.toString(),\n };\n this.saveLocalApp(local);\n\n result.created.push(local.name);\n } catch (error) {\n logger.error(`Failed to create app ${local.name}: ${await formatClientError(error)}`);\n }\n } else if (!this.areAppsEqual(local, remote.app)) {\n // App differs - update remote\n try {\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n\n await this.api.updateApp(remote.reference, update, remote.app);\n result.updated.push(local.name);\n } catch (error) {\n logger.error(`Failed to update app ${local.name}: ${await formatClientError(error)}`);\n }\n } else {\n result.unchanged.push(local.name);\n }\n }\n\n // Note: We don't auto-delete remote apps when deleted locally\n // User must use \"farseer app delete\" explicitly\n\n return result;\n }\n\n /**\n * Build update payload for API\n */\n private buildUpdatePayload(\n local: LocalAppConfig,\n findScriptId: (scriptRef: string) => string | undefined,\n ): {\n name?: string;\n description?: string;\n expectedArguments?: AppArgument[];\n mainScriptFileId?: string | null;\n } {\n const update: {\n name?: string;\n description?: string;\n expectedArguments?: AppArgument[];\n mainScriptFileId?: string | null;\n } = {};\n\n // Arguments \u2014 preserve all axes. `dataType` defaults to 'string' for\n // older app json files that pre-date typed parameters. Always sent\n // (even when empty): the local config is authoritative for the sync\n // path, so an app whose args were cleared locally must push that\n // emptiness through, otherwise `mergeAppUpdate` would keep the remote\n // args and `status` would report the app modified forever.\n update.expectedArguments = local.arguments.map((a) => {\n const arg: AppArgument = {\n name: a.name,\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.defaultValue !== undefined) arg.defaultValue = a.defaultValue;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n });\n\n // Entrypoint - lookup by path or filename\n if (local.entrypoint) {\n const entrypointId = findScriptId(local.entrypoint);\n if (entrypointId) {\n update.mainScriptFileId = entrypointId;\n }\n }\n\n return update;\n }\n\n /**\n * Get sync status without making changes\n */\n async getStatus(): Promise<AppSyncStatus> {\n const status: AppSyncStatus = {\n newLocal: [],\n newRemote: [],\n modified: [],\n synced: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Check local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n status.newLocal.push(local.name);\n } else if (!this.areAppsEqual(local, remote.app)) {\n status.modified.push(local.name);\n } else {\n status.synced.push(local.name);\n }\n }\n\n // Check for new remote apps\n for (const [key, { app }] of remoteApps) {\n if (!localApps.has(key)) {\n status.newRemote.push(app.name);\n }\n }\n\n return status;\n }\n}\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AAGtB,qBAA8E;AAC9E,oBAAu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