farseer-cli 1.11.2 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +88 -10
  2. package/dist/commands/app.js +54 -4
  3. package/dist/commands/app.js.map +2 -2
  4. package/dist/commands/login.js +60 -26
  5. package/dist/commands/login.js.map +2 -2
  6. package/dist/commands/logout.js +37 -12
  7. package/dist/commands/logout.js.map +3 -3
  8. package/dist/commands/run.js +10 -27
  9. package/dist/commands/run.js.map +2 -2
  10. package/dist/commands/whoami.js +10 -14
  11. package/dist/commands/whoami.js.map +2 -2
  12. package/dist/mcp/prompts/workflows.js +2 -0
  13. package/dist/mcp/prompts/workflows.js.map +2 -2
  14. package/dist/mcp/tools/appTools.js +54 -4
  15. package/dist/mcp/tools/appTools.js.map +2 -2
  16. package/dist/mcp/tools/authTools.js +5 -2
  17. package/dist/mcp/tools/authTools.js.map +2 -2
  18. package/dist/mcp/tools/runTools.js +5 -18
  19. package/dist/mcp/tools/runTools.js.map +2 -2
  20. package/dist/mcp/utils/helpers.js +16 -6
  21. package/dist/mcp/utils/helpers.js.map +3 -3
  22. package/dist/mcp/utils/session.js +14 -9
  23. package/dist/mcp/utils/session.js.map +2 -2
  24. package/dist/services/appSyncService.js +33 -1
  25. package/dist/services/appSyncService.js.map +2 -2
  26. package/dist/services/apps.js +199 -9
  27. package/dist/services/apps.js.map +3 -3
  28. package/dist/services/authErrors.js +2 -2
  29. package/dist/services/authErrors.js.map +2 -2
  30. package/dist/services/configService.js +45 -9
  31. package/dist/services/configService.js.map +2 -2
  32. package/dist/services/credentials.js +10 -7
  33. package/dist/services/credentials.js.map +2 -2
  34. package/dist/services/farseerService.js +95 -36
  35. package/dist/services/farseerService.js.map +2 -2
  36. package/dist/services/preflight.js +3 -2
  37. package/dist/services/preflight.js.map +2 -2
  38. package/dist/services/realms.js +67 -0
  39. package/dist/services/realms.js.map +7 -0
  40. package/docs/cli-guide.md +16 -0
  41. package/package.json +1 -1
@@ -23,20 +23,22 @@ __export(logout_exports, {
23
23
  module.exports = __toCommonJS(logout_exports);
24
24
  var import_logger = require("../utils/logger");
25
25
  var import_configService = require("../services/configService");
26
+ var import_farseerService = require("../services/farseerService");
26
27
  function registerLogoutCommand(program) {
27
- program.command("logout [tenant]").description("Logout from Farseer (remove credentials)").option("--all", "Remove all credentials").action(async (tenant, options) => {
28
+ program.command("logout [tenant]").description("Logout from Farseer (remove credentials)").option("--all", "Remove all credentials").option("--realm <realm>", "Clear only this realm's browser login").action(async (tenant, options) => {
28
29
  if (options.all) {
29
- const credentials = (0, import_configService.listCredentials)();
30
- const tenants = Object.keys(credentials);
31
- if (tenants.length === 0) {
30
+ const tenants = Object.keys((0, import_configService.listCredentials)());
31
+ const realms2 = await logOutOfRealms(Object.entries((0, import_configService.listUserAuths)()));
32
+ if (tenants.length === 0 && realms2.length === 0) {
32
33
  import_logger.logger.info("No credentials stored.");
33
34
  return;
34
35
  }
35
36
  for (const t of tenants) {
36
37
  (0, import_configService.removeCredential)(t);
37
38
  }
38
- (0, import_configService.clearUserAuth)();
39
- import_logger.logger.success(`Removed credentials for ${tenants.length} tenant(s).`);
39
+ import_logger.logger.success(
40
+ `Removed credentials for ${tenants.length} tenant(s) and ${realms2.length} browser login(s).`
41
+ );
40
42
  return;
41
43
  }
42
44
  if (tenant) {
@@ -46,15 +48,38 @@ function registerLogoutCommand(program) {
46
48
  } else {
47
49
  import_logger.logger.warning(`No credentials found for tenant: ${tenant}`);
48
50
  }
49
- } else {
50
- (0, import_configService.clearUserAuth)();
51
- import_logger.logger.success("Logged out (user token cleared).");
52
- import_logger.logger.dim(
53
- 'API key credentials are still stored. Use "farseer logout <tenant>" to remove specific ones.'
54
- );
51
+ return;
55
52
  }
53
+ const logins = Object.entries((0, import_configService.listUserAuths)());
54
+ const selected = options.realm ? logins.filter(([realm]) => sameRealm(realm, options.realm)) : logins;
55
+ if (selected.length === 0) {
56
+ if (options.realm) {
57
+ import_logger.logger.warning(`No browser login for realm: ${options.realm}`);
58
+ if (logins.length > 0) {
59
+ import_logger.logger.dim(`Logged in to: ${logins.map(([realm]) => realm).join(", ")}`);
60
+ }
61
+ } else {
62
+ import_logger.logger.info("Not logged in via browser.");
63
+ }
64
+ return;
65
+ }
66
+ const realms = await logOutOfRealms(selected);
67
+ import_logger.logger.success(`Logged out of ${realms.join(", ")} (user token cleared).`);
68
+ import_logger.logger.dim('API key credentials are still stored. Use "farseer logout <tenant>" to remove specific ones.');
56
69
  });
57
70
  }
71
+ function sameRealm(stored, typed) {
72
+ return stored.toLowerCase() === typed.toLowerCase();
73
+ }
74
+ async function logOutOfRealms(logins) {
75
+ for (const [realm, login] of logins) {
76
+ if (!await (0, import_farseerService.revokeRefreshToken)(realm, login.refreshToken)) {
77
+ import_logger.logger.dim(`Could not end the ${realm} session at Keycloak; it is cleared here only.`);
78
+ }
79
+ (0, import_configService.clearUserAuth)(realm);
80
+ }
81
+ return logins.map(([realm]) => realm);
82
+ }
58
83
  // Annotate the CommonJS export names for ESM import in node:
59
84
  0 && (module.exports = {
60
85
  registerLogoutCommand
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/commands/logout.ts"],
4
- "sourcesContent": ["import { Command } from 'commander';\nimport { logger } from '../utils/logger';\nimport { removeCredential, clearUserAuth, listCredentials } from '../services/configService';\n\nexport function registerLogoutCommand(program: Command): void {\n program\n .command('logout [tenant]')\n .description('Logout from Farseer (remove credentials)')\n .option('--all', 'Remove all credentials')\n .action(async (tenant, options) => {\n if (options.all) {\n // Remove all credentials\n const credentials = listCredentials();\n const tenants = Object.keys(credentials);\n\n if (tenants.length === 0) {\n logger.info('No credentials stored.');\n return;\n }\n\n for (const t of tenants) {\n removeCredential(t);\n }\n clearUserAuth();\n\n logger.success(`Removed credentials for ${tenants.length} tenant(s).`);\n return;\n }\n\n if (tenant) {\n // Remove specific tenant\n const removed = removeCredential(tenant);\n if (removed) {\n logger.success(`Removed credentials for tenant: ${tenant}`);\n } else {\n logger.warning(`No credentials found for tenant: ${tenant}`);\n }\n } else {\n // Remove user auth token\n clearUserAuth();\n logger.success('Logged out (user token cleared).');\n logger.dim(\n 'API key credentials are still stored. Use \"farseer logout <tenant>\" to remove specific ones.',\n );\n }\n });\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAuB;AACvB,2BAAiE;AAE1D,SAAS,sBAAsB,SAAwB;AAC1D,UACK,QAAQ,iBAAiB,EACzB,YAAY,0CAA0C,EACtD,OAAO,SAAS,wBAAwB,EACxC,OAAO,OAAO,QAAQ,YAAY;AAC/B,QAAI,QAAQ,KAAK;AAEb,YAAM,kBAAc,sCAAgB;AACpC,YAAM,UAAU,OAAO,KAAK,WAAW;AAEvC,UAAI,QAAQ,WAAW,GAAG;AACtB,6BAAO,KAAK,wBAAwB;AACpC;AAAA,MACJ;AAEA,iBAAW,KAAK,SAAS;AACrB,mDAAiB,CAAC;AAAA,MACtB;AACA,8CAAc;AAEd,2BAAO,QAAQ,2BAA2B,QAAQ,MAAM,aAAa;AACrE;AAAA,IACJ;AAEA,QAAI,QAAQ;AAER,YAAM,cAAU,uCAAiB,MAAM;AACvC,UAAI,SAAS;AACT,6BAAO,QAAQ,mCAAmC,MAAM,EAAE;AAAA,MAC9D,OAAO;AACH,6BAAO,QAAQ,oCAAoC,MAAM,EAAE;AAAA,MAC/D;AAAA,IACJ,OAAO;AAEH,8CAAc;AACd,2BAAO,QAAQ,kCAAkC;AACjD,2BAAO;AAAA,QACH;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ,CAAC;AACT;",
6
- "names": []
4
+ "sourcesContent": ["import { Command } from 'commander';\nimport { logger } from '../utils/logger';\nimport {\n removeCredential,\n clearUserAuth,\n listCredentials,\n listUserAuths,\n type UserAuth,\n} from '../services/configService';\nimport { revokeRefreshToken } from '../services/farseerService';\n\nexport function registerLogoutCommand(program: Command): void {\n program\n .command('logout [tenant]')\n .description('Logout from Farseer (remove credentials)')\n .option('--all', 'Remove all credentials')\n .option('--realm <realm>', \"Clear only this realm's browser login\")\n .action(async (tenant, options) => {\n if (options.all) {\n // Remove all credentials\n const tenants = Object.keys(listCredentials());\n const realms = await logOutOfRealms(Object.entries(listUserAuths()));\n\n if (tenants.length === 0 && realms.length === 0) {\n logger.info('No credentials stored.');\n return;\n }\n\n for (const t of tenants) {\n removeCredential(t);\n }\n\n logger.success(\n `Removed credentials for ${tenants.length} tenant(s) and ${realms.length} browser login(s).`,\n );\n return;\n }\n\n if (tenant) {\n // Remove specific tenant\n const removed = removeCredential(tenant);\n if (removed) {\n logger.success(`Removed credentials for tenant: ${tenant}`);\n } else {\n logger.warning(`No credentials found for tenant: ${tenant}`);\n }\n return;\n }\n\n // Remove browser logins: one realm's, or all of them\n const logins = Object.entries(listUserAuths());\n const selected = options.realm ? logins.filter(([realm]) => sameRealm(realm, options.realm)) : logins;\n\n if (selected.length === 0) {\n if (options.realm) {\n logger.warning(`No browser login for realm: ${options.realm}`);\n if (logins.length > 0) {\n logger.dim(`Logged in to: ${logins.map(([realm]) => realm).join(', ')}`);\n }\n } else {\n logger.info('Not logged in via browser.');\n }\n return;\n }\n\n const realms = await logOutOfRealms(selected);\n logger.success(`Logged out of ${realms.join(', ')} (user token cleared).`);\n logger.dim('API key credentials are still stored. Use \"farseer logout <tenant>\" to remove specific ones.');\n });\n}\n\n/**\n * Realm names are case-sensitive in Keycloak, but people type them from the\n * organisation name \u2014 `login --realm jgl` itself resolves to `JGL`.\n */\nfunction sameRealm(stored: string, typed: string): boolean {\n return stored.toLowerCase() === typed.toLowerCase();\n}\n\n/** Ends each session at Keycloak, then clears it here whatever Keycloak said. */\nasync function logOutOfRealms(logins: [string, UserAuth][]): Promise<string[]> {\n for (const [realm, login] of logins) {\n if (!(await revokeRefreshToken(realm, login.refreshToken))) {\n logger.dim(`Could not end the ${realm} session at Keycloak; it is cleared here only.`);\n }\n clearUserAuth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AAK,MAAM,KAAK,EAAE,KAAK,IAAI,CAAC,EAAE;AAAA,QAC3E;AAAA,MACJ,OAAO;AACH,6BAAO,KAAK,4BAA4B;AAAA,MAC5C;AACA;AAAA,IACJ;AAEA,UAAM,SAAS,MAAM,eAAe,QAAQ;AAC5C,yBAAO,QAAQ,iBAAiB,OAAO,KAAK,IAAI,CAAC,wBAAwB;AACzE,yBAAO,IAAI,8FAA8F;AAAA,EAC7G,CAAC;AACT;AAMA,SAAS,UAAU,QAAgB,OAAwB;AACvD,SAAO,OAAO,YAAY,MAAM,MAAM,YAAY;AACtD;AAGA,eAAe,eAAe,QAAiD;AAC3E,aAAW,CAAC,OAAO,KAAK,KAAK,QAAQ;AACjC,QAAI,CAAE,UAAM,0CAAmB,OAAO,MAAM,YAAY,GAAI;AACxD,2BAAO,IAAI,qBAAqB,KAAK,gDAAgD;AAAA,IACzF;AACA,4CAAc,KAAK;AAAA,EACvB;AACA,SAAO,OAAO,IAAI,CAAC,CAAC,KAAK,MAAM,KAAK;AACxC;",
6
+ "names": ["realms"]
7
7
  }
@@ -34,6 +34,7 @@ module.exports = __toCommonJS(run_exports);
34
34
  var import_logger = require("../utils/logger");
35
35
  var import_configService = require("../services/configService");
36
36
  var import_farseerService = require("../services/farseerService");
37
+ var import_realms = require("../services/realms");
37
38
  var import_authErrors = require("../services/authErrors");
38
39
  var import_preflight = require("../services/preflight");
39
40
  var import_helpers = require("../utils/helpers");
@@ -69,31 +70,13 @@ async function getRunCredentials(organisation, tenant, tenantIdOverride) {
69
70
  basePath: credential.basePath
70
71
  };
71
72
  }
72
- const auth = (0, import_configService.getUserAuth)();
73
- if (auth) {
74
- if (!(0, import_configService.isUserAuthValid)()) {
75
- import_logger.logger.dim("Token expired, refreshing...");
76
- const refreshed = await (0, import_farseerService.refreshAccessToken)(auth.refreshToken, auth.realm || "master");
77
- if (refreshed) {
78
- (0, import_configService.setUserAuth)({
79
- accessToken: refreshed.accessToken,
80
- refreshToken: refreshed.refreshToken,
81
- expiresAt: new Date(Date.now() + refreshed.expiresIn * 1e3).toISOString(),
82
- realm: auth.realm
83
- });
84
- import_logger.logger.success("Token refreshed");
85
- } else {
86
- import_logger.logger.warning("Could not refresh token. Please login again with: farseer login");
87
- }
88
- }
89
- const updatedAuth = (0, import_configService.getUserAuth)();
90
- if (updatedAuth && (0, import_configService.isUserAuthValid)()) {
91
- return {
92
- tenantId: tenantIdOverride || tenant,
93
- accessToken: updatedAuth.accessToken,
94
- basePath: (0, import_configService.generateBasePath)(organisation)
95
- };
96
- }
73
+ const accessToken = await (0, import_farseerService.getFreshAccessToken)(await (0, import_realms.realmForOrganisation)(organisation));
74
+ if (accessToken) {
75
+ return {
76
+ tenantId: tenantIdOverride || tenant,
77
+ accessToken,
78
+ basePath: (0, import_configService.generateBasePath)(organisation)
79
+ };
97
80
  }
98
81
  return null;
99
82
  }
@@ -126,7 +109,7 @@ function registerRunCommand(program) {
126
109
  }
127
110
  const credentials = await getRunCredentials(organisation, tenant, options.tenantId);
128
111
  if (!credentials) {
129
- (0, import_authErrors.showLoginPrompt)(tenant);
112
+ (0, import_authErrors.showLoginPrompt)(tenant, organisation);
130
113
  process.exit(1);
131
114
  }
132
115
  const tenantDir = (0, import_helpers.getTenantDir)(tenant);
@@ -217,7 +200,7 @@ function registerRunCommand(program) {
217
200
  let script = appName;
218
201
  const credentials = await getRunCredentials(organisation, tenant, options.tenantId);
219
202
  if (!credentials) {
220
- (0, import_authErrors.showLoginPrompt)(tenant);
203
+ (0, import_authErrors.showLoginPrompt)(tenant, organisation);
221
204
  process.exit(1);
222
205
  }
223
206
  if (script.toLowerCase().startsWith("scripts/")) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/commands/run.ts"],
4
- "sourcesContent": ["import { Command } from 'commander';\nimport { logger } from '../utils/logger';\nimport { getCredential, getUserAuth, isUserAuthValid, setUserAuth, generateBasePath } from '../services/configService';\nimport { refreshAccessToken } from '../services/farseerService';\nimport { showLoginPrompt } from '../services/authErrors';\nimport { preflightForPair } from '../services/preflight';\nimport { getTenantDir, getTenantSrcDir, getTenantFilesDir, parseAppArgs, resolveAppOrExit } from '../utils/helpers';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { spawn } from 'child_process';\n\n/**\n * Find a script file recursively in a directory.\n * Returns the relative path from baseDir if found, null otherwise.\n */\nfunction findScriptRecursively(baseDir: string, scriptName: string): string | null {\n if (!fs.existsSync(baseDir)) {\n return null;\n }\n\n const search = (dir: string, relativePath: string = ''): string | null => {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const item of items) {\n const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;\n\n if (item.isFile() && item.name === scriptName) {\n return itemRelPath;\n }\n\n if (item.isDirectory()) {\n const found = search(path.join(dir, item.name), itemRelPath);\n if (found) return found;\n }\n }\n\n return null;\n };\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(\n organisation: string,\n tenant: string,\n tenantIdOverride?: string,\n): Promise<RunCredentials | null> {\n // 1. Prefer API key when one is saved for this tenant \u2014 it's already the\n // canonical credential, has the correct basePath, and doesn't expire\n // during a long-running script.\n const credential = getCredential(tenant);\n if (credential) {\n return {\n tenantId: tenantIdOverride || credential.tenantId,\n apiKey: credential.apiKey,\n basePath: credential.basePath,\n };\n }\n\n // 2. Fall back to browser-login JWT. Refresh proactively if expired.\n const auth = getUserAuth();\n if (auth) {\n if (!isUserAuthValid()) {\n logger.dim('Token expired, refreshing...');\n const refreshed = await refreshAccessToken(auth.refreshToken, auth.realm || 'master');\n if (refreshed) {\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 logger.success('Token refreshed');\n } else {\n logger.warning('Could not refresh token. Please login again with: farseer login');\n }\n }\n\n const updatedAuth = getUserAuth();\n if (updatedAuth && isUserAuthValid()) {\n return {\n tenantId: tenantIdOverride || tenant,\n accessToken: updatedAuth.accessToken,\n basePath: generateBasePath(organisation),\n };\n }\n }\n\n return null;\n}\n\n// Helper to collect multiple --arg options\nfunction collectArgs(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n\nexport function registerRunCommand(program: Command): void {\n program\n .command('run [args...]')\n .description('Run an app locally with injected credentials')\n .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')\n .option('--arg <value>', 'Pass argument in format \"Name=Value\" (can be used multiple times)', collectArgs, [])\n .option('--id <id>', 'Select the app by its numeric id (use when names collide)')\n .action(async (args: string[], options) => {\n const { organisation, tenant, appName } = parseAppArgs(args, {\n allowEmptyName: !!options.id,\n command: 'run',\n });\n // Guard (auth + org\u220Btenant) first, then fetch the app details.\n const { client: api } = await preflightForPair(organisation, tenant);\n\n // Find the app\n logger.info(appName ? `Loading app: ${appName}...` : `Loading app by id: ${options.id}...`);\n const app = await resolveAppOrExit(api, { appName, id: options.id, tenant });\n\n const runScripts = app.scriptFiles ?? [];\n if (!app.mainScriptFileId || runScripts.length === 0) {\n logger.error(`App \"${app.name}\" has no scripts configured.`);\n logger.dim('Configure the app with: farseer app configure \"' + app.name + '\" --entrypoint <script>');\n process.exit(1);\n }\n\n // Find the entrypoint script name\n const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);\n if (!mainScript) {\n logger.error(`Entrypoint script not found for app \"${app.name}\".`);\n process.exit(1);\n }\n\n // Normalize script name - handle both \"test.ts\" and \"Scripts/test.ts\" formats\n let scriptName = mainScript.name;\n if (scriptName.toLowerCase().startsWith('scripts/')) {\n scriptName = scriptName.substring('scripts/'.length);\n }\n\n // Get credentials for running\n const credentials = await getRunCredentials(organisation, tenant, options.tenantId);\n\n if (!credentials) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Script path is relative to files/Scripts/ folder\n // First try direct path, then search recursively if not found\n let scriptPath = path.resolve(srcDir, scriptName);\n let relativeScriptPath = `files/Scripts/${scriptName}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try to find the script recursively in the files directory\n const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n logger.dim(`Found script at: ${foundPath}`);\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n logger.error(`Script not found locally: ${scriptPath}`);\n logger.dim('Run \"farseer pull ' + tenant + '\" to download scripts first.');\n process.exit(1);\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n logger.error(`Dependencies not installed for ${tenant}`);\n logger.dim(`Run: farseer install ${tenant}`);\n process.exit(1);\n }\n\n // Parse arguments\n const appArgs: Record<string, string> = {};\n\n // Start with default values from app config.\n // defaultValue is optional on the API type; treat missing as ''\n // so we always hand a string to the runner.\n for (const arg of app.expectedArguments) {\n appArgs[arg.name] = arg.defaultValue ?? '';\n }\n\n // Override with provided arguments\n for (const argStr of options.arg) {\n const eqIndex = argStr.indexOf('=');\n if (eqIndex === -1) {\n logger.error(`Invalid argument format: ${argStr}`);\n logger.dim('Use format: --arg \"Name=Value\"');\n process.exit(1);\n }\n const name = argStr.substring(0, eqIndex);\n const value = argStr.substring(eqIndex + 1);\n appArgs[name] = value;\n }\n\n const authType = credentials.apiKey ? 'API key' : 'access token';\n logger.info(`Running app \"${app.name}\" (${scriptName}) for tenant ${tenant} (using ${authType})...`);\n\n // Show arguments being used\n if (Object.keys(appArgs).length > 0) {\n logger.dim('Arguments:');\n for (const [key, value] of Object.entries(appArgs)) {\n logger.dim(` ${key}: ${value}`);\n }\n }\n console.log();\n\n // Build environment variables based on auth type\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 from app 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 with credentials injected via environment variables, arguments via command line\n const quotedScriptPath = `\"${relativeScriptPath}\"`;\n const child = spawn('npx', ['tsx', quotedScriptPath, ...cmdArgs], {\n stdio: 'inherit',\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.on('close', (code) => {\n if (code !== 0) {\n logger.error(`Script exited with code ${code}`);\n process.exit(code || 1);\n }\n });\n\n child.on('error', (err) => {\n logger.error(`Failed to run script: ${err.message}`);\n logger.dim('Make sure tsx is installed: npm install -g tsx');\n process.exit(1);\n });\n });\n\n // Keep the old script-based run as a separate command\n program\n .command('run-script <args...>')\n .description('Run a script directly (without app wrapper)')\n .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')\n .action(async (args: string[], options) => {\n const { organisation, tenant, appName } = parseAppArgs(args);\n // Same guard as `run`, but the result is discarded: run-script needs\n // no client of its own. It's here for the gate alone \u2014 the script is\n // handed live credentials for this tenant a few lines down, so the\n // pair has to be proven before that happens. That makes it the one\n // command that trades zero network calls for one.\n await preflightForPair(organisation, tenant);\n let script = appName;\n const credentials = await getRunCredentials(organisation, tenant, options.tenantId);\n\n if (!credentials) {\n showLoginPrompt(tenant);\n process.exit(1);\n }\n\n // Normalize script path - strip Scripts/ prefix if present\n if (script.toLowerCase().startsWith('scripts/')) {\n script = script.substring('scripts/'.length);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Script path is relative to files/Scripts/ folder\n // First try direct path, then search recursively if not found\n let scriptPath = path.resolve(srcDir, script);\n let relativeScriptPath = `files/Scripts/${script}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try to find the script recursively in the files directory\n const foundPath = findScriptRecursively(filesDir, path.basename(script));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n logger.dim(`Found script at: ${foundPath}`);\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n logger.error(`Script not found: ${scriptPath}`);\n process.exit(1);\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n logger.error(`Dependencies not installed for ${tenant}`);\n logger.dim(`Run: farseer install ${tenant}`);\n process.exit(1);\n }\n\n const authType = credentials.apiKey ? 'API key' : 'access token';\n logger.info(`Running ${script} for tenant ${tenant} (using ${authType})...`);\n console.log();\n\n // Build environment variables based on auth type\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 const quotedScriptPath = `\"${relativeScriptPath}\"`;\n const child = spawn('npx', ['tsx', quotedScriptPath], {\n stdio: 'inherit',\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.on('close', (code) => {\n if (code !== 0) {\n logger.error(`Script exited with code ${code}`);\n process.exit(code || 1);\n }\n });\n\n child.on('error', (err) => {\n logger.error(`Failed to run script: ${err.message}`);\n logger.dim('Make sure tsx is installed: npm install -g tsx');\n process.exit(1);\n });\n });\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAuB;AACvB,2BAA2F;AAC3F,4BAAmC;AACnC,wBAAgC;AAChC,uBAAiC;AACjC,qBAAiG;AACj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} from 'commander';\nimport { logger } from '../utils/logger';\nimport { getCredential, generateBasePath } from '../services/configService';\nimport { getFreshAccessToken } from '../services/farseerService';\nimport { realmForOrganisation } from '../services/realms';\nimport { showLoginPrompt } from '../services/authErrors';\nimport { preflightForPair } from '../services/preflight';\nimport { getTenantDir, getTenantSrcDir, getTenantFilesDir, parseAppArgs, resolveAppOrExit } from '../utils/helpers';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { spawn } from 'child_process';\n\n/**\n * Find a script file recursively in a directory.\n * Returns the relative path from baseDir if found, null otherwise.\n */\nfunction findScriptRecursively(baseDir: string, scriptName: string): string | null {\n if (!fs.existsSync(baseDir)) {\n return null;\n }\n\n const search = (dir: string, relativePath: string = ''): string | null => {\n const items = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const item of items) {\n const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;\n\n if (item.isFile() && item.name === scriptName) {\n return itemRelPath;\n }\n\n if (item.isDirectory()) {\n const found = search(path.join(dir, item.name), itemRelPath);\n if (found) return found;\n }\n }\n\n return null;\n };\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(\n organisation: string,\n tenant: string,\n tenantIdOverride?: string,\n): Promise<RunCredentials | null> {\n // 1. Prefer API key when one is saved for this tenant \u2014 it's already the\n // canonical credential, has the correct basePath, and doesn't expire\n // during a long-running script.\n const credential = getCredential(tenant);\n if (credential) {\n return {\n tenantId: tenantIdOverride || credential.tenantId,\n apiKey: credential.apiKey,\n basePath: credential.basePath,\n };\n }\n\n // 2. Fall back to the browser login for the organisation's realm, refreshed if expired.\n const accessToken = await getFreshAccessToken(await realmForOrganisation(organisation));\n if (accessToken) {\n return {\n tenantId: tenantIdOverride || tenant,\n accessToken,\n basePath: generateBasePath(organisation),\n };\n }\n return null;\n}\n\n// Helper to collect multiple --arg options\nfunction collectArgs(value: string, previous: string[]): string[] {\n return previous.concat([value]);\n}\n\nexport function registerRunCommand(program: Command): void {\n program\n .command('run [args...]')\n .description('Run an app locally with injected credentials')\n .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')\n .option('--arg <value>', 'Pass argument in format \"Name=Value\" (can be used multiple times)', collectArgs, [])\n .option('--id <id>', 'Select the app by its numeric id (use when names collide)')\n .action(async (args: string[], options) => {\n const { organisation, tenant, appName } = parseAppArgs(args, {\n allowEmptyName: !!options.id,\n command: 'run',\n });\n // Guard (auth + org\u220Btenant) first, then fetch the app details.\n const { client: api } = await preflightForPair(organisation, tenant);\n\n // Find the app\n logger.info(appName ? `Loading app: ${appName}...` : `Loading app by id: ${options.id}...`);\n const app = await resolveAppOrExit(api, { appName, id: options.id, tenant });\n\n const runScripts = app.scriptFiles ?? [];\n if (!app.mainScriptFileId || runScripts.length === 0) {\n logger.error(`App \"${app.name}\" has no scripts configured.`);\n logger.dim('Configure the app with: farseer app configure \"' + app.name + '\" --entrypoint <script>');\n process.exit(1);\n }\n\n // Find the entrypoint script name\n const mainScript = runScripts.find((s) => s.id === app.mainScriptFileId);\n if (!mainScript) {\n logger.error(`Entrypoint script not found for app \"${app.name}\".`);\n process.exit(1);\n }\n\n // Normalize script name - handle both \"test.ts\" and \"Scripts/test.ts\" formats\n let scriptName = mainScript.name;\n if (scriptName.toLowerCase().startsWith('scripts/')) {\n scriptName = scriptName.substring('scripts/'.length);\n }\n\n // Get credentials for running\n const credentials = await getRunCredentials(organisation, tenant, options.tenantId);\n\n if (!credentials) {\n showLoginPrompt(tenant, organisation);\n process.exit(1);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Script path is relative to files/Scripts/ folder\n // First try direct path, then search recursively if not found\n let scriptPath = path.resolve(srcDir, scriptName);\n let relativeScriptPath = `files/Scripts/${scriptName}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try to find the script recursively in the files directory\n const foundPath = findScriptRecursively(filesDir, path.basename(scriptName));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n logger.dim(`Found script at: ${foundPath}`);\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n logger.error(`Script not found locally: ${scriptPath}`);\n logger.dim('Run \"farseer pull ' + tenant + '\" to download scripts first.');\n process.exit(1);\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n logger.error(`Dependencies not installed for ${tenant}`);\n logger.dim(`Run: farseer install ${tenant}`);\n process.exit(1);\n }\n\n // Parse arguments\n const appArgs: Record<string, string> = {};\n\n // Start with default values from app config.\n // defaultValue is optional on the API type; treat missing as ''\n // so we always hand a string to the runner.\n for (const arg of app.expectedArguments) {\n appArgs[arg.name] = arg.defaultValue ?? '';\n }\n\n // Override with provided arguments\n for (const argStr of options.arg) {\n const eqIndex = argStr.indexOf('=');\n if (eqIndex === -1) {\n logger.error(`Invalid argument format: ${argStr}`);\n logger.dim('Use format: --arg \"Name=Value\"');\n process.exit(1);\n }\n const name = argStr.substring(0, eqIndex);\n const value = argStr.substring(eqIndex + 1);\n appArgs[name] = value;\n }\n\n const authType = credentials.apiKey ? 'API key' : 'access token';\n logger.info(`Running app \"${app.name}\" (${scriptName}) for tenant ${tenant} (using ${authType})...`);\n\n // Show arguments being used\n if (Object.keys(appArgs).length > 0) {\n logger.dim('Arguments:');\n for (const [key, value] of Object.entries(appArgs)) {\n logger.dim(` ${key}: ${value}`);\n }\n }\n console.log();\n\n // Build environment variables based on auth type\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 from app 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 with credentials injected via environment variables, arguments via command line\n const quotedScriptPath = `\"${relativeScriptPath}\"`;\n const child = spawn('npx', ['tsx', quotedScriptPath, ...cmdArgs], {\n stdio: 'inherit',\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.on('close', (code) => {\n if (code !== 0) {\n logger.error(`Script exited with code ${code}`);\n process.exit(code || 1);\n }\n });\n\n child.on('error', (err) => {\n logger.error(`Failed to run script: ${err.message}`);\n logger.dim('Make sure tsx is installed: npm install -g tsx');\n process.exit(1);\n });\n });\n\n // Keep the old script-based run as a separate command\n program\n .command('run-script <args...>')\n .description('Run a script directly (without app wrapper)')\n .option('--tenant-id <id>', 'Tenant ID for env variables (defaults to tenant name)')\n .action(async (args: string[], options) => {\n const { organisation, tenant, appName } = parseAppArgs(args);\n // Same guard as `run`, but the result is discarded: run-script needs\n // no client of its own. It's here for the gate alone \u2014 the script is\n // handed live credentials for this tenant a few lines down, so the\n // pair has to be proven before that happens. That makes it the one\n // command that trades zero network calls for one.\n await preflightForPair(organisation, tenant);\n let script = appName;\n const credentials = await getRunCredentials(organisation, tenant, options.tenantId);\n\n if (!credentials) {\n showLoginPrompt(tenant, organisation);\n process.exit(1);\n }\n\n // Normalize script path - strip Scripts/ prefix if present\n if (script.toLowerCase().startsWith('scripts/')) {\n script = script.substring('scripts/'.length);\n }\n\n const tenantDir = getTenantDir(tenant);\n const srcDir = getTenantSrcDir(tenant);\n const filesDir = getTenantFilesDir(tenant);\n\n // Script path is relative to files/Scripts/ folder\n // First try direct path, then search recursively if not found\n let scriptPath = path.resolve(srcDir, script);\n let relativeScriptPath = `files/Scripts/${script}`;\n\n if (!fs.existsSync(scriptPath)) {\n // Try to find the script recursively in the files directory\n const foundPath = findScriptRecursively(filesDir, path.basename(script));\n if (foundPath) {\n scriptPath = path.resolve(filesDir, foundPath);\n relativeScriptPath = `files/${foundPath}`;\n logger.dim(`Found script at: ${foundPath}`);\n }\n }\n\n if (!fs.existsSync(scriptPath)) {\n logger.error(`Script not found: ${scriptPath}`);\n process.exit(1);\n }\n\n // Check if node_modules exists\n const nodeModulesPath = path.join(tenantDir, 'node_modules');\n if (!fs.existsSync(nodeModulesPath)) {\n logger.error(`Dependencies not installed for ${tenant}`);\n logger.dim(`Run: farseer install ${tenant}`);\n process.exit(1);\n }\n\n const authType = credentials.apiKey ? 'API key' : 'access token';\n logger.info(`Running ${script} for tenant ${tenant} (using ${authType})...`);\n console.log();\n\n // Build environment variables based on auth type\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 const quotedScriptPath = `\"${relativeScriptPath}\"`;\n const child = spawn('npx', ['tsx', quotedScriptPath], {\n stdio: 'inherit',\n cwd: tenantDir,\n shell: true,\n env: envVars,\n });\n\n child.on('close', (code) => {\n if (code !== 0) {\n logger.error(`Script exited with code ${code}`);\n process.exit(code || 1);\n }\n });\n\n child.on('error', (err) => {\n logger.error(`Failed to run script: ${err.message}`);\n logger.dim('Make sure tsx is installed: npm install -g tsx');\n process.exit(1);\n });\n });\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAuB;AACvB,2BAAgD;AAChD,4BAAoC;AACpC,oBAAqC;AACrC,wBAAgC;AAChC,uBAAiC;AACjC,qBAAiG;AACjG,SAAoB;AACpB,WAAsB;AACtB,2BAAsB;AAMtB,SAAS,sBAAsB,SAAiB,YAAmC;AAC/E,MAAI,CAAC,GAAG,WAAW,OAAO,GAAG;AACzB,WAAO;AAAA,EACX;AAEA,QAAM,SAAS,CAAC,KAAa,eAA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AAI,YAAY,aAAa;AACzB,cAAQ,gBAAgB,YAAY;AAAA,IACxC;AAEA,UAAM,mBAAmB,IAAI,kBAAkB;AAC/C,UAAM,YAAQ,4BAAM,OAAO,CAAC,OAAO,gBAAgB,GAAG;AAAA,MAClD,OAAO;AAAA,MACP,KAAK;AAAA,MACL,OAAO;AAAA,MACP,KAAK;AAAA,IACT,CAAC;AAED,UAAM,GAAG,SAAS,CAAC,SAAS;AACxB,UAAI,SAAS,GAAG;AACZ,6BAAO,MAAM,2BAA2B,IAAI,EAAE;AAC9C,gBAAQ,KAAK,QAAQ,CAAC;AAAA,MAC1B;AAAA,IACJ,CAAC;AAED,UAAM,GAAG,SAAS,CAAC,QAAQ;AACvB,2BAAO,MAAM,yBAAyB,IAAI,OAAO,EAAE;AACnD,2BAAO,IAAI,gDAAgD;AAC3D,cAAQ,KAAK,CAAC;AAAA,IAClB,CAAC;AAAA,EACL,CAAC;AACT;",
6
6
  "names": []
7
7
  }
@@ -37,22 +37,18 @@ function registerWhoamiCommand(program) {
37
37
  import_logger.logger.dim(" Pass a tenant per command, or set: export FARSEER_TENANT=<tenant>");
38
38
  }
39
39
  console.log();
40
- const userAuth = (0, import_configService.getUserAuth)();
41
- if (userAuth) {
42
- if ((0, import_configService.isUserAuthValid)()) {
43
- const expiresAt = new Date(userAuth.expiresAt);
44
- const realm = userAuth.realm || "master";
45
- import_logger.logger.success("Logged in via browser");
46
- import_logger.logger.dim(`Realm: ${realm}`);
47
- import_logger.logger.dim(`Token expires: ${expiresAt.toLocaleString()}`);
40
+ const logins = Object.entries((0, import_configService.listUserAuths)());
41
+ if (logins.length === 0) {
42
+ import_logger.logger.dim("Not logged in via browser");
43
+ }
44
+ for (const [realm, login] of logins) {
45
+ if ((0, import_configService.isUserAuthValid)(login)) {
46
+ import_logger.logger.success(`Logged in via browser (realm: ${realm})`);
47
+ import_logger.logger.dim(`Token expires: ${new Date(login.expiresAt).toLocaleString()}`);
48
48
  } else {
49
- const realm = userAuth.realm || "master";
50
- import_logger.logger.warning("Browser login expired");
51
- import_logger.logger.dim(`Realm: ${realm}`);
52
- import_logger.logger.dim("Run: farseer login");
49
+ import_logger.logger.warning(`Browser login expired (realm: ${realm})`);
50
+ import_logger.logger.dim(`Run: farseer login${realm === import_configService.DEFAULT_REALM ? "" : ` --realm ${realm}`}`);
53
51
  }
54
- } else {
55
- import_logger.logger.dim("Not logged in via browser");
56
52
  }
57
53
  console.log();
58
54
  const credentials = (0, import_configService.listCredentials)();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/commands/whoami.ts"],
4
- "sourcesContent": ["import { Command } from 'commander';\nimport { logger } from '../utils/logger';\nimport { getUserAuth, isUserAuthValid, listCredentials, getTenantOrg } from '../services/configService';\n\nexport function registerWhoamiCommand(program: Command): void {\n program\n .command('whoami')\n .description('Show current login status and configured tenants')\n .action(async () => {\n logger.header('Farseer Status');\n\n // Active target for THIS shell \u2014 what a command run with no tenant\n // argument will operate on. Resolved from FARSEER_TENANT (+\n // FARSEER_ORG / the saved mapping), mirroring the command\n // resolvers. There is no machine-global default any more, so if\n // this is unset every command needs an explicit tenant argument.\n const envTenant = process.env.FARSEER_TENANT;\n if (envTenant) {\n const envOrg = process.env.FARSEER_ORG || getTenantOrg(envTenant) || envTenant;\n logger.info('Active target (this shell):');\n console.log(` ${envTenant}${envOrg !== envTenant ? ` (org: ${envOrg})` : ''}`);\n logger.dim(' from FARSEER_TENANT');\n } else {\n logger.info('Active target (this shell): none');\n logger.dim(' Pass a tenant per command, or set: export FARSEER_TENANT=<tenant>');\n }\n\n console.log();\n\n // Check user auth (browser login)\n const userAuth = getUserAuth();\n if (userAuth) {\n if (isUserAuthValid()) {\n const expiresAt = new Date(userAuth.expiresAt);\n const realm = userAuth.realm || 'master';\n logger.success('Logged in via browser');\n logger.dim(`Realm: ${realm}`);\n logger.dim(`Token expires: ${expiresAt.toLocaleString()}`);\n } else {\n const realm = userAuth.realm || 'master';\n logger.warning('Browser login expired');\n logger.dim(`Realm: ${realm}`);\n logger.dim('Run: farseer login');\n }\n } else {\n logger.dim('Not logged in via browser');\n }\n\n console.log();\n\n // List configured tenants (API key)\n const credentials = listCredentials();\n const tenants = Object.keys(credentials);\n\n if (tenants.length > 0) {\n logger.info(`Configured tenants (${tenants.length}):`);\n for (const tenant of tenants) {\n const cred = credentials[tenant];\n const keyPreview = cred.apiKey.substring(0, 8) + '...';\n console.log(` ${tenant}`);\n console.log(` Base: ${cred.basePath}`);\n console.log(` Key: ${keyPreview}`);\n }\n } else {\n logger.dim('No tenants configured');\n logger.dim('Run: farseer config set <tenant> --api-key <key>');\n }\n });\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAuB;AACvB,2BAA4E;AAErE,SAAS,sBAAsB,SAAwB;AAC1D,UACK,QAAQ,QAAQ,EAChB,YAAY,kDAAkD,EAC9D,OAAO,YAAY;AAChB,yBAAO,OAAO,gBAAgB;AAO9B,UAAM,YAAY,QAAQ,IAAI;AAC9B,QAAI,WAAW;AACX,YAAM,SAAS,QAAQ,IAAI,mBAAe,mCAAa,SAAS,KAAK;AACrE,2BAAO,KAAK,6BAA6B;AACzC,cAAQ,IAAI,KAAK,SAAS,GAAG,WAAW,YAAY,UAAU,MAAM,MAAM,EAAE,EAAE;AAC9E,2BAAO,IAAI,uBAAuB;AAAA,IACtC,OAAO;AACH,2BAAO,KAAK,kCAAkC;AAC9C,2BAAO,IAAI,qEAAqE;AAAA,IACpF;AAEA,YAAQ,IAAI;AAGZ,UAAM,eAAW,kCAAY;AAC7B,QAAI,UAAU;AACV,cAAI,sCAAgB,GAAG;AACnB,cAAM,YAAY,IAAI,KAAK,SAAS,SAAS;AAC7C,cAAM,QAAQ,SAAS,SAAS;AAChC,6BAAO,QAAQ,uBAAuB;AACtC,6BAAO,IAAI,UAAU,KAAK,EAAE;AAC5B,6BAAO,IAAI,kBAAkB,UAAU,eAAe,CAAC,EAAE;AAAA,MAC7D,OAAO;AACH,cAAM,QAAQ,SAAS,SAAS;AAChC,6BAAO,QAAQ,uBAAuB;AACtC,6BAAO,IAAI,UAAU,KAAK,EAAE;AAC5B,6BAAO,IAAI,oBAAoB;AAAA,MACnC;AAAA,IACJ,OAAO;AACH,2BAAO,IAAI,2BAA2B;AAAA,IAC1C;AAEA,YAAQ,IAAI;AAGZ,UAAM,kBAAc,sCAAgB;AACpC,UAAM,UAAU,OAAO,KAAK,WAAW;AAEvC,QAAI,QAAQ,SAAS,GAAG;AACpB,2BAAO,KAAK,uBAAuB,QAAQ,MAAM,IAAI;AACrD,iBAAW,UAAU,SAAS;AAC1B,cAAM,OAAO,YAAY,MAAM;AAC/B,cAAM,aAAa,KAAK,OAAO,UAAU,GAAG,CAAC,IAAI;AACjD,gBAAQ,IAAI,KAAK,MAAM,EAAE;AACzB,gBAAQ,IAAI,aAAa,KAAK,QAAQ,EAAE;AACxC,gBAAQ,IAAI,aAAa,UAAU,EAAE;AAAA,MACzC;AAAA,IACJ,OAAO;AACH,2BAAO,IAAI,uBAAuB;AAClC,2BAAO,IAAI,kDAAkD;AAAA,IACjE;AAAA,EACJ,CAAC;AACT;",
4
+ "sourcesContent": ["import { Command } from 'commander';\nimport { logger } from '../utils/logger';\nimport {\n DEFAULT_REALM,\n getTenantOrg,\n isUserAuthValid,\n listCredentials,\n listUserAuths,\n} from '../services/configService';\n\nexport function registerWhoamiCommand(program: Command): void {\n program\n .command('whoami')\n .description('Show current login status and configured tenants')\n .action(async () => {\n logger.header('Farseer Status');\n\n // Active target for THIS shell \u2014 what a command run with no tenant\n // argument will operate on. Resolved from FARSEER_TENANT (+\n // FARSEER_ORG / the saved mapping), mirroring the command\n // resolvers. There is no machine-global default any more, so if\n // this is unset every command needs an explicit tenant argument.\n const envTenant = process.env.FARSEER_TENANT;\n if (envTenant) {\n const envOrg = process.env.FARSEER_ORG || getTenantOrg(envTenant) || envTenant;\n logger.info('Active target (this shell):');\n console.log(` ${envTenant}${envOrg !== envTenant ? ` (org: ${envOrg})` : ''}`);\n logger.dim(' from FARSEER_TENANT');\n } else {\n logger.info('Active target (this shell): none');\n logger.dim(' Pass a tenant per command, or set: export FARSEER_TENANT=<tenant>');\n }\n\n console.log();\n\n // Browser logins, one per Keycloak realm\n const logins = Object.entries(listUserAuths());\n if (logins.length === 0) {\n logger.dim('Not logged in via browser');\n }\n for (const [realm, login] of logins) {\n if (isUserAuthValid(login)) {\n logger.success(`Logged in via browser (realm: ${realm})`);\n logger.dim(`Token expires: ${new Date(login.expiresAt).toLocaleString()}`);\n } else {\n logger.warning(`Browser login expired (realm: ${realm})`);\n logger.dim(`Run: farseer login${realm === DEFAULT_REALM ? '' : ` --realm ${realm}`}`);\n }\n }\n\n console.log();\n\n // List configured tenants (API key)\n const credentials = listCredentials();\n const tenants = Object.keys(credentials);\n\n if (tenants.length > 0) {\n logger.info(`Configured tenants (${tenants.length}):`);\n for (const tenant of tenants) {\n const cred = credentials[tenant];\n const keyPreview = cred.apiKey.substring(0, 8) + '...';\n console.log(` ${tenant}`);\n console.log(` Base: ${cred.basePath}`);\n console.log(` Key: ${keyPreview}`);\n }\n } else {\n logger.dim('No tenants configured');\n logger.dim('Run: farseer config set <tenant> --api-key <key>');\n }\n });\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAAuB;AACvB,2BAMO;AAEA,SAAS,sBAAsB,SAAwB;AAC1D,UACK,QAAQ,QAAQ,EAChB,YAAY,kDAAkD,EAC9D,OAAO,YAAY;AAChB,yBAAO,OAAO,gBAAgB;AAO9B,UAAM,YAAY,QAAQ,IAAI;AAC9B,QAAI,WAAW;AACX,YAAM,SAAS,QAAQ,IAAI,mBAAe,mCAAa,SAAS,KAAK;AACrE,2BAAO,KAAK,6BAA6B;AACzC,cAAQ,IAAI,KAAK,SAAS,GAAG,WAAW,YAAY,UAAU,MAAM,MAAM,EAAE,EAAE;AAC9E,2BAAO,IAAI,uBAAuB;AAAA,IACtC,OAAO;AACH,2BAAO,KAAK,kCAAkC;AAC9C,2BAAO,IAAI,qEAAqE;AAAA,IACpF;AAEA,YAAQ,IAAI;AAGZ,UAAM,SAAS,OAAO,YAAQ,oCAAc,CAAC;AAC7C,QAAI,OAAO,WAAW,GAAG;AACrB,2BAAO,IAAI,2BAA2B;AAAA,IAC1C;AACA,eAAW,CAAC,OAAO,KAAK,KAAK,QAAQ;AACjC,cAAI,sCAAgB,KAAK,GAAG;AACxB,6BAAO,QAAQ,iCAAiC,KAAK,GAAG;AACxD,6BAAO,IAAI,kBAAkB,IAAI,KAAK,MAAM,SAAS,EAAE,eAAe,CAAC,EAAE;AAAA,MAC7E,OAAO;AACH,6BAAO,QAAQ,iCAAiC,KAAK,GAAG;AACxD,6BAAO,IAAI,qBAAqB,UAAU,qCAAgB,KAAK,YAAY,KAAK,EAAE,EAAE;AAAA,MACxF;AAAA,IACJ;AAEA,YAAQ,IAAI;AAGZ,UAAM,kBAAc,sCAAgB;AACpC,UAAM,UAAU,OAAO,KAAK,WAAW;AAEvC,QAAI,QAAQ,SAAS,GAAG;AACpB,2BAAO,KAAK,uBAAuB,QAAQ,MAAM,IAAI;AACrD,iBAAW,UAAU,SAAS;AAC1B,cAAM,OAAO,YAAY,MAAM;AAC/B,cAAM,aAAa,KAAK,OAAO,UAAU,GAAG,CAAC,IAAI;AACjD,gBAAQ,IAAI,KAAK,MAAM,EAAE;AACzB,gBAAQ,IAAI,aAAa,KAAK,QAAQ,EAAE;AACxC,gBAAQ,IAAI,aAAa,UAAU,EAAE;AAAA,MACzC;AAAA,IACJ,OAAO;AACH,2BAAO,IAAI,uBAAuB;AAClC,2BAAO,IAAI,kDAAkD;AAAA,IACjE;AAAA,EACJ,CAAC;AACT;",
6
6
  "names": []
7
7
  }
@@ -311,6 +311,8 @@ Steps to follow:
311
311
  Copy the source JSON file and modify:
312
312
  - Change "name" to "${newAppName}"
313
313
  - **IMPORTANT: Remove "_remote" field** (this makes it a new app)
314
+ - Set "schedule" to null, unless the user asked for the copy to run on the
315
+ same schedule \u2014 otherwise both apps run at the same moment
314
316
  - Modify arguments, description as needed
315
317
 
316
318
  4. JSON format for new app:
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/mcp/prompts/workflows.ts"],
4
- "sourcesContent": ["/**\n * Workflow Prompts\n *\n * Reusable prompt templates for common Farseer workflows.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\n\n// Define schemas outside of prompt registration to avoid deep type instantiation\nconst setupTenantSchema = {\n tenant: z.string().describe('Tenant name to setup'),\n};\n\nconst createAppSchema = {\n tenant: z.string().describe('Tenant name'),\n appName: z.string().describe('Name for the new app'),\n scriptName: z.string().optional().describe('Main script filename (default: index.ts)'),\n};\n\nconst understandModelSchema = {\n tenant: z.string().describe('Tenant name'),\n};\n\nconst writeImportScriptSchema = {\n tenant: z.string().describe('Tenant name'),\n variableName: z.string().describe('Target variable to import into'),\n};\n\nconst copyAppSchema = {\n tenant: z.string().describe('Tenant name'),\n sourceApp: z.string().describe('Name of app to copy'),\n newAppName: z.string().describe('Name for the new app'),\n};\n\nconst exportDataSchema = {\n tenant: z.string().describe('Tenant name'),\n variableName: z.string().describe('Variable to export'),\n};\n\nconst debugSyncSchema = {\n tenant: z.string().describe('Tenant name'),\n};\n\nexport function registerWorkflowPrompts(server: McpServer): void {\n // Cast to any to avoid very deep generic type instantiation from the MCP SDK\n const anyServer = server as any;\n // Setup new tenant\n anyServer.prompt(\n 'setup_new_tenant',\n 'Guide for getting started on the tenant this server is bound to: verify login, pull, install dependencies.',\n setupTenantSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `You are setting up a new Farseer tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Check authentication and the bound tenant with farseer_whoami\n2. If not logged in, inform the user to run \"farseer login\" in terminal (MCP cannot do browser login)\n3. If farseer_whoami does not show \"${tenant}\", tell the user to set --tenant ${tenant} in this MCP server's config and reconnect \u2014 MCP tools cannot change the tenant\n4. Pull files and apps with farseer_pull\n5. Tell user to run \"farseer install ${tenant}\" in terminal to install npm dependencies\n6. Use farseer_list_apps to show available apps\n7. Use farseer_export_model to understand the data structure\n\nAfter setup, the user can:\n- Run apps with farseer_run_app\n- Edit scripts in apps/${tenant}/files/Scripts/\n- Push changes with farseer_push\n- Check model with farseer_get_variable or farseer_get_table`,\n },\n },\n ],\n };\n },\n );\n\n // Create new app\n anyServer.prompt(\n 'create_new_app',\n 'Guide for creating a new Farseer app from scratch.',\n createAppSchema,\n async (params: { tenant: string; appName: string; scriptName?: string }) => {\n const { tenant, appName, scriptName } = params;\n const script = scriptName || 'index.ts';\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Creating a new Farseer app \"${appName}\" for tenant \"${tenant}\".\n\nIMPORTANT: A Farseer App = a TypeScript script + an app config that tells Farseer which script to run and with what arguments.\nThe script uses \\`farseer-client\\` to interact with the Farseer API.\nAuthentication is automatic - \\`new FarseerClient()\\` reads credentials from environment variables injected by the CLI.\nYou NEVER hardcode credentials in scripts.\n\nSteps to follow:\n\n1. Write the script file at farseer-apps/${tenant}/files/Scripts/${script}\n Use the template below as a starting point.\n\n2. Push the script to remote with farseer_push\n (Scripts must exist on remote before they can be assigned to an app)\n\n3. Create the app with farseer_create_app (name: \"${appName}\")\n\n4. Configure the app with farseer_configure_app:\n - sourceFolder: \"Scripts\"\n - entrypoint: \"${script}\"\n - arguments: Add any arguments the script expects (they arrive via process.argv)\n\n5. Test with farseer_run_app\n The CLI injects auth credentials as env vars and runs the script with npx tsx.\n\nScript template:\n\\`\\`\\`typescript\nimport * as farseer from 'farseer-client';\n\n// FarseerClient auto-configures from env vars injected by \"farseer run\"\n// NEVER hardcode credentials - just use the empty constructor\nconst client = new farseer.FarseerClient();\n\n// Arguments come via process.argv in the order defined by app config\nconst args = process.argv.slice(2);\n\nasync function main() {\n // Load dimension/variable metadata\n await client.initTagMap();\n\n // Your code here\n console.log('App running successfully');\n}\n\nmain().catch(farseer.handleUnknownError);\n\\`\\`\\``,\n },\n },\n ],\n };\n },\n );\n\n // Understand model\n anyServer.prompt(\n 'understand_model',\n 'Explore and understand the data model of a Farseer tenant.',\n understandModelSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Analyzing the data model for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_export_model to get the full model structure\n\n2. Review dimension tables:\n - Use farseer_list_tables for overview\n - Key dimensions usually include: Products, Regions, Time (Months, Years), Versions\n - Check foreign key relationships between tables\n\n3. Review variables:\n - Use farseer_list_variables for overview\n - Use farseer_get_variable for specific variable details\n - Note which dimensions each variable has\n\n4. For import scripts, you need to know:\n - Target variable name\n - All dimensions the variable has\n - Valid members for each dimension\n\nKey concepts:\n- Dimensions structure the data (Product, Region, Month, Year, Version)\n- Variables store values at dimension intersections\n- Formulas calculate values automatically\n- Roll-up types determine aggregation (SUM, AVERAGE, etc.)\n\nCommon dimension tables:\n- Months, Years (time)\n- Versions (Plan, Actual, Forecast)\n- Products, Categories, Brands\n- Regions, Entities, Cost Centers`,\n },\n },\n ],\n };\n },\n );\n\n // Write import script\n anyServer.prompt(\n 'write_import_script',\n 'Guide for writing a data import script.',\n writeImportScriptSchema,\n async (params: { tenant: string; variableName: string }) => {\n const { tenant, variableName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Writing an import script for variable \"${variableName}\" in tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_get_variable to understand the target variable:\n - What dimensions does it have?\n - What is the roll-up type?\n\n2. Use farseer_get_table for each dimension to see valid members\n\n3. Create the import script with this pattern:\n\n\\`\\`\\`typescript\nimport * as farseer from 'farseer-client';\n\nconst client = new farseer.FarseerClient();\n\nasync function main() {\n await client.initTagMap();\n\n // Create import job with column definitions\n const importJob = await client.createImportJob({\n title: 'Import ${variableName}',\n columns: [\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Product' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Years' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Months' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Versions' },\n { type: 'VARIABLE', variableName: '${variableName}' },\n ],\n labels: ['auto', 'import-${variableName.toLowerCase().replace(/\\s+/g, '-')}']\n });\n\n // Add rows - each row matches column order\n const rows = [\n ['ProductA', 'Y2025', 'M1', 'Plan', 1000],\n ['ProductB', 'Y2025', 'M1', 'Plan', 2000],\n ];\n\n await importJob.addRows(rows);\n await importJob.flushRows();\n await importJob.undoPrevious(); // Remove previous import\n await importJob.commit();\n\n console.log('Import completed!');\n}\n\nmain().catch(farseer.handleUnknownError);\n\\`\\`\\`\n\n4. Save script to apps/${tenant}/files/Scripts/\n5. Push with farseer_push\n6. Create app with farseer_create_app\n7. Configure with farseer_configure_app\n8. Test with farseer_run_app\n\nALTERNATIVE: For simple imports without a script, use the farseer_create_import_job tool directly.\nIt handles the full workflow (create metadata, add rows, undo previous, commit) in a single call.\nUse farseer_create_import_job when:\n- Data is already available (no need to fetch from external source)\n- The import is a one-time or simple operation\n- You want to quickly import without creating a full script\n\nUse a script when:\n- Data comes from external sources (APIs, databases, files)\n- Complex data transformation is needed\n- The import runs on a schedule as an App`,\n },\n },\n ],\n };\n },\n );\n\n // Copy existing app\n anyServer.prompt(\n 'copy_app',\n 'Guide for copying an existing app to create a new one.',\n copyAppSchema,\n async (params: { tenant: string; sourceApp: string; newAppName: string }) => {\n const { tenant, sourceApp, newAppName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Copying app \"${sourceApp}\" to create \"${newAppName}\" for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Pull latest with farseer_pull to get current app JSON\n\n2. Use farseer_get_app to see the source app configuration\n\n3. The app JSON files are in apps/${tenant}/apps/\n\n Copy the source JSON file and modify:\n - Change \"name\" to \"${newAppName}\"\n - **IMPORTANT: Remove \"_remote\" field** (this makes it a new app)\n - Modify arguments, description as needed\n\n4. JSON format for new app:\n\\`\\`\\`json\n{\n \"name\": \"${newAppName}\",\n \"description\": \"Copied from ${sourceApp}\",\n \"entrypoint\": \"script.ts\",\n \"scripts\": [\"script.ts\"],\n \"arguments\": [\n { \"name\": \"Year\", \"defaultValue\": \"2025\" }\n ]\n}\n\\`\\`\\`\n\nNote: Do NOT include \"_remote\" for new apps - CLI adds it after first push.\n\n5. Push with farseer_push to create the new app\n\n6. Test with farseer_run_app`,\n },\n },\n ],\n };\n },\n );\n\n // Export data\n anyServer.prompt(\n 'export_data',\n 'Guide for exporting variable data from Farseer.',\n exportDataSchema,\n async (params: { tenant: string; variableName: string }) => {\n const { tenant, variableName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Exporting data for variable \"${variableName}\" from tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_get_variable to understand the variable:\n - What dimensions does it span?\n - What is its data type?\n\n2. Choose export method:\n\n **Option A: Quick export (farseer_export_variable_data)**\n - Uses ExportApi.exportFormula() internally\n - Returns CSV/JSON data inline\n - Good for quick inspection or small datasets\n - Use 'limit' parameter for large datasets\n\n **Option B: Structured export (farseer_load_variable_data)**\n - Uses data.loadFarseerVariable() internally\n - Can specify which dimensions to include as columns\n - Returns structured CSV data\n - Good when you need specific dimension breakdowns\n\n **Option C: CLI export (farseer variable export)**\n - Saves CSV/JSON/XLSX to a local file\n - Best for saving data locally for analysis\n\n3. For analysis:\n - Parse the CSV data returned by the tools\n - Summarize, filter, or transform as needed`,\n },\n },\n ],\n };\n },\n );\n\n // Debug sync issues\n anyServer.prompt(\n 'debug_sync_issues',\n 'Troubleshoot synchronization problems between local and remote.',\n debugSyncSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Debugging sync issues for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Check authentication: farseer_whoami\n - Is JWT valid?\n - Which tenant is this server bound to (via --tenant)?\n\n2. Check sync status: farseer_status\n - Are there modified files?\n - Are there only-local or only-remote files?\n\n3. If files show as modified:\n - Use farseer_diff to see differences\n - Decide: pull (accept remote) or push (upload local)\n\n4. Common issues and solutions:\n\n **\"No credentials found\"**\n \u2192 User needs to run \"farseer login\" in terminal\n \u2192 Or configure API key: \"farseer config set ${tenant} --api-key KEY\"\n\n **\"Remote has changes\"**\n \u2192 Pull first with farseer_pull\n \u2192 Then push with farseer_push\n\n **\"Token expired\"**\n \u2192 User needs to run \"farseer login\" again\n\n **Apps not syncing**\n \u2192 Need JWT login (browser), not API key\n \u2192 API key only syncs files, not apps\n\n5. Force resolution:\n - To accept all remote changes: farseer_pull with force=true (overwrites local)\n - To accept all local changes: farseer_push with force=true (overwrites remote)\n - For selective resolution: farseer_pull without force will skip conflicts (resolve via CLI)\n\n6. Check specific file diff:\n - Use farseer_diff with file parameter to see exact changes`,\n },\n },\n ],\n };\n },\n );\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAGlB,MAAM,oBAAoB;AAAA,EACtB,QAAQ,aAAE,OAAO,EAAE,SAAS,sBAAsB;AACtD;AAEA,MAAM,kBAAkB;AAAA,EACpB,QAAQ,aAAE,OAAO,EAAE,SAAS,aAAa;AAAA,EACzC,SAAS,aAAE,OAAO,EAAE,SAAS,sBAAsB;AAAA,EACnD,YAAY,aAAE,OAAO,EAAE,SAAS,EAAE,SAAS,0CAA0C;AACzF;AAEA,MAAM,wBAAwB;AAAA,EAC1B,QAAQ,aAAE,OAAO,EAAE,SAAS,aAAa;AAC7C;AAEA,MAAM,0BAA0B;AAAA,EAC5B,QAAQ,aAAE,OAAO,EAAE,SAAS,aAAa;AAAA,EACzC,cAAc,aAAE,OAAO,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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YA6B9E;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AAGA,YAAU;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA,OAAO,WAA+B;AAClC,YAAM,EAAE,OAAO,IAAI;AACnB,aAAO;AAAA,QACH,UAAU;AAAA,UACN;AAAA,YACI,MAAM;AAAA,YACN,SAAS;AAAA,cACL,MAAM;AAAA,cACN,MAAM,qCAAqC,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sDAoB5B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAoB/B;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;",
4
+ "sourcesContent": ["/**\n * Workflow Prompts\n *\n * Reusable prompt templates for common Farseer workflows.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z } from 'zod';\n\n// Define schemas outside of prompt registration to avoid deep type instantiation\nconst setupTenantSchema = {\n tenant: z.string().describe('Tenant name to setup'),\n};\n\nconst createAppSchema = {\n tenant: z.string().describe('Tenant name'),\n appName: z.string().describe('Name for the new app'),\n scriptName: z.string().optional().describe('Main script filename (default: index.ts)'),\n};\n\nconst understandModelSchema = {\n tenant: z.string().describe('Tenant name'),\n};\n\nconst writeImportScriptSchema = {\n tenant: z.string().describe('Tenant name'),\n variableName: z.string().describe('Target variable to import into'),\n};\n\nconst copyAppSchema = {\n tenant: z.string().describe('Tenant name'),\n sourceApp: z.string().describe('Name of app to copy'),\n newAppName: z.string().describe('Name for the new app'),\n};\n\nconst exportDataSchema = {\n tenant: z.string().describe('Tenant name'),\n variableName: z.string().describe('Variable to export'),\n};\n\nconst debugSyncSchema = {\n tenant: z.string().describe('Tenant name'),\n};\n\nexport function registerWorkflowPrompts(server: McpServer): void {\n // Cast to any to avoid very deep generic type instantiation from the MCP SDK\n const anyServer = server as any;\n // Setup new tenant\n anyServer.prompt(\n 'setup_new_tenant',\n 'Guide for getting started on the tenant this server is bound to: verify login, pull, install dependencies.',\n setupTenantSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `You are setting up a new Farseer tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Check authentication and the bound tenant with farseer_whoami\n2. If not logged in, inform the user to run \"farseer login\" in terminal (MCP cannot do browser login)\n3. If farseer_whoami does not show \"${tenant}\", tell the user to set --tenant ${tenant} in this MCP server's config and reconnect \u2014 MCP tools cannot change the tenant\n4. Pull files and apps with farseer_pull\n5. Tell user to run \"farseer install ${tenant}\" in terminal to install npm dependencies\n6. Use farseer_list_apps to show available apps\n7. Use farseer_export_model to understand the data structure\n\nAfter setup, the user can:\n- Run apps with farseer_run_app\n- Edit scripts in apps/${tenant}/files/Scripts/\n- Push changes with farseer_push\n- Check model with farseer_get_variable or farseer_get_table`,\n },\n },\n ],\n };\n },\n );\n\n // Create new app\n anyServer.prompt(\n 'create_new_app',\n 'Guide for creating a new Farseer app from scratch.',\n createAppSchema,\n async (params: { tenant: string; appName: string; scriptName?: string }) => {\n const { tenant, appName, scriptName } = params;\n const script = scriptName || 'index.ts';\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Creating a new Farseer app \"${appName}\" for tenant \"${tenant}\".\n\nIMPORTANT: A Farseer App = a TypeScript script + an app config that tells Farseer which script to run and with what arguments.\nThe script uses \\`farseer-client\\` to interact with the Farseer API.\nAuthentication is automatic - \\`new FarseerClient()\\` reads credentials from environment variables injected by the CLI.\nYou NEVER hardcode credentials in scripts.\n\nSteps to follow:\n\n1. Write the script file at farseer-apps/${tenant}/files/Scripts/${script}\n Use the template below as a starting point.\n\n2. Push the script to remote with farseer_push\n (Scripts must exist on remote before they can be assigned to an app)\n\n3. Create the app with farseer_create_app (name: \"${appName}\")\n\n4. Configure the app with farseer_configure_app:\n - sourceFolder: \"Scripts\"\n - entrypoint: \"${script}\"\n - arguments: Add any arguments the script expects (they arrive via process.argv)\n\n5. Test with farseer_run_app\n The CLI injects auth credentials as env vars and runs the script with npx tsx.\n\nScript template:\n\\`\\`\\`typescript\nimport * as farseer from 'farseer-client';\n\n// FarseerClient auto-configures from env vars injected by \"farseer run\"\n// NEVER hardcode credentials - just use the empty constructor\nconst client = new farseer.FarseerClient();\n\n// Arguments come via process.argv in the order defined by app config\nconst args = process.argv.slice(2);\n\nasync function main() {\n // Load dimension/variable metadata\n await client.initTagMap();\n\n // Your code here\n console.log('App running successfully');\n}\n\nmain().catch(farseer.handleUnknownError);\n\\`\\`\\``,\n },\n },\n ],\n };\n },\n );\n\n // Understand model\n anyServer.prompt(\n 'understand_model',\n 'Explore and understand the data model of a Farseer tenant.',\n understandModelSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Analyzing the data model for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_export_model to get the full model structure\n\n2. Review dimension tables:\n - Use farseer_list_tables for overview\n - Key dimensions usually include: Products, Regions, Time (Months, Years), Versions\n - Check foreign key relationships between tables\n\n3. Review variables:\n - Use farseer_list_variables for overview\n - Use farseer_get_variable for specific variable details\n - Note which dimensions each variable has\n\n4. For import scripts, you need to know:\n - Target variable name\n - All dimensions the variable has\n - Valid members for each dimension\n\nKey concepts:\n- Dimensions structure the data (Product, Region, Month, Year, Version)\n- Variables store values at dimension intersections\n- Formulas calculate values automatically\n- Roll-up types determine aggregation (SUM, AVERAGE, etc.)\n\nCommon dimension tables:\n- Months, Years (time)\n- Versions (Plan, Actual, Forecast)\n- Products, Categories, Brands\n- Regions, Entities, Cost Centers`,\n },\n },\n ],\n };\n },\n );\n\n // Write import script\n anyServer.prompt(\n 'write_import_script',\n 'Guide for writing a data import script.',\n writeImportScriptSchema,\n async (params: { tenant: string; variableName: string }) => {\n const { tenant, variableName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Writing an import script for variable \"${variableName}\" in tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_get_variable to understand the target variable:\n - What dimensions does it have?\n - What is the roll-up type?\n\n2. Use farseer_get_table for each dimension to see valid members\n\n3. Create the import script with this pattern:\n\n\\`\\`\\`typescript\nimport * as farseer from 'farseer-client';\n\nconst client = new farseer.FarseerClient();\n\nasync function main() {\n await client.initTagMap();\n\n // Create import job with column definitions\n const importJob = await client.createImportJob({\n title: 'Import ${variableName}',\n columns: [\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Product' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Years' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Months' },\n { type: 'DIMENSION_TABLE', dimensionTableName: 'Versions' },\n { type: 'VARIABLE', variableName: '${variableName}' },\n ],\n labels: ['auto', 'import-${variableName.toLowerCase().replace(/\\s+/g, '-')}']\n });\n\n // Add rows - each row matches column order\n const rows = [\n ['ProductA', 'Y2025', 'M1', 'Plan', 1000],\n ['ProductB', 'Y2025', 'M1', 'Plan', 2000],\n ];\n\n await importJob.addRows(rows);\n await importJob.flushRows();\n await importJob.undoPrevious(); // Remove previous import\n await importJob.commit();\n\n console.log('Import completed!');\n}\n\nmain().catch(farseer.handleUnknownError);\n\\`\\`\\`\n\n4. Save script to apps/${tenant}/files/Scripts/\n5. Push with farseer_push\n6. Create app with farseer_create_app\n7. Configure with farseer_configure_app\n8. Test with farseer_run_app\n\nALTERNATIVE: For simple imports without a script, use the farseer_create_import_job tool directly.\nIt handles the full workflow (create metadata, add rows, undo previous, commit) in a single call.\nUse farseer_create_import_job when:\n- Data is already available (no need to fetch from external source)\n- The import is a one-time or simple operation\n- You want to quickly import without creating a full script\n\nUse a script when:\n- Data comes from external sources (APIs, databases, files)\n- Complex data transformation is needed\n- The import runs on a schedule as an App`,\n },\n },\n ],\n };\n },\n );\n\n // Copy existing app\n anyServer.prompt(\n 'copy_app',\n 'Guide for copying an existing app to create a new one.',\n copyAppSchema,\n async (params: { tenant: string; sourceApp: string; newAppName: string }) => {\n const { tenant, sourceApp, newAppName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Copying app \"${sourceApp}\" to create \"${newAppName}\" for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Pull latest with farseer_pull to get current app JSON\n\n2. Use farseer_get_app to see the source app configuration\n\n3. The app JSON files are in apps/${tenant}/apps/\n\n Copy the source JSON file and modify:\n - Change \"name\" to \"${newAppName}\"\n - **IMPORTANT: Remove \"_remote\" field** (this makes it a new app)\n - Set \"schedule\" to null, unless the user asked for the copy to run on the\n same schedule \u2014 otherwise both apps run at the same moment\n - Modify arguments, description as needed\n\n4. JSON format for new app:\n\\`\\`\\`json\n{\n \"name\": \"${newAppName}\",\n \"description\": \"Copied from ${sourceApp}\",\n \"entrypoint\": \"script.ts\",\n \"scripts\": [\"script.ts\"],\n \"arguments\": [\n { \"name\": \"Year\", \"defaultValue\": \"2025\" }\n ]\n}\n\\`\\`\\`\n\nNote: Do NOT include \"_remote\" for new apps - CLI adds it after first push.\n\n5. Push with farseer_push to create the new app\n\n6. Test with farseer_run_app`,\n },\n },\n ],\n };\n },\n );\n\n // Export data\n anyServer.prompt(\n 'export_data',\n 'Guide for exporting variable data from Farseer.',\n exportDataSchema,\n async (params: { tenant: string; variableName: string }) => {\n const { tenant, variableName } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Exporting data for variable \"${variableName}\" from tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Use farseer_get_variable to understand the variable:\n - What dimensions does it span?\n - What is its data type?\n\n2. Choose export method:\n\n **Option A: Quick export (farseer_export_variable_data)**\n - Uses ExportApi.exportFormula() internally\n - Returns CSV/JSON data inline\n - Good for quick inspection or small datasets\n - Use 'limit' parameter for large datasets\n\n **Option B: Structured export (farseer_load_variable_data)**\n - Uses data.loadFarseerVariable() internally\n - Can specify which dimensions to include as columns\n - Returns structured CSV data\n - Good when you need specific dimension breakdowns\n\n **Option C: CLI export (farseer variable export)**\n - Saves CSV/JSON/XLSX to a local file\n - Best for saving data locally for analysis\n\n3. For analysis:\n - Parse the CSV data returned by the tools\n - Summarize, filter, or transform as needed`,\n },\n },\n ],\n };\n },\n );\n\n // Debug sync issues\n anyServer.prompt(\n 'debug_sync_issues',\n 'Troubleshoot synchronization problems between local and remote.',\n debugSyncSchema,\n async (params: { tenant: string }) => {\n const { tenant } = params;\n return {\n messages: [\n {\n role: 'user',\n content: {\n type: 'text',\n text: `Debugging sync issues for tenant \"${tenant}\".\n\nSteps to follow:\n\n1. Check authentication: farseer_whoami\n - Is JWT valid?\n - Which tenant is this server bound to (via --tenant)?\n\n2. Check sync status: farseer_status\n - Are there modified files?\n - Are there only-local or only-remote files?\n\n3. If files show as modified:\n - Use farseer_diff to see differences\n - Decide: pull (accept remote) or push (upload local)\n\n4. Common issues and solutions:\n\n **\"No credentials found\"**\n \u2192 User needs to run \"farseer login\" in terminal\n \u2192 Or configure API key: \"farseer config set ${tenant} --api-key KEY\"\n\n **\"Remote has changes\"**\n \u2192 Pull first with farseer_pull\n \u2192 Then push with farseer_push\n\n **\"Token expired\"**\n \u2192 User needs to run \"farseer login\" again\n\n **Apps not syncing**\n \u2192 Need JWT login (browser), not API key\n \u2192 API key only syncs files, not apps\n\n5. Force resolution:\n - To accept all remote changes: farseer_pull with force=true (overwrites local)\n - To accept all local changes: farseer_push with force=true (overwrites remote)\n - For selective resolution: farseer_pull without force will skip conflicts (resolve via CLI)\n\n6. Check specific file diff:\n - Use farseer_diff with file parameter to see exact changes`,\n },\n },\n ],\n };\n },\n );\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAOA,iBAAkB;AAGlB,MAAM,oBAAoB;AAAA,EACtB,QAAQ,aAAE,OAAO,EAAE,SAAS,sBAAsB;AACtD;AAEA,MAAM,kBAAkB;AAAA,EACpB,QAAQ,aAAE,OAAO,EAAE,SAAS,aAAa;AAAA,EACzC,SAAS,aAAE,OAAO,EAAE,SAAS,sBAAsB;AAAA,EACnD,YAAY,aAAE,OAAO,EAAE,SAAS,EAAE,SAAS,0CAA0C;AACzF;AAEA,MAAM,wBAAwB;AAAA,EAC1B,QAAQ,aAAE,OAAO,EAAE,SAAS,aAAa;AAC7C;AAEA,MAAM,0BAA0B;AAAA,EAC5B,QAAQ,aAAE,OAAO,EAAE,SAAS,aAAa;AAAA,EACzC,cAAc,aAAE,OAAO,EAAE,SAAS,gCAAgC;AACtE;AAEA,MAAM,gBAAgB;AAAA,EAClB,QAAQ,aAAE,OAAO,EAAE,SAAS,aAAa;AAAA,EACzC,WAAW,aAAE,OAAO,EAAE,SAAS,qBAAqB;AAAA,EACpD,YAAY,aAAE,OAAO,EAAE,SAAS,sBAAsB;AAC1D;AAEA,MAAM,mBAAmB;AAAA,EACrB,QAAQ,aAAE,OAAO,EAAE,SAAS,aAAa;AAAA,EACzC,cAAc,aAAE,OAAO,EAAE,SAAS,oBAAoB;AAC1D;AAEA,MAAM,kBAAkB;AAAA,EACpB,QAAQ,aAAE,OAAO,EAAE,SAAS,aAAa;AAC7C;AAEO,SAAS,wBAAwB,QAAyB;AAE7D,QAAM,YAAY;AAElB,YAAU;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA,OAAO,WAA+B;AAClC,YAAM,EAAE,OAAO,IAAI;AACnB,aAAO;AAAA,QACH,UAAU;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;AAAA,sDAoB5B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAoB/B;AAAA,UACJ;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;",
6
6
  "names": []
7
7
  }
@@ -19,6 +19,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
19
19
  var appTools_exports = {};
20
20
  __export(appTools_exports, {
21
21
  argumentSchema: () => argumentSchema,
22
+ predefinedActionSchema: () => predefinedActionSchema,
22
23
  registerAppTools: () => registerAppTools
23
24
  });
24
25
  module.exports = __toCommonJS(appTools_exports);
@@ -55,6 +56,10 @@ const argumentSchema = import_zod.z.object({
55
56
  message: "defaultValue must be one of the options",
56
57
  path: ["defaultValue"]
57
58
  });
59
+ const predefinedActionSchema = import_zod.z.object({
60
+ name: import_zod.z.string(),
61
+ runArguments: import_zod.z.record(import_zod.z.string()).describe("Argument name to the value this action runs with.")
62
+ });
58
63
  const configureAppSchema = {
59
64
  appName: import_zod.z.string().optional().describe("Name of the app to configure. Omit if using appId."),
60
65
  appId: import_zod.z.string().optional().describe("Numeric app id \u2014 use instead of appName when names collide."),
@@ -62,7 +67,16 @@ const configureAppSchema = {
62
67
  sourceFolder: import_zod.z.string().optional().describe(`Source folder the app's scripts come from (path under Files/, e.g. "Scripts/MyApp")`),
63
68
  description: import_zod.z.string().optional().describe("App description"),
64
69
  arguments: import_zod.z.array(argumentSchema).optional().describe("App arguments with default values"),
65
- newName: import_zod.z.string().optional().describe("Rename the app")
70
+ newName: import_zod.z.string().optional().describe("Rename the app"),
71
+ schedule: import_zod.z.string().optional().describe(`Cron expression to run the app on, e.g. "0 6 * * *". Pass "${import_apps.CLEAR_SETTING}" to clear it.`),
72
+ runner: import_zod.z.string().optional().describe(`Name of the jobrunner that runs the app. Pass "${import_apps.CLEAR_SETTING}" to let any runner take it.`),
73
+ runnerImage: import_zod.z.string().optional().describe(
74
+ `Container image the app runs in, as "<repository>:<tag>" (e.g. "runner-typescript:latest") or a full registry reference. Pass "${import_apps.CLEAR_SETTING}" for the tenant default.`
75
+ ),
76
+ compute: import_zod.z.enum(import_apps.APP_COMPUTE_CHOICES).optional().describe(
77
+ `Where a run executes: "local" is a container on the jobrunner's own machine, "batch" a machine created for that run. The size suffix picks how much machine; bare "batch" takes the deployment's default size.`
78
+ ),
79
+ predefinedActions: import_zod.z.array(predefinedActionSchema).optional().describe("Named argument presets offered as buttons in the UI. Replaces the existing list wholesale.")
66
80
  };
67
81
  const deleteAppSchema = {
68
82
  appName: import_zod.z.string().optional().describe("Name of the app to delete. Omit if using appId."),
@@ -138,7 +152,9 @@ Returns:
138
152
  - App name and description
139
153
  - Entry point script (main script that runs)
140
154
  - List of all included scripts
141
- - Expected arguments with their default values`,
155
+ - Expected arguments with their default values
156
+ - Schedule, runner, runner image and compute selection
157
+ - Predefined actions (named argument presets)`,
142
158
  getAppSchema,
143
159
  async (params) => {
144
160
  const gate = await (0, import_session.requireSession)();
@@ -176,7 +192,12 @@ Returns:
176
192
  ...a.secret !== void 0 ? { secret: a.secret } : {}
177
193
  })),
178
194
  status: app.status,
179
- lastHeartbeat: app.lastHeartbeat
195
+ lastHeartbeat: app.lastHeartbeat,
196
+ schedule: app.schedule ?? null,
197
+ runner: app.runnerName ?? null,
198
+ runnerImage: app.runnerImage ?? null,
199
+ compute: (0, import_apps.formatCompute)(app.compute),
200
+ predefinedActions: (0, import_apps.redactActionValues)(app.predefinedActions ?? [], app.expectedArguments)
180
201
  }
181
202
  });
182
203
  } catch (error) {
@@ -236,6 +257,15 @@ You can set:
236
257
  value at run time), optional options (closed allowed-value set, string
237
258
  dataType only), optional defaultValue, and optional secret.
238
259
  - newName: Rename the app
260
+ - schedule: Cron expression the app runs on (e.g. "0 6 * * *")
261
+ - runner: Which jobrunner runs the app
262
+ - runnerImage: Container image, as "<repository>:<tag>" or a full registry reference
263
+ - compute: Where a run executes \u2014 'local', 'batch', or 'batch:<size>' with size s, m, l or xl
264
+ - predefinedActions: Named argument presets offered as buttons in the UI. The
265
+ list you pass replaces the app's whole list. farseer_get_app shows a secret
266
+ argument's value as "<secret>"; send "<secret>" back to keep the stored value
267
+ of the action with exactly that name. Where two actions share a name, give
268
+ the real value.
239
269
 
240
270
  Important:
241
271
  - The app's scripts are derived from its source folder; the entrypoint must be
@@ -243,6 +273,7 @@ Important:
243
273
  - Changing sourceFolder to a folder that doesn't contain the current entrypoint
244
274
  requires passing entrypoint in the same call.
245
275
  - Settings you don't pass are preserved (this only changes what you specify).
276
+ - Pass "${import_apps.CLEAR_SETTING}" to schedule, runner or runnerImage to clear it.
246
277
  - Arguments are passed to the script as a JSON-encoded FARSEER_ARGS env var
247
278
  - Boolean dataType requires defaultValue \u2208 { "true", "false" }; defaultValue
248
279
  must be one of options when options is set`,
@@ -296,12 +327,30 @@ Important:
296
327
  if (sourceFolderError) {
297
328
  return (0, import_helpers.errorResponse)(sourceFolderError, "VALIDATION_ERROR");
298
329
  }
330
+ if (params.predefinedActions) {
331
+ const restored = (0, import_apps.restoreRedactedValues)(params.predefinedActions, app.predefinedActions ?? []);
332
+ if ("error" in restored) {
333
+ return (0, import_helpers.errorResponse)(restored.error, "VALIDATION_ERROR");
334
+ }
335
+ changes.predefinedActions = restored.actions;
336
+ }
337
+ const runSettings = await (0, import_apps.applyRunSettings)(client, app, changes, {
338
+ schedule: params.schedule,
339
+ runner: params.runner,
340
+ runnerImage: params.runnerImage,
341
+ compute: params.compute
342
+ });
343
+ if ("error" in runSettings) {
344
+ return (0, import_helpers.errorResponse)(runSettings.error, "VALIDATION_ERROR");
345
+ }
299
346
  const reference = app.id.toString();
300
- await client.updateApp(reference, changes, app);
347
+ const updated = await client.updateApp(reference, changes, app);
301
348
  return (0, import_helpers.successResponse)({
302
349
  tenant,
303
350
  appName: params.newName || app.name,
304
351
  updated: Object.keys(changes),
352
+ compute: (0, import_apps.formatCompute)(updated.compute),
353
+ warnings: runSettings.warnings,
305
354
  message: `App "${app.name}" configured successfully`
306
355
  });
307
356
  } catch (error) {
@@ -355,6 +404,7 @@ This does NOT delete the script files, only the app configuration.`,
355
404
  // Annotate the CommonJS export names for ESM import in node:
356
405
  0 && (module.exports = {
357
406
  argumentSchema,
407
+ predefinedActionSchema,
358
408
  registerAppTools
359
409
  });
360
410
  //# sourceMappingURL=appTools.js.map