farseer-cli 1.10.3 → 1.11.1

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 (84) hide show
  1. package/README.md +5 -0
  2. package/dist/commands/app.js +41 -42
  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 +13 -15
  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 +38 -23
  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/tools/runTools.js +12 -7
  41. package/dist/mcp/tools/runTools.js.map +2 -2
  42. package/dist/mcp/utils/helpers.js +41 -0
  43. package/dist/mcp/utils/helpers.js.map +2 -2
  44. package/dist/mcp/utils/session.js +2 -2
  45. package/dist/mcp/utils/session.js.map +2 -2
  46. package/dist/services/appSyncService.js.map +1 -1
  47. package/dist/services/apps.js +149 -0
  48. package/dist/services/apps.js.map +7 -0
  49. package/dist/services/authErrors.js +77 -0
  50. package/dist/services/authErrors.js.map +7 -0
  51. package/dist/services/configService.js +7 -4
  52. package/dist/services/configService.js.map +2 -2
  53. package/dist/services/credentials.js +87 -0
  54. package/dist/services/credentials.js.map +7 -0
  55. package/dist/services/farseerService.js +247 -123
  56. package/dist/services/farseerService.js.map +2 -2
  57. package/dist/services/httpError.js +35 -0
  58. package/dist/services/httpError.js.map +7 -0
  59. package/dist/services/modelExport.js +63 -0
  60. package/dist/services/modelExport.js.map +7 -0
  61. package/dist/services/organisation.js +88 -0
  62. package/dist/services/organisation.js.map +7 -0
  63. package/dist/services/preflight.js +10 -13
  64. package/dist/services/preflight.js.map +2 -2
  65. package/dist/services/syncService.js +2 -2
  66. package/dist/services/syncService.js.map +2 -2
  67. package/dist/utils/appResolver.js +63 -0
  68. package/dist/utils/appResolver.js.map +7 -0
  69. package/dist/utils/constants.js +2 -5
  70. package/dist/utils/constants.js.map +2 -2
  71. package/dist/utils/fileLogger.js +24 -1
  72. package/dist/utils/fileLogger.js.map +2 -2
  73. package/dist/utils/folderMatch.js +49 -0
  74. package/dist/utils/folderMatch.js.map +7 -0
  75. package/dist/utils/helpers.js +98 -1
  76. package/dist/utils/helpers.js.map +3 -3
  77. package/dist/utils/syncScope.js +44 -0
  78. package/dist/utils/syncScope.js.map +7 -0
  79. package/docs/api-reference.md +13 -1
  80. package/package.json +1 -1
  81. package/dist/services/farseerApi.js +0 -716
  82. package/dist/services/farseerApi.js.map +0 -7
  83. package/dist/services/farseerFactory.js +0 -276
  84. package/dist/services/farseerFactory.js.map +0 -7
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/mcp/tools/runTools.ts"],
4
- "sourcesContent": ["/**\n * App Execution Tools\n *\n * Tools for running Farseer apps locally.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { requireSession } from '../utils/session';\nimport {\n getCredential,\n getUserAuth,\n isUserAuthValid,\n setUserAuth,\n generateBasePath,\n} from '../../services/configService';\nimport { refreshAccessToken } from '../../services/farseerService';\nimport { getTenantDir, getTenantSrcDir, getTenantFilesDir } from '../../utils/helpers';\nimport { ensurePackageJson, parsePackageSpec } from '../../utils/packageManager';\nimport {\n getSessionTenant,\n successResponse,\n errorResponse,\n authRequiredResponse,\n tenantRequiredResponse,\n} from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n/**\n * Find a script file recursively in a directory.\n */\nfunction findScriptRecursively(baseDir: string, scriptName: string): string | null {\n if (!fs.existsSync(baseDir)) return null;\n const search = (dir: string, relativePath: string = ''): string | null => {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n for (const item of items) {\n const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;\n if (item.isFile() && item.name === scriptName) return itemRelPath;\n if (item.isDirectory()) {\n const found = search(path.join(dir, item.name), itemRelPath);\n if (found) return found;\n }\n }\n return null;\n };\n return search(baseDir);\n}\n\ninterface RunCredentials {\n tenantId: string;\n apiKey?: string;\n accessToken?: string;\n basePath: string;\n}\n\nasync function getRunCredentials(organisation: string, tenant: string): Promise<RunCredentials | null> {\n // First try API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n tenantId: credential.tenantId,\n apiKey: credential.apiKey,\n basePath: credential.basePath,\n };\n }\n\n // Try user auth (browser login)\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n\n // Check if token needs refresh\n if (!isUserAuthValid()) {\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n return null;\n }\n // Save refreshed token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n }\n\n const updatedAuth = getUserAuth();\n if (!updatedAuth) return null;\n\n return {\n tenantId: tenant,\n accessToken: updatedAuth.accessToken,\n basePath: generateBasePath(organisation),\n };\n}\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst runAppSchema = {\n appName: z.string().describe('Name of the app to run'),\n argumentOverrides: z\n .record(z.string(), z.string())\n .optional()\n .describe('Override argument values (Name: Value pairs)'),\n};\n\nexport function registerRunTools(server: McpServer): void {\n // farseer_run_app - Run an app locally\n server.tool(\n 'farseer_run_app',\n `Run a Farseer app locally.\n\nThis executes the app's entrypoint script using npx tsx with credentials automatically injected.\nThe script's FarseerClient() constructor picks up the injected env vars - no hardcoded credentials needed.\n\nHow it works:\n1. Looks up app configuration to find the entrypoint script\n2. Injects credentials as environment variables:\n - TENANT_ID: The tenant identifier\n - FARSEER_URL: Base API URL (e.g., https://myorg.farseer.io/api/v3)\n - FARSEER_API_KEY or FARSEER_TOKEN: Authentication credentials from login\n3. Passes app arguments via command line in the order defined by app config\n4. Executes the script using npx tsx in the tenant directory\n\nRequirements:\n- Scripts must be pulled locally first (farseer_pull)\n- Dependencies must be installed (run \"farseer install <tenant>\" in terminal)\n- All CLI commands must be run from the repository root (the directory containing farseer-apps/)\n\nArguments can be overridden using the argumentOverrides parameter.\nArguments not overridden use their default values from app config.`,\n runAppSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { appName: string; argumentOverrides?: Record<string, string> }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client } = gate.session;\n\n try {\n // Get app details\n const app = await client.getAppByName(params.appName);\n if (!app) {\n return errorResponse(`App \"${params.appName}\" not found`, 'NOT_FOUND');\n }\n\n const runScripts = app.scriptFiles ?? [];\n if (!app.mainScriptFileId || runScripts.length === 0) {\n return errorResponse(\n `App \"${params.appName}\" has no scripts configured. Configure it with farseer_configure_app.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Find entrypoint script\n const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);\n if (!mainScript) {\n return errorResponse(`Entrypoint script not found for app \"${params.appName}\"`, 'NOT_FOUND');\n }\n\n // Get run credentials\n const credentials = await getRunCredentials(organisation, tenant);\n if (!credentials) {\n return authRequiredResponse(tenant);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Normalize script name - strip Scripts/ prefix if present\n let scriptName = mainScript.name;\n if (scriptName.toLowerCase().startsWith('scripts/')) {\n scriptName = scriptName.substring('scripts/'.length);\n }\n\n // Find script: try Scripts/ first, then search recursively in files/\n let scriptPath = path.resolve(srcDir, scriptName);\n let relativeScriptPath = `files/Scripts/${scriptName}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try full relative path under files/ first (e.g. Scripts/MyApp/index.ts \u2192 files/Scripts/MyApp/index.ts)\n const fullRelPath = path.resolve(filesDir, mainScript.name);\n if (fs.existsSync(fullRelPath)) {\n scriptPath = fullRelPath;\n relativeScriptPath = `files/${mainScript.name}`;\n } else {\n const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n }\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n return errorResponse(\n `Script not found locally: ${scriptName}. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n return errorResponse(\n `Dependencies not installed. Run \"farseer install ${tenant}\" in terminal first.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Build arguments\n const appArgs: Record<string, string> = {};\n\n // Start with defaults. defaultValue is optional on the API\n // type; treat missing as '' so we always hand a string to\n // the runner.\n for (const arg of app.expectedArguments) {\n appArgs[arg.name] = arg.defaultValue ?? '';\n }\n\n // Apply overrides\n if (params.argumentOverrides) {\n for (const [name, value] of Object.entries(params.argumentOverrides)) {\n appArgs[name] = value;\n }\n }\n\n // Build environment\n const envVars: Record<string, string> = {\n ...(process.env as Record<string, string>),\n TENANT_ID: credentials.tenantId,\n FARSEER_URL: credentials.basePath,\n };\n\n if (credentials.apiKey) {\n envVars.FARSEER_API_KEY = credentials.apiKey;\n }\n if (credentials.accessToken) {\n envVars.FARSEER_TOKEN = credentials.accessToken;\n }\n\n // Build command line arguments (in order)\n const cmdArgs: string[] = [];\n for (const arg of app.expectedArguments) {\n cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue ?? '');\n }\n\n // Run the script\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npx', ['tsx', relativeScriptPath, ...cmdArgs], {\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n resolve(\n successResponse({\n tenant,\n app: params.appName,\n script: mainScript.name,\n arguments: appArgs,\n exitCode: code ?? 0,\n stdout: stdout.slice(0, 10000), // Limit output size\n stderr: stderr.slice(0, 5000),\n truncated: stdout.length > 10000 || stderr.length > 5000,\n }),\n );\n });\n\n child.on('error', (err) => {\n resolve(\n errorResponse(\n `Failed to run script: ${err.message}. Make sure tsx is installed: npm install -g tsx`,\n 'UNKNOWN',\n ),\n );\n });\n\n // Timeout after 5 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('Script execution timed out after 5 minutes', 'UNKNOWN'));\n },\n 5 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Run app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_install - Install dependencies for a tenant\n server.tool(\n 'farseer_install',\n `Install npm dependencies for a Farseer tenant.\n\nEnsures the tenant directory has a package.json with farseer-client, then runs npm install.\nIf package.json doesn't exist, it is auto-created with farseer-client as a dependency.\n\nYou can also add extra npm packages (e.g., axios, lodash) that a script needs.\nThese are added to package.json and installed in one step.\n\nTypical workflow:\n1. farseer_pull \u2192 farseer_install \u2192 farseer_run_app\n\nAll commands must run from the repository root (the directory containing farseer-apps/).`,\n {\n packages: z\n .array(z.string())\n .optional()\n .describe('Additional npm packages to install (e.g., [\"axios\", \"lodash@4\"])'),\n },\n async (params: { packages?: string[] }) => {\n // Not behind requireSession: this never reaches the tenant, so there\n // is nothing to validate. `farseer install` is excluded for the same reason.\n const resolved = getSessionTenant();\n if (!resolved) return tenantRequiredResponse();\n const { tenant } = resolved;\n\n const tenantDir = getTenantDir(tenant);\n\n if (!fs.existsSync(tenantDir)) {\n return errorResponse(\n `Tenant folder not found: farseer-apps/${tenant}/. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n try {\n // Auto-create or update package.json using shared utility\n const addedPackages = [...ensurePackageJson(tenantDir, tenant)];\n\n // Add extra packages if requested\n if (params.packages && params.packages.length > 0) {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n pkg.dependencies = pkg.dependencies || {};\n\n for (const pkgSpec of params.packages) {\n const { name, version } = parsePackageSpec(pkgSpec);\n if (!pkg.dependencies[name]) {\n pkg.dependencies[name] = version;\n addedPackages.push(pkgSpec);\n }\n }\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\\n');\n }\n\n // Run npm install\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npm', ['install'], {\n cwd: tenantDir,\n shell: true,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n if (code === 0) {\n resolve(\n successResponse({\n tenant,\n tenantDir: `farseer-apps/${tenant}/`,\n addedPackages,\n exitCode: 0,\n message: `Dependencies installed successfully${addedPackages.length ? ` (${addedPackages.join(', ')})` : ''}`,\n }),\n );\n } else {\n resolve(\n errorResponse(\n `npm install failed (exit code ${code}):\\n${stderr.slice(0, 3000)}`,\n 'UNKNOWN',\n ),\n );\n }\n });\n\n child.on('error', (err) => {\n resolve(errorResponse(`Failed to run npm install: ${err.message}`, 'UNKNOWN'));\n });\n\n // Timeout after 2 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('npm install timed out after 2 minutes', 'UNKNOWN'));\n },\n 2 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Install failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,2BAAsB;AACtB,SAAoB;AACpB,WAAsB;AACtB,qBAA+B;AAC/B,2BAMO;AACP,4BAAmC;AACnC,qBAAiE;AACjE,4BAAoD;AACpD,IAAAA,kBAMO;AACP,4BAAkC;AAKlC,SAAS,sBAAsB,SAAiB,YAAmC;AAC/E,MAAI,CAAC,GAAG,WAAW,OAAO,EAAG,QAAO;AACpC,QAAM,SAAS,CAAC,KAAa,eAAuB,OAAsB;AACtE,UAAM,QAAQ,GAAG,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC;AACzD,eAAW,QAAQ,OAAO;AACtB,YAAM,cAAc,eAAe,GAAG,YAAY,IAAI,KAAK,IAAI,KAAK,KAAK;AACzE,UAAI,KAAK,OAAO,KAAK,KAAK,SAAS,WAAY,QAAO;AACtD,UAAI,KAAK,YAAY,GAAG;AACpB,cAAM,QAAQ,OAAO,KAAK,KAAK,KAAK,KAAK,IAAI,GAAG,WAAW;AAC3D,YA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AAS;AACxB,gBAAI,SAAS,GAAG;AACZ;AAAA,oBACI,iCAAgB;AAAA,kBACZ;AAAA,kBACA,WAAW,gBAAgB,MAAM;AAAA,kBACjC;AAAA,kBACA,UAAU;AAAA,kBACV,SAAS,sCAAsC,cAAc,SAAS,KAAK,cAAc,KAAK,IAAI,CAAC,MAAM,EAAE;AAAA,gBAC/G,CAAC;AAAA,cACL;AAAA,YACJ,OAAO;AACH;AAAA,oBACI;AAAA,kBACI,iCAAiC,IAAI;AAAA,EAAO,OAAO,MAAM,GAAG,GAAI,CAAC;AAAA,kBACjE;AAAA,gBACJ;AAAA,cACJ;AAAA,YACJ;AAAA,UACJ,CAAC;AAED,gBAAM,GAAG,SAAS,CAAC,QAAQ;AACvB,wBAAQ,+BAAc,8BAA8B,IAAI,OAAO,IAAI,SAAS,CAAC;AAAA,UACjF,CAAC;AAGD;AAAA,YACI,MAAM;AACF,oBAAM,KAAK;AACX,0BAAQ,+BAAc,yCAAyC,SAAS,CAAC;AAAA,YAC7E;AAAA,YACA,IAAI,KAAK;AAAA,UACb;AAAA,QACJ,CAAC;AAAA,MACL,SAAS,OAAO;AACZ,mBAAO,+BAAc,mBAAmB,UAAM,yCAAkB,KAAK,CAAC,IAAI,eAAe;AAAA,MAC7F;AAAA,IACJ;AAAA,EACJ;AACJ;",
4
+ "sourcesContent": ["/**\n * App Execution Tools\n *\n * Tools for running Farseer apps locally.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\nimport { spawn } from 'child_process';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { requireSession } from '../utils/session';\nimport {\n getCredential,\n getUserAuth,\n isUserAuthValid,\n setUserAuth,\n generateBasePath,\n} from '../../services/configService';\nimport { refreshAccessToken } from '../../services/farseerService';\nimport { getTenantDir, getTenantSrcDir, getTenantFilesDir } from '../../utils/helpers';\nimport { ensurePackageJson, parsePackageSpec } from '../../utils/packageManager';\nimport {\n getSessionTenant,\n successResponse,\n errorResponse,\n authRequiredResponse,\n tenantRequiredResponse,\n resolveAppForMcp,\n} from '../utils/helpers';\nimport { formatClientError } from '../../utils/errorFormatter';\n\n/**\n * Find a script file recursively in a directory.\n */\nfunction findScriptRecursively(baseDir: string, scriptName: string): string | null {\n if (!fs.existsSync(baseDir)) return null;\n const search = (dir: string, relativePath: string = ''): string | null => {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n for (const item of items) {\n const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;\n if (item.isFile() && item.name === scriptName) return itemRelPath;\n if (item.isDirectory()) {\n const found = search(path.join(dir, item.name), itemRelPath);\n if (found) return found;\n }\n }\n return null;\n };\n return search(baseDir);\n}\n\ninterface RunCredentials {\n tenantId: string;\n apiKey?: string;\n accessToken?: string;\n basePath: string;\n}\n\nasync function getRunCredentials(organisation: string, tenant: string): Promise<RunCredentials | null> {\n // First try API key config\n const credential = getCredential(tenant);\n if (credential) {\n return {\n tenantId: credential.tenantId,\n apiKey: credential.apiKey,\n basePath: credential.basePath,\n };\n }\n\n // Try user auth (browser login)\n const auth = getUserAuth();\n if (!auth) {\n return null;\n }\n\n // Check if token needs refresh\n if (!isUserAuthValid()) {\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (!refreshed) {\n return null;\n }\n // Save refreshed token\n setUserAuth({\n accessToken: refreshed.accessToken,\n refreshToken: refreshed.refreshToken,\n expiresAt: new Date(Date.now() + refreshed.expiresIn * 1000).toISOString(),\n realm: auth.realm,\n });\n }\n\n const updatedAuth = getUserAuth();\n if (!updatedAuth) return null;\n\n return {\n tenantId: tenant,\n accessToken: updatedAuth.accessToken,\n basePath: generateBasePath(organisation),\n };\n}\n\n// Define schemas outside of tool registration to avoid deep type instantiation\nconst runAppSchema = {\n appName: z.string().optional().describe('Name of the app to run. Omit if using appId.'),\n appId: z.string().optional().describe('Numeric app id \u2014 use instead of appName when names collide.'),\n argumentOverrides: z\n .record(z.string(), z.string())\n .optional()\n .describe('Override argument values (Name: Value pairs)'),\n};\n\nexport function registerRunTools(server: McpServer): void {\n // farseer_run_app - Run an app locally\n server.tool(\n 'farseer_run_app',\n `Run a Farseer app locally.\n\nThis executes the app's entrypoint script using npx tsx with credentials automatically injected.\nThe script's FarseerClient() constructor picks up the injected env vars - no hardcoded credentials needed.\n\nHow it works:\n1. Looks up app configuration to find the entrypoint script\n2. Injects credentials as environment variables:\n - TENANT_ID: The tenant identifier\n - FARSEER_URL: Base API URL (e.g., https://myorg.farseer.io/api/v3)\n - FARSEER_API_KEY or FARSEER_TOKEN: Authentication credentials from login\n3. Passes app arguments via command line in the order defined by app config\n4. Executes the script using npx tsx in the tenant directory\n\nRequirements:\n- Scripts must be pulled locally first (farseer_pull)\n- Dependencies must be installed (run \"farseer install <tenant>\" in terminal)\n- All CLI commands must be run from the repository root (the directory containing farseer-apps/)\n\nArguments can be overridden using the argumentOverrides parameter.\nArguments not overridden use their default values from app config.`,\n runAppSchema,\n // @ts-expect-error TS2589 - MCP SDK deep type inference with zod schemas\n async (params: { appName?: string; appId?: string; argumentOverrides?: Record<string, string> }) => {\n const gate = await requireSession();\n if (!gate.ok) return gate.response;\n const { organisation, tenant, client } = gate.session;\n\n try {\n // Get app details\n const resolution = await resolveAppForMcp(client, {\n appName: params.appName,\n id: params.appId,\n });\n if ('error' in resolution) {\n return resolution.error;\n }\n const app = resolution.app;\n\n const runScripts = app.scriptFiles ?? [];\n if (!app.mainScriptFileId || runScripts.length === 0) {\n return errorResponse(\n `App \"${app.name}\" has no scripts configured. Configure it with farseer_configure_app.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Find entrypoint script\n const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);\n if (!mainScript) {\n return errorResponse(`Entrypoint script not found for app \"${app.name}\"`, 'NOT_FOUND');\n }\n\n // Get run credentials\n const credentials = await getRunCredentials(organisation, tenant);\n if (!credentials) {\n return authRequiredResponse(tenant);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Normalize script name - strip Scripts/ prefix if present\n let scriptName = mainScript.name;\n if (scriptName.toLowerCase().startsWith('scripts/')) {\n scriptName = scriptName.substring('scripts/'.length);\n }\n\n // Find script: try Scripts/ first, then search recursively in files/\n let scriptPath = path.resolve(srcDir, scriptName);\n let relativeScriptPath = `files/Scripts/${scriptName}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try full relative path under files/ first (e.g. Scripts/MyApp/index.ts \u2192 files/Scripts/MyApp/index.ts)\n const fullRelPath = path.resolve(filesDir, mainScript.name);\n if (fs.existsSync(fullRelPath)) {\n scriptPath = fullRelPath;\n relativeScriptPath = `files/${mainScript.name}`;\n } else {\n const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n }\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n return errorResponse(\n `Script not found locally: ${scriptName}. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n return errorResponse(\n `Dependencies not installed. Run \"farseer install ${tenant}\" in terminal first.`,\n 'VALIDATION_ERROR',\n );\n }\n\n // Build arguments\n const appArgs: Record<string, string> = {};\n\n // Start with defaults. defaultValue is optional on the API\n // type; treat missing as '' so we always hand a string to\n // the runner.\n for (const arg of app.expectedArguments) {\n appArgs[arg.name] = arg.defaultValue ?? '';\n }\n\n // Apply overrides\n if (params.argumentOverrides) {\n for (const [name, value] of Object.entries(params.argumentOverrides)) {\n appArgs[name] = value;\n }\n }\n\n // Build environment\n const envVars: Record<string, string> = {\n ...(process.env as Record<string, string>),\n TENANT_ID: credentials.tenantId,\n FARSEER_URL: credentials.basePath,\n };\n\n if (credentials.apiKey) {\n envVars.FARSEER_API_KEY = credentials.apiKey;\n }\n if (credentials.accessToken) {\n envVars.FARSEER_TOKEN = credentials.accessToken;\n }\n\n // Build command line arguments (in order)\n const cmdArgs: string[] = [];\n for (const arg of app.expectedArguments) {\n cmdArgs.push(appArgs[arg.name] ?? arg.defaultValue ?? '');\n }\n\n // Run the script\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npx', ['tsx', relativeScriptPath, ...cmdArgs], {\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n resolve(\n successResponse({\n tenant,\n app: app.name,\n script: mainScript.name,\n arguments: appArgs,\n exitCode: code ?? 0,\n stdout: stdout.slice(0, 10000), // Limit output size\n stderr: stderr.slice(0, 5000),\n truncated: stdout.length > 10000 || stderr.length > 5000,\n }),\n );\n });\n\n child.on('error', (err) => {\n resolve(\n errorResponse(\n `Failed to run script: ${err.message}. Make sure tsx is installed: npm install -g tsx`,\n 'UNKNOWN',\n ),\n );\n });\n\n // Timeout after 5 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('Script execution timed out after 5 minutes', 'UNKNOWN'));\n },\n 5 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Run app failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n\n // farseer_install - Install dependencies for a tenant\n server.tool(\n 'farseer_install',\n `Install npm dependencies for a Farseer tenant.\n\nEnsures the tenant directory has a package.json with farseer-client, then runs npm install.\nIf package.json doesn't exist, it is auto-created with farseer-client as a dependency.\n\nYou can also add extra npm packages (e.g., axios, lodash) that a script needs.\nThese are added to package.json and installed in one step.\n\nTypical workflow:\n1. farseer_pull \u2192 farseer_install \u2192 farseer_run_app\n\nAll commands must run from the repository root (the directory containing farseer-apps/).`,\n {\n packages: z\n .array(z.string())\n .optional()\n .describe('Additional npm packages to install (e.g., [\"axios\", \"lodash@4\"])'),\n },\n async (params: { packages?: string[] }) => {\n // Not behind requireSession: this never reaches the tenant, so there\n // is nothing to validate. `farseer install` is excluded for the same reason.\n const resolved = getSessionTenant();\n if (!resolved) return tenantRequiredResponse();\n const { tenant } = resolved;\n\n const tenantDir = getTenantDir(tenant);\n\n if (!fs.existsSync(tenantDir)) {\n return errorResponse(\n `Tenant folder not found: farseer-apps/${tenant}/. Run farseer_pull first.`,\n 'NOT_FOUND',\n );\n }\n\n try {\n // Auto-create or update package.json using shared utility\n const addedPackages = [...ensurePackageJson(tenantDir, tenant)];\n\n // Add extra packages if requested\n if (params.packages && params.packages.length > 0) {\n const packageJsonPath = path.join(tenantDir, 'package.json');\n const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));\n pkg.dependencies = pkg.dependencies || {};\n\n for (const pkgSpec of params.packages) {\n const { name, version } = parsePackageSpec(pkgSpec);\n if (!pkg.dependencies[name]) {\n pkg.dependencies[name] = version;\n addedPackages.push(pkgSpec);\n }\n }\n\n fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\\n');\n }\n\n // Run npm install\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n\n const child = spawn('npm', ['install'], {\n cwd: tenantDir,\n shell: true,\n });\n\n child.stdout?.on('data', (data: Buffer) => {\n stdout += data.toString();\n });\n\n child.stderr?.on('data', (data: Buffer) => {\n stderr += data.toString();\n });\n\n child.on('close', (code) => {\n if (code === 0) {\n resolve(\n successResponse({\n tenant,\n tenantDir: `farseer-apps/${tenant}/`,\n addedPackages,\n exitCode: 0,\n message: `Dependencies installed successfully${addedPackages.length ? ` (${addedPackages.join(', ')})` : ''}`,\n }),\n );\n } else {\n resolve(\n errorResponse(\n `npm install failed (exit code ${code}):\\n${stderr.slice(0, 3000)}`,\n 'UNKNOWN',\n ),\n );\n }\n });\n\n child.on('error', (err) => {\n resolve(errorResponse(`Failed to run npm install: ${err.message}`, 'UNKNOWN'));\n });\n\n // Timeout after 2 minutes\n setTimeout(\n () => {\n child.kill();\n resolve(errorResponse('npm install timed out after 2 minutes', 'UNKNOWN'));\n },\n 2 * 60 * 1000,\n );\n });\n } catch (error) {\n return errorResponse(`Install failed: ${await formatClientError(error)}`, 'NETWORK_ERROR');\n }\n },\n );\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAClB,2BAAsB;AACtB,SAAoB;AACpB,WAAsB;AACtB,qBAA+B;AAC/B,2BAMO;AACP,4BAAmC;AACnC,qBAAiE;AACjE,4BAAoD;AACpD,IAAAA,kBAOO;AACP,4BAAkC;AAKlC,SAAS,sBAAsB,SAAiB,YAAmC;AAC/E,MAAI,CAAC,GAAG,WAAW,OAAO,EAAG,QAAO;AACpC,QAAM,SAAS,CAAC,KAAa,eAAuB,OAAsB;AACtE,UAAM,QAAQ,GAAG,YAAY,KAAK,EAAE,eAAe,KAAK,CAAC;AACzD,eAAW,QAAQ,OAAO;AACtB,YAAM,cAAc,eAAe,GAAG,YAAY,IAAI,KAAK,IAAI,KAAK,KAAK;AACzE,UAAI,KAAK,OAAO,KAAK,KAAK,SAAS,WAAY,QAAO;AACtD,UAAI,KAAK,YAAY,GAAG;AACpB,cAAM,QAAQ,OAAO,KAAK,KAAK,KAAK,KAAK,IAAI,GAAG,WAAW;AAC3D,YAAI,MAAO,QAAO;AAAA,MACtB;AAAA,IACJ;AACA,WAAO;AAAA,EACX;AACA,SAAO,OAAO,OAAO;AACzB;AASA,eAAe,kBAAkB,cAAsB,QAAgD;AAEnG,QAAM,iBAAa,oCAAc,MAAM;AACvC,MAAI,YAAY;AACZ,WAAO;AAAA,MACH,UAAU,WAAW;AAAA,MACrB,QAAQ,WAAW;AAAA,MACnB,UAAU,WAAW;AAAA,IACzB;AAAA,EACJ;AAGA,QAAM,WAAO,kCAAY;AACzB,MAAI,CAAC,MAAM;AACP,WAAO;AAAA,EACX;AAGA,MAAI,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AAA,YACJ,OAAO;AACH;AAAA,oBACI;AAAA,kBACI,iCAAiC,IAAI;AAAA,EAAO,OAAO,MAAM,GAAG,GAAI,CAAC;AAAA,kBACjE;AAAA,gBACJ;AAAA,cACJ;AAAA,YACJ;AAAA,UACJ,CAAC;AAED,gBAAM,GAAG,SAAS,CAAC,QAAQ;AACvB,wBAAQ,+BAAc,8BAA8B,IAAI,OAAO,IAAI,SAAS,CAAC;AAAA,UACjF,CAAC;AAGD;AAAA,YACI,MAAM;AACF,oBAAM,KAAK;AACX,0BAAQ,+BAAc,yCAAyC,SAAS,CAAC;AAAA,YAC7E;AAAA,YACA,IAAI,KAAK;AAAA,UACb;AAAA,QACJ,CAAC;AAAA,MACL,SAAS,OAAO;AACZ,mBAAO,+BAAc,mBAAmB,UAAM,yCAAkB,KAAK,CAAC,IAAI,eAAe;AAAA,MAC7F;AAAA,IACJ;AAAA,EACJ;AACJ;",
6
6
  "names": ["import_helpers"]
7
7
  }
@@ -24,6 +24,8 @@ __export(helpers_exports, {
24
24
  errorResponse: () => errorResponse,
25
25
  getAuthStatus: () => getAuthStatus,
26
26
  getSessionTenant: () => getSessionTenant,
27
+ resolveAppForMcp: () => resolveAppForMcp,
28
+ resolveAppItemForMcp: () => resolveAppItemForMcp,
27
29
  successResponse: () => successResponse,
28
30
  tenantRequiredResponse: () => tenantRequiredResponse
29
31
  });
@@ -31,6 +33,7 @@ module.exports = __toCommonJS(helpers_exports);
31
33
  var import_configService = require("../../services/configService");
32
34
  var import_tenantPin = require("./tenantPin");
33
35
  var import_fileLogger = require("../../utils/fileLogger");
36
+ var import_appResolver = require("../../utils/appResolver");
34
37
  function getSessionTenant() {
35
38
  return (0, import_tenantPin.getTenantPin)() ?? null;
36
39
  }
@@ -64,6 +67,42 @@ function errorResponse(message, errorCode) {
64
67
  isError: true
65
68
  };
66
69
  }
70
+ async function resolveAppItemForMcp(client, selector) {
71
+ const selection = (0, import_appResolver.selectApp)(await client.listApps(), { name: selector.appName, id: selector.id });
72
+ if (selection.kind === "found") {
73
+ return { item: selection.app };
74
+ }
75
+ if (selection.kind === "ambiguous") {
76
+ return {
77
+ error: errorResponse((0, import_appResolver.formatAmbiguousApp)(selector.appName ?? "", selection.matches), "VALIDATION_ERROR")
78
+ };
79
+ }
80
+ if (selection.kind === "conflict") {
81
+ return {
82
+ error: errorResponse(
83
+ `App ${selection.app.reference} is "${selection.app.name}", not "${selection.name}". The id and the name point at different apps, so nothing was done \u2014 pass one of them.`,
84
+ "VALIDATION_ERROR"
85
+ )
86
+ };
87
+ }
88
+ return {
89
+ error: errorResponse(
90
+ selector.id ? `App not found: id ${selector.id}` : `App "${selector.appName}" not found`,
91
+ "NOT_FOUND"
92
+ )
93
+ };
94
+ }
95
+ async function resolveAppForMcp(client, selector) {
96
+ const resolution = await resolveAppItemForMcp(client, selector);
97
+ if ("error" in resolution) {
98
+ return resolution;
99
+ }
100
+ const app = await client.getApp(resolution.item.reference);
101
+ if (!app) {
102
+ return { error: errorResponse("Failed to load app details", "NETWORK_ERROR") };
103
+ }
104
+ return { app };
105
+ }
67
106
  function authRequiredResponse(tenant) {
68
107
  const message = tenant ? `Authentication required for tenant "${tenant}". Run "farseer login" to authenticate.` : 'Authentication required. Run "farseer login" to authenticate.';
69
108
  return errorResponse(message, "AUTH_REQUIRED");
@@ -121,6 +160,8 @@ function describeSessionWarning(warning) {
121
160
  errorResponse,
122
161
  getAuthStatus,
123
162
  getSessionTenant,
163
+ resolveAppForMcp,
164
+ resolveAppItemForMcp,
124
165
  successResponse,
125
166
  tenantRequiredResponse
126
167
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/mcp/utils/helpers.ts"],
4
- "sourcesContent": ["/** Response shapes and wording shared by the MCP tools. */\n\nimport { getUserAuth, isUserAuthValid, listCredentials } from '../../services/configService';\nimport type { SessionFailure, SessionWarning } from '../../services/preflight';\nimport { getTenantPin, isLaunchPinned } from './tenantPin';\nimport { fileLogger } from '../../utils/fileLogger';\n\n/**\n * The tenant this server is bound to, or null if nothing is bound yet. The env\n * is read once at launch (see launchPin.ts), so re-exporting FARSEER_TENANT\n * mid-session cannot retarget a running server.\n */\nexport function getSessionTenant(): { organisation: string; tenant: string } | null {\n return getTenantPin() ?? null;\n}\n\nexport function successResponse(data: Record<string, unknown>): { content: Array<{ type: 'text'; text: string }> } {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ success: true, ...data }, null, 2),\n },\n ],\n };\n}\n\nexport type McpErrorResponse = { content: Array<{ type: 'text'; text: string }>; isError: true };\n\nexport function errorResponse(\n message: string,\n errorCode?: 'AUTH_REQUIRED' | 'NOT_FOUND' | 'NETWORK_ERROR' | 'VALIDATION_ERROR' | 'UNKNOWN',\n): McpErrorResponse {\n // Log MCP tool errors to file for diagnostics\n fileLogger.error('mcp-tool', message, { errorCode: errorCode || 'UNKNOWN' });\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n success: false,\n error: message,\n errorCode: errorCode || 'UNKNOWN',\n },\n null,\n 2,\n ),\n },\n ],\n isError: true,\n };\n}\n\nexport function authRequiredResponse(tenant?: string): McpErrorResponse {\n const message = tenant\n ? `Authentication required for tenant \"${tenant}\". Run \"farseer login\" to authenticate.`\n : 'Authentication required. Run \"farseer login\" to authenticate.';\n\n return errorResponse(message, 'AUTH_REQUIRED');\n}\n\n/** No usable tenant for this call. States only how to fix the current situation. */\nexport function tenantRequiredResponse(): McpErrorResponse {\n const pin = getTenantPin();\n if (pin) {\n return errorResponse(\n `This session works only on tenant \"${pin.tenant}\". The tenant is locked for the session \u2014 to work on a different tenant, start a new session.`,\n 'VALIDATION_ERROR',\n );\n }\n // Agent-facing: the in-session fix is farseer_select_tenant, not a CLI\n // command or config edit. Configured API-key tenants are offered as a hint\n // when present (a browser-login user may reach others not listed).\n const configured = Object.keys(listCredentials());\n const hint = configured.length > 0 ? ` Configured tenants include: ${configured.join(', ')}.` : '';\n return errorResponse(\n `No tenant is selected for this session yet. Call farseer_select_tenant with the tenant to work on (the client the user named). It can be selected once, then locks for the session.${hint}`,\n 'VALIDATION_ERROR',\n );\n}\n\nexport function getAuthStatus(): {\n jwtValid: boolean;\n jwtExpiresAt?: string;\n tenant?: { organisation: string; tenant: string };\n launchPinned: boolean;\n configuredTenants: string[];\n} {\n const auth = getUserAuth();\n const pin = getTenantPin();\n const credentials = listCredentials();\n\n return {\n jwtValid: isUserAuthValid(),\n jwtExpiresAt: auth?.expiresAt,\n tenant: pin,\n launchPinned: isLaunchPinned(),\n configuredTenants: Object.keys(credentials),\n };\n}\n\n/**\n * The diagnosis is the guard's; `remedy` is the caller's, because the same\n * refusal is fixable in-session before the tenant locks and not after.\n */\nexport function describeSessionFailure(failure: SessionFailure, remedy: string): McpErrorResponse {\n switch (failure.reason) {\n case 'no-credentials':\n return authRequiredResponse(failure.tenant);\n\n case 'org-unknown':\n return errorResponse(`No Farseer organisation at \"${failure.organisation}\". ${remedy}`, 'VALIDATION_ERROR');\n\n case 'pair-refuted': {\n const known =\n failure.orgTenants.length > 0\n ? ` Tenants you can access under \"${failure.organisation}\": ${failure.orgTenants.join(', ')}.`\n : '';\n return errorResponse(\n `Tenant \"${failure.tenant}\" is not available under organisation \"${failure.organisation}\".${known} ${remedy}`,\n 'VALIDATION_ERROR',\n );\n }\n }\n}\n\n/** The CLI's warning without the \"you typed it\" framing \u2014 an agent did not type it. */\nexport function describeSessionWarning(warning: SessionWarning): string {\n return (\n `Organisation \"${warning.organisation}\" is not being used: the stored API key for \"${warning.tenant}\" ` +\n `carries its own host (${warning.host}). The tenant is the bound one; the organisation has no effect.`\n );\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,2BAA8D;AAE9D,uBAA6C;AAC7C,wBAA2B;AAOpB,SAAS,mBAAoE;AAChF,aAAO,+BAAa,KAAK;AAC7B;AAEO,SAAS,gBAAgB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;AAMO,SAAS,uBAAuB,SAAyB,QAAkC;AAC9F,UAAQ,QAAQ,QAAQ;AAAA,IACpB,KAAK;AACD,aAAO,qBAAqB,QAAQ,MAAM;AAAA,IAE9C,KAAK;AACD,aAAO,cAAc,+BAA+B,QAAQ,YAAY,MAAM,MAAM,IAAI,kBAAkB;AAAA,IAE9G,KAAK,gBAAgB;AACjB,YAAM,QACF,QAAQ,WAAW,SAAS,IACtB,kCAAkC,QAAQ,YAAY,MAAM,QAAQ,WAAW,KAAK,IAAI,CAAC,MACzF;AACV,aAAO;AAAA,QACH,WAAW,QAAQ,MAAM,0CAA0C,QAAQ,YAAY,KAAK,KAAK,IAAI,MAAM;AAAA,QAC3G;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;AAGO,SAAS,uBAAuB,SAAiC;AACpE,SACI,iBAAiB,QAAQ,YAAY,gDAAgD,QAAQ,MAAM,2BAC1E,QAAQ,IAAI;AAE7C;",
4
+ "sourcesContent": ["/** Response shapes and wording shared by the MCP tools. */\n\nimport { getUserAuth, isUserAuthValid, listCredentials } from '../../services/configService';\nimport type { SessionFailure, SessionWarning } from '../../services/preflight';\nimport { getTenantPin, isLaunchPinned } from './tenantPin';\nimport { fileLogger } from '../../utils/fileLogger';\nimport type { FarseerService } from '../../services/farseerService';\nimport type { AppListItem, RemoteApp } from '../../services/apps';\nimport { selectApp, formatAmbiguousApp } from '../../utils/appResolver';\n\n/**\n * The tenant this server is bound to, or null if nothing is bound yet. The env\n * is read once at launch (see launchPin.ts), so re-exporting FARSEER_TENANT\n * mid-session cannot retarget a running server.\n */\nexport function getSessionTenant(): { organisation: string; tenant: string } | null {\n return getTenantPin() ?? null;\n}\n\nexport function successResponse(data: Record<string, unknown>): { content: Array<{ type: 'text'; text: string }> } {\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify({ success: true, ...data }, null, 2),\n },\n ],\n };\n}\n\nexport type McpErrorResponse = { content: Array<{ type: 'text'; text: string }>; isError: true };\n\nexport function errorResponse(\n message: string,\n errorCode?: 'AUTH_REQUIRED' | 'NOT_FOUND' | 'NETWORK_ERROR' | 'VALIDATION_ERROR' | 'UNKNOWN',\n): McpErrorResponse {\n // Log MCP tool errors to file for diagnostics\n fileLogger.error('mcp-tool', message, { errorCode: errorCode || 'UNKNOWN' });\n\n return {\n content: [\n {\n type: 'text',\n text: JSON.stringify(\n {\n success: false,\n error: message,\n errorCode: errorCode || 'UNKNOWN',\n },\n null,\n 2,\n ),\n },\n ],\n isError: true,\n };\n}\n\n/**\n * Resolve an app to its folder list item, or to an error response ready to\n * return. An explicit `appId` wins; a name that matches more than one app is a\n * validation error listing the candidates, never a guess.\n *\n * Callers take `.reference` to fetch details and `.id` to delete \u2014 the two ids\n * are different and their number spaces overlap.\n */\nexport async function resolveAppItemForMcp(\n client: FarseerService,\n selector: { appName?: string; id?: string },\n): Promise<{ item: AppListItem } | { error: ReturnType<typeof errorResponse> }> {\n const selection = selectApp(await client.listApps(), { name: selector.appName, id: selector.id });\n if (selection.kind === 'found') {\n return { item: selection.app };\n }\n if (selection.kind === 'ambiguous') {\n // Names are not unique \u2014 refuse to guess which colliding app was meant.\n return {\n error: errorResponse(formatAmbiguousApp(selector.appName ?? '', selection.matches), 'VALIDATION_ERROR'),\n };\n }\n if (selection.kind === 'conflict') {\n return {\n error: errorResponse(\n `App ${selection.app.reference} is \"${selection.app.name}\", not \"${selection.name}\". The id and the name point at different apps, so nothing was done \u2014 pass one of them.`,\n 'VALIDATION_ERROR',\n ),\n };\n }\n return {\n error: errorResponse(\n selector.id ? `App not found: id ${selector.id}` : `App \"${selector.appName}\" not found`,\n 'NOT_FOUND',\n ),\n };\n}\n\n/**\n * Resolve an app for an MCP tool to its full details. Wraps\n * `resolveAppItemForMcp` + `getApp` so the tools that need the whole\n * `RemoteApp` (get, configure, run) don't repeat the fetch.\n */\nexport async function resolveAppForMcp(\n client: FarseerService,\n selector: { appName?: string; id?: string },\n): Promise<{ app: RemoteApp } | { error: ReturnType<typeof errorResponse> }> {\n const resolution = await resolveAppItemForMcp(client, selector);\n if ('error' in resolution) {\n return resolution;\n }\n const app = await client.getApp(resolution.item.reference);\n if (!app) {\n return { error: errorResponse('Failed to load app details', 'NETWORK_ERROR') };\n }\n return { app };\n}\n\nexport function authRequiredResponse(tenant?: string): McpErrorResponse {\n const message = tenant\n ? `Authentication required for tenant \"${tenant}\". Run \"farseer login\" to authenticate.`\n : 'Authentication required. Run \"farseer login\" to authenticate.';\n\n return errorResponse(message, 'AUTH_REQUIRED');\n}\n\n/** No usable tenant for this call. States only how to fix the current situation. */\nexport function tenantRequiredResponse(): McpErrorResponse {\n const pin = getTenantPin();\n if (pin) {\n return errorResponse(\n `This session works only on tenant \"${pin.tenant}\". The tenant is locked for the session \u2014 to work on a different tenant, start a new session.`,\n 'VALIDATION_ERROR',\n );\n }\n // Agent-facing: the in-session fix is farseer_select_tenant, not a CLI\n // command or config edit. Configured API-key tenants are offered as a hint\n // when present (a browser-login user may reach others not listed).\n const configured = Object.keys(listCredentials());\n const hint = configured.length > 0 ? ` Configured tenants include: ${configured.join(', ')}.` : '';\n return errorResponse(\n `No tenant is selected for this session yet. Call farseer_select_tenant with the tenant to work on (the client the user named). It can be selected once, then locks for the session.${hint}`,\n 'VALIDATION_ERROR',\n );\n}\n\nexport function getAuthStatus(): {\n jwtValid: boolean;\n jwtExpiresAt?: string;\n tenant?: { organisation: string; tenant: string };\n launchPinned: boolean;\n configuredTenants: string[];\n} {\n const auth = getUserAuth();\n const pin = getTenantPin();\n const credentials = listCredentials();\n\n return {\n jwtValid: isUserAuthValid(),\n jwtExpiresAt: auth?.expiresAt,\n tenant: pin,\n launchPinned: isLaunchPinned(),\n configuredTenants: Object.keys(credentials),\n };\n}\n\n/**\n * The diagnosis is the guard's; `remedy` is the caller's, because the same\n * refusal is fixable in-session before the tenant locks and not after.\n */\nexport function describeSessionFailure(failure: SessionFailure, remedy: string): McpErrorResponse {\n switch (failure.reason) {\n case 'no-credentials':\n return authRequiredResponse(failure.tenant);\n\n case 'org-unknown':\n return errorResponse(`No Farseer organisation at \"${failure.organisation}\". ${remedy}`, 'VALIDATION_ERROR');\n\n case 'pair-refuted': {\n const known =\n failure.orgTenants.length > 0\n ? ` Tenants you can access under \"${failure.organisation}\": ${failure.orgTenants.join(', ')}.`\n : '';\n return errorResponse(\n `Tenant \"${failure.tenant}\" is not available under organisation \"${failure.organisation}\".${known} ${remedy}`,\n 'VALIDATION_ERROR',\n );\n }\n }\n}\n\n/** The CLI's warning without the \"you typed it\" framing \u2014 an agent did not type it. */\nexport function describeSessionWarning(warning: SessionWarning): string {\n return (\n `Organisation \"${warning.organisation}\" is not being used: the stored API key for \"${warning.tenant}\" ` +\n `carries its own host (${warning.host}). The tenant is the bound one; the organisation has no effect.`\n );\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,2BAA8D;AAE9D,uBAA6C;AAC7C,wBAA2B;AAG3B,yBAA8C;AAOvC,SAAS,mBAAoE;AAChF,aAAO,+BAAa,KAAK;AAC7B;AAEO,SAAS,gBAAgB,MAAmF;AAC/G,SAAO;AAAA,IACH,SAAS;AAAA,MACL;AAAA,QACI,MAAM;AAAA,QACN,MAAM,KAAK,UAAU,EAAE,SAAS,MAAM,GAAG,KAAK,GAAG,MAAM,CAAC;AAAA,MAC5D;AAAA,IACJ;AAAA,EACJ;AACJ;AAIO,SAAS,cACZ,SACA,WACgB;AAEhB,+BAAW,MAAM,YAAY,SAAS,EAAE,WAAW,aAAa,UAAU,CAAC;AAE3E,SAAO;AAAA,IACH,SAAS;AAAA,MACL;AAAA,QACI,MAAM;AAAA,QACN,MAAM,KAAK;AAAA,UACP;AAAA,YACI,SAAS;AAAA,YACT,OAAO;AAAA,YACP,WAAW,aAAa;AAAA,UAC5B;AAAA,UACA;AAAA,UACA;AAAA,QACJ;AAAA,MACJ;AAAA,IAC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,MAChD;AAAA,IACJ;AAAA,EACJ;AAIA,QAAM,aAAa,OAAO,SAAK,sCAAgB,CAAC;AAChD,QAAM,OAAO,WAAW,SAAS,IAAI,gCAAgC,WAAW,KAAK,IAAI,CAAC,MAAM;AAChG,SAAO;AAAA,IACH,sLAAsL,IAAI;AAAA,IAC1L;AAAA,EACJ;AACJ;AAEO,SAAS,gBAMd;AACE,QAAM,WAAO,kCAAY;AACzB,QAAM,UAAM,+BAAa;AACzB,QAAM,kBAAc,sCAAgB;AAEpC,SAAO;AAAA,IACH,cAAU,sCAAgB;AAAA,IAC1B,cAAc,MAAM;AAAA,IACpB,QAAQ;AAAA,IACR,kBAAc,iCAAe;AAAA,IAC7B,mBAAmB,OAAO,KAAK,WAAW;AAAA,EAC9C;AACJ;AAMO,SAAS,uBAAuB,SAAyB,QAAkC;AAC9F,UAAQ,QAAQ,QAAQ;AAAA,IACpB,KAAK;AACD,aAAO,qBAAqB,QAAQ,MAAM;AAAA,IAE9C,KAAK;AACD,aAAO,cAAc,+BAA+B,QAAQ,YAAY,MAAM,MAAM,IAAI,kBAAkB;AAAA,IAE9G,KAAK,gBAAgB;AACjB,YAAM,QACF,QAAQ,WAAW,SAAS,IACtB,kCAAkC,QAAQ,YAAY,MAAM,QAAQ,WAAW,KAAK,IAAI,CAAC,MACzF;AACV,aAAO;AAAA,QACH,WAAW,QAAQ,MAAM,0CAA0C,QAAQ,YAAY,KAAK,KAAK,IAAI,MAAM;AAAA,QAC3G;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;AAGO,SAAS,uBAAuB,SAAiC;AACpE,SACI,iBAAiB,QAAQ,YAAY,gDAAgD,QAAQ,MAAM,2BAC1E,QAAQ,IAAI;AAE7C;",
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;AAC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AAgB,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 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;AAQA,2BAMO;AACP,yBAA4B;AAE5B,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,k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AS,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,oBAAuB;AACvB,4BAAkC;AA2ClC,SAAS,mBAAmB,MAAsB;AAC9C,QAAM,eAAuC;AAAA;AAAA,IAEzC,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA;AAAA,IAEH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA;AAAA,IAEH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AA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I,GAAG;AAEjC,UAAI,CAAC,QAAQ;AACT,eAAO,SAAS,KAAK,MAAM,IAAI;AAAA,MACnC,WAAW,CAAC,KAAK,aAAa,OAAO,OAAO,GAAG,GAAG;AAC9C,eAAO,SAAS,KAAK,MAAM,IAAI;AAAA,MACnC,OAAO;AACH,eAAO,OAAO,KAAK,MAAM,IAAI;AAAA,MACjC;AAAA,IACJ;AAGA,eAAW,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,YAAY;AACrC,UAAI,CAAC,UAAU,IAAI,GAAG,GAAG;AACrB,eAAO,UAAU,KAAK,IAAI,IAAI;AAAA,MAClC;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var apps_exports = {};
30
+ __export(apps_exports, {
31
+ AppDeleteRefusedError: () => AppDeleteRefusedError,
32
+ REMOTE_JOB_ITEM_TYPE: () => REMOTE_JOB_ITEM_TYPE,
33
+ applySourceFolderChange: () => applySourceFolderChange,
34
+ findScriptInFolder: () => findScriptInFolder,
35
+ mergeAppUpdate: () => mergeAppUpdate,
36
+ remoteJobReverseReferences: () => remoteJobReverseReferences,
37
+ resolveAppItemNodeId: () => resolveAppItemNodeId
38
+ });
39
+ module.exports = __toCommonJS(apps_exports);
40
+ var import_chalk = __toESM(require("chalk"));
41
+ var farseer = __toESM(require("farseer-client"));
42
+ function mergeAppUpdate(current, changes) {
43
+ return {
44
+ name: changes.name ?? current.name,
45
+ description: changes.description ?? current.description ?? "",
46
+ expectedArguments: changes.expectedArguments ?? current.expectedArguments ?? [],
47
+ mainScriptFileId: changes.mainScriptFileId ?? current.mainScriptFileId ?? null,
48
+ sourceFolderId: changes.sourceFolderId ?? current.sourceFolderId ?? null,
49
+ schedule: changes.schedule ?? current.schedule ?? null,
50
+ runnerName: changes.runnerName ?? current.runnerName ?? null,
51
+ runnerImage: changes.runnerImage ?? current.runnerImage ?? null,
52
+ predefinedActions: changes.predefinedActions ?? current.predefinedActions ?? []
53
+ };
54
+ }
55
+ function findScriptInFolder(folderScripts, name) {
56
+ return folderScripts.find((s) => s.name === name);
57
+ }
58
+ async function applySourceFolderChange(client, app, changes, options, caller) {
59
+ const cli = caller === "cli";
60
+ const hint = (text) => cli ? import_chalk.default.dim(text) : text;
61
+ let folderScripts = app.scriptFiles ?? [];
62
+ let sourceFolderId;
63
+ if (options.sourceFolder) {
64
+ const resolved = await client.resolveSourceFolder(options.sourceFolder);
65
+ if (!resolved) {
66
+ return [
67
+ `Source folder not found under Files/: ${options.sourceFolder}`,
68
+ hint('Use a path relative to Files/, e.g. "Scripts/MyApp".')
69
+ ].join("\n");
70
+ }
71
+ sourceFolderId = resolved.id;
72
+ folderScripts = resolved.scripts;
73
+ if (!options.entrypoint && app.mainScriptFileId) {
74
+ const stillThere = folderScripts.some((s) => s.id === app.mainScriptFileId);
75
+ if (!stillThere) {
76
+ const files = folderScripts.map((s) => s.name).join(", ") || "(none)";
77
+ return [
78
+ "The app's current entrypoint is not in the new source folder.",
79
+ hint(
80
+ cli ? "Pass --entrypoint <script> (a file in the new folder) in the same command." : 'Pass "entrypoint" (a file in the new folder) in the same call.'
81
+ ),
82
+ hint(`Files in this folder: ${files}`)
83
+ ].join("\n");
84
+ }
85
+ }
86
+ }
87
+ let mainScriptFileId;
88
+ if (options.entrypoint) {
89
+ const match = findScriptInFolder(folderScripts, options.entrypoint);
90
+ if (!match) {
91
+ const files = folderScripts.map((s) => s.name).join(", ") || "(none)";
92
+ const lines = [
93
+ `Entrypoint not found in the source folder: ${options.entrypoint}`,
94
+ hint(`Files in this folder: ${files}`)
95
+ ];
96
+ if (!options.sourceFolder) {
97
+ lines.push(
98
+ hint(
99
+ cli ? "To use a file from another folder, set it first with --source-folder <path>." : "To use a file from another folder, pass sourceFolder first."
100
+ )
101
+ );
102
+ }
103
+ return lines.join("\n");
104
+ }
105
+ mainScriptFileId = match.id;
106
+ }
107
+ if (sourceFolderId !== void 0) {
108
+ changes.sourceFolderId = sourceFolderId;
109
+ }
110
+ if (mainScriptFileId !== void 0) {
111
+ changes.mainScriptFileId = mainScriptFileId;
112
+ }
113
+ return null;
114
+ }
115
+ const REMOTE_JOB_ITEM_TYPE = farseer.FolderItemType.RemoteJob;
116
+ function remoteJobReverseReferences(remoteJobIds) {
117
+ return remoteJobIds.map((reference) => ({ reference, type: REMOTE_JOB_ITEM_TYPE }));
118
+ }
119
+ class AppDeleteRefusedError extends Error {
120
+ }
121
+ function resolveAppItemNodeId(remoteJobId, items) {
122
+ const matches = items.filter((item2) => item2.reference === remoteJobId);
123
+ if (matches.length === 0) {
124
+ throw new AppDeleteRefusedError(`No app found for Remote Job id ${remoteJobId} \u2014 nothing was deleted.`);
125
+ }
126
+ if (matches.length > 1) {
127
+ throw new AppDeleteRefusedError(
128
+ `Remote Job id ${remoteJobId} resolved to ${matches.length} folder items \u2014 refusing to delete.`
129
+ );
130
+ }
131
+ const item = matches[0];
132
+ if (item.type !== REMOTE_JOB_ITEM_TYPE) {
133
+ throw new AppDeleteRefusedError(
134
+ `Refusing to delete: Remote Job id ${remoteJobId} resolved to a ${item.type} ("${item.name}"), not an app.`
135
+ );
136
+ }
137
+ return item.id;
138
+ }
139
+ // Annotate the CommonJS export names for ESM import in node:
140
+ 0 && (module.exports = {
141
+ AppDeleteRefusedError,
142
+ REMOTE_JOB_ITEM_TYPE,
143
+ applySourceFolderChange,
144
+ findScriptInFolder,
145
+ mergeAppUpdate,
146
+ remoteJobReverseReferences,
147
+ resolveAppItemNodeId
148
+ });
149
+ //# sourceMappingURL=apps.js.map