farseer-cli 1.12.0 → 1.14.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 (101) hide show
  1. package/README.md +51 -18
  2. package/dist/commands/login.js +60 -26
  3. package/dist/commands/login.js.map +2 -2
  4. package/dist/commands/logout.js +37 -12
  5. package/dist/commands/logout.js.map +3 -3
  6. package/dist/commands/pipeline.js +158 -0
  7. package/dist/commands/pipeline.js.map +7 -0
  8. package/dist/commands/run.js +10 -27
  9. package/dist/commands/run.js.map +2 -2
  10. package/dist/commands/variables.js +17 -8
  11. package/dist/commands/variables.js.map +2 -2
  12. package/dist/commands/whoami.js +10 -14
  13. package/dist/commands/whoami.js.map +2 -2
  14. package/dist/index.js +40 -46
  15. package/dist/index.js.map +2 -2
  16. package/dist/mcp/prompts/workflows.js +13 -68
  17. package/dist/mcp/prompts/workflows.js.map +2 -2
  18. package/dist/mcp/resources/documentation.js +14 -0
  19. package/dist/mcp/resources/documentation.js.map +2 -2
  20. package/dist/mcp/server.js +14 -2
  21. package/dist/mcp/server.js.map +2 -2
  22. package/dist/mcp/skills.js +59 -0
  23. package/dist/mcp/skills.js.map +7 -0
  24. package/dist/mcp/tools/appTools.js +4 -0
  25. package/dist/mcp/tools/appTools.js.map +2 -2
  26. package/dist/mcp/tools/authTools.js +5 -2
  27. package/dist/mcp/tools/authTools.js.map +2 -2
  28. package/dist/mcp/tools/dataTools.js +2 -0
  29. package/dist/mcp/tools/dataTools.js.map +2 -2
  30. package/dist/mcp/tools/modelTools.js +6 -41
  31. package/dist/mcp/tools/modelTools.js.map +2 -2
  32. package/dist/mcp/tools/pipelineContract.js +317 -0
  33. package/dist/mcp/tools/pipelineContract.js.map +7 -0
  34. package/dist/mcp/tools/pipelineTools.js +111 -0
  35. package/dist/mcp/tools/pipelineTools.js.map +7 -0
  36. package/dist/mcp/tools/runTools.js +7 -18
  37. package/dist/mcp/tools/runTools.js.map +2 -2
  38. package/dist/mcp/tools/syncTools.js +4 -0
  39. package/dist/mcp/tools/syncTools.js.map +2 -2
  40. package/dist/mcp/utils/helpers.js +16 -6
  41. package/dist/mcp/utils/helpers.js.map +3 -3
  42. package/dist/mcp/utils/session.js +14 -9
  43. package/dist/mcp/utils/session.js.map +2 -2
  44. package/dist/pipeline/compatibility.js +53 -0
  45. package/dist/pipeline/compatibility.js.map +7 -0
  46. package/dist/pipeline/connect.js +139 -0
  47. package/dist/pipeline/connect.js.map +7 -0
  48. package/dist/pipeline/create.js +158 -0
  49. package/dist/pipeline/create.js.map +7 -0
  50. package/dist/pipeline/errors.js +45 -0
  51. package/dist/pipeline/errors.js.map +7 -0
  52. package/dist/pipeline/generated-reference.json +115 -0
  53. package/dist/pipeline/guide.js +33 -0
  54. package/dist/pipeline/guide.js.map +7 -0
  55. package/dist/pipeline/init.js +204 -0
  56. package/dist/pipeline/init.js.map +7 -0
  57. package/dist/pipeline/operations.js +103 -0
  58. package/dist/pipeline/operations.js.map +7 -0
  59. package/dist/pipeline/query.js +103 -0
  60. package/dist/pipeline/query.js.map +7 -0
  61. package/dist/pipeline/queryWorker.js +119 -0
  62. package/dist/pipeline/queryWorker.js.map +7 -0
  63. package/dist/pipeline/readiness.js +55 -0
  64. package/dist/pipeline/readiness.js.map +7 -0
  65. package/dist/pipeline/reference.js +72 -0
  66. package/dist/pipeline/reference.js.map +7 -0
  67. package/dist/pipeline/requests.js +122 -0
  68. package/dist/pipeline/requests.js.map +7 -0
  69. package/dist/pipeline/runArguments.js +68 -0
  70. package/dist/pipeline/runArguments.js.map +7 -0
  71. package/dist/pipeline/runtime.js +105 -0
  72. package/dist/pipeline/runtime.js.map +7 -0
  73. package/dist/pipeline/service.js +967 -0
  74. package/dist/pipeline/service.js.map +7 -0
  75. package/dist/services/agentApprovalFetch.js +86 -0
  76. package/dist/services/agentApprovalFetch.js.map +7 -0
  77. package/dist/services/authErrors.js +2 -2
  78. package/dist/services/authErrors.js.map +2 -2
  79. package/dist/services/configService.js +74 -9
  80. package/dist/services/configService.js.map +2 -2
  81. package/dist/services/credentials.js +12 -7
  82. package/dist/services/credentials.js.map +2 -2
  83. package/dist/services/farseerService.js +94 -39
  84. package/dist/services/farseerService.js.map +2 -2
  85. package/dist/services/preflight.js +7 -2
  86. package/dist/services/preflight.js.map +2 -2
  87. package/dist/services/realms.js +67 -0
  88. package/dist/services/realms.js.map +7 -0
  89. package/dist/services/syncService.js +6 -0
  90. package/dist/services/syncService.js.map +2 -2
  91. package/dist/skills/pipeline.js +71 -0
  92. package/dist/skills/pipeline.js.map +7 -0
  93. package/dist/utils/helpers.js +2 -1
  94. package/dist/utils/helpers.js.map +2 -2
  95. package/dist/utils/variableValues.js +78 -0
  96. package/dist/utils/variableValues.js.map +7 -0
  97. package/docs/pipeline-client-guide.md +67 -0
  98. package/docs/pipeline-reference.md +2064 -0
  99. package/package.json +5 -1
  100. package/skills/pipeline-authoring/SKILL.md +95 -0
  101. package/skills/pipeline-authoring/practices.md +325 -0
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var pipeline_exports = {};
20
+ __export(pipeline_exports, {
21
+ PIPELINE_SKILL_PATH: () => PIPELINE_SKILL_PATH,
22
+ PIPELINE_SKILL_URI: () => PIPELINE_SKILL_URI,
23
+ pipelineSkill: () => pipelineSkill
24
+ });
25
+ module.exports = __toCommonJS(pipeline_exports);
26
+ var import_crypto = require("crypto");
27
+ var import_fs = require("fs");
28
+ var import_path = require("path");
29
+ var import_zod = require("zod");
30
+ const { load } = require("js-yaml");
31
+ const PIPELINE_SKILL_PATH = (0, import_path.resolve)(__dirname, "../../skills/pipeline-authoring/SKILL.md");
32
+ const PIPELINE_SKILL_URI = "skill://farseer/pipeline-authoring/SKILL.md";
33
+ const frontmatterSchema = import_zod.z.object({ name: import_zod.z.literal("pipeline-authoring"), description: import_zod.z.string().min(1) }).passthrough();
34
+ function loadPipelineSkill() {
35
+ const folder = (0, import_path.dirname)(PIPELINE_SKILL_PATH);
36
+ const files = (0, import_fs.readdirSync)(folder).sort();
37
+ const contents = new Map(files.map((file) => [file, (0, import_fs.readFileSync)((0, import_path.join)(folder, file))]));
38
+ const bytes = contents.get("SKILL.md");
39
+ const text = bytes.toString("utf8");
40
+ const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/.exec(text);
41
+ if (!match) throw new Error("Bundled pipeline skill has no YAML frontmatter");
42
+ const frontmatter = frontmatterSchema.parse(load(match[1]));
43
+ return {
44
+ text,
45
+ body: match[2].trim() + "\n",
46
+ /** The judgment layer the method points to: how a Farseer data engineer designs a pipeline. */
47
+ practices: contents.get("practices.md").toString("utf8"),
48
+ /** Resource URI to file text, for serving each resource. */
49
+ files: new Map(files.map((file) => [skillFileUri(file), contents.get(file).toString("utf8")])),
50
+ entry: {
51
+ uri: PIPELINE_SKILL_URI,
52
+ frontmatter,
53
+ resources: files.map((file) => ({
54
+ uri: skillFileUri(file),
55
+ digest: `sha256:${(0, import_crypto.createHash)("sha256").update(contents.get(file)).digest("hex")}`,
56
+ size: contents.get(file).length
57
+ }))
58
+ }
59
+ };
60
+ }
61
+ function skillFileUri(file) {
62
+ return PIPELINE_SKILL_URI.replace("SKILL.md", file);
63
+ }
64
+ const pipelineSkill = loadPipelineSkill();
65
+ // Annotate the CommonJS export names for ESM import in node:
66
+ 0 && (module.exports = {
67
+ PIPELINE_SKILL_PATH,
68
+ PIPELINE_SKILL_URI,
69
+ pipelineSkill
70
+ });
71
+ //# sourceMappingURL=pipeline.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/skills/pipeline.ts"],
4
+ "sourcesContent": ["import { createHash } from 'crypto';\nimport { readdirSync, readFileSync } from 'fs';\nimport { dirname, join, resolve } from 'path';\nimport { z } from 'zod';\n\nconst { load }: { load: (source: string) => unknown } = require('js-yaml');\n\nexport const PIPELINE_SKILL_PATH = resolve(__dirname, '../../skills/pipeline-authoring/SKILL.md');\nexport const PIPELINE_SKILL_URI = 'skill://farseer/pipeline-authoring/SKILL.md';\n\nconst frontmatterSchema = z\n .object({ name: z.literal('pipeline-authoring'), description: z.string().min(1) })\n .passthrough();\n\n/**\n * One immutable package snapshot backs native discovery and the guide fallback. Every file in the\n * skill folder is one of its resources, so a native install and the MCP server serve the same set.\n */\nfunction loadPipelineSkill() {\n const folder = dirname(PIPELINE_SKILL_PATH);\n const files = readdirSync(folder).sort();\n const contents = new Map(files.map((file) => [file, readFileSync(join(folder, file))]));\n const bytes = contents.get('SKILL.md')!;\n const text = bytes.toString('utf8');\n const match = /^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n([\\s\\S]*)$/.exec(text);\n if (!match) throw new Error('Bundled pipeline skill has no YAML frontmatter');\n const frontmatter = frontmatterSchema.parse(load(match[1]));\n return {\n text,\n body: match[2].trim() + '\\n',\n /** The judgment layer the method points to: how a Farseer data engineer designs a pipeline. */\n practices: contents.get('practices.md')!.toString('utf8'),\n /** Resource URI to file text, for serving each resource. */\n files: new Map(files.map((file) => [skillFileUri(file), contents.get(file)!.toString('utf8')])),\n entry: {\n uri: PIPELINE_SKILL_URI,\n frontmatter,\n resources: files.map((file) => ({\n uri: skillFileUri(file),\n digest: `sha256:${createHash('sha256').update(contents.get(file)!).digest('hex')}`,\n size: contents.get(file)!.length,\n })),\n },\n };\n}\n\nfunction skillFileUri(file: string): string {\n return PIPELINE_SKILL_URI.replace('SKILL.md', file);\n}\n\nexport const pipelineSkill = loadPipelineSkill();\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAA2B;AAC3B,gBAA0C;AAC1C,kBAAuC;AACvC,iBAAkB;AAElB,MAAM,EAAE,KAAK,IAA2C,QAAQ,SAAS;AAElE,MAAM,0BAAsB,qBAAQ,WAAW,0CAA0C;AACzF,MAAM,qBAAqB;AAElC,MAAM,oBAAoB,aACrB,OAAO,EAAE,MAAM,aAAE,QAAQ,oBAAoB,GAAG,aAAa,aAAE,OAAO,EAAE,IAAI,CAAC,EAAE,CAAC,EAChF,YAAY;AAMjB,SAAS,oBAAoB;AACzB,QAAM,aAAS,qBAAQ,mBAAmB;AAC1C,QAAM,YAAQ,uBAAY,MAAM,EAAE,KAAK;AACvC,QAAM,WAAW,IAAI,IAAI,MAAM,IAAI,CAAC,SAAS,CAAC,UAAM,4BAAa,kBAAK,QAAQ,IAAI,CAAC,CAAC,CAAC,CAAC;AACtF,QAAM,QAAQ,SAAS,IAAI,UAAU;AACrC,QAAM,OAAO,MAAM,SAAS,MAAM;AAClC,QAAM,QAAQ,6CAA6C,KAAK,IAAI;AACpE,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,gDAAgD;AAC5E,QAAM,cAAc,kBAAkB,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC;AAC1D,SAAO;AAAA,IACH;AAAA,IACA,MAAM,MAAM,CAAC,EAAE,KAAK,IAAI;AAAA;AAAA,IAExB,WAAW,SAAS,IAAI,cAAc,EAAG,SAAS,MAAM;AAAA;AAAA,IAExD,OAAO,IAAI,IAAI,MAAM,IAAI,CAAC,SAAS,CAAC,aAAa,IAAI,GAAG,SAAS,IAAI,IAAI,EAAG,SAAS,MAAM,CAAC,CAAC,CAAC;AAAA,IAC9F,OAAO;AAAA,MACH,KAAK;AAAA,MACL;AAAA,MACA,WAAW,MAAM,IAAI,CAAC,UAAU;AAAA,QAC5B,KAAK,aAAa,IAAI;AAAA,QACtB,QAAQ,cAAU,0BAAW,QAAQ,EAAE,OAAO,SAAS,IAAI,IAAI,CAAE,EAAE,OAAO,KAAK,CAAC;AAAA,QAChF,MAAM,SAAS,IAAI,IAAI,EAAG;AAAA,MAC9B,EAAE;AAAA,IACN;AAAA,EACJ;AACJ;AAEA,SAAS,aAAa,MAAsB;AACxC,SAAO,mBAAmB,QAAQ,YAAY,IAAI;AACtD;AAEO,MAAM,gBAAgB,kBAAkB;",
6
+ "names": []
7
+ }
@@ -83,7 +83,8 @@ function calculateHash(content) {
83
83
  return crypto.createHash("md5").update(content).digest("hex");
84
84
  }
85
85
  function getAppsDir() {
86
- return path.join(process.cwd(), "farseer-apps");
86
+ const base = process.env.FARSEER_APPS_DIR?.trim();
87
+ return path.join(base ? path.resolve(process.cwd(), base) : process.cwd(), "farseer-apps");
87
88
  }
88
89
  function getTenantDir(tenant) {
89
90
  return path.join(getAppsDir(), tenant);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/utils/helpers.ts"],
4
- "sourcesContent": ["import * as crypto from 'crypto';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { getCredential, getTenantOrg } from '../services/configService';\nimport { logger } from './logger';\nimport { formatClientError } from './errorFormatter';\nimport type { AppListItem, RemoteApp } from '../services/apps';\nimport type { ConnectionFailure, FarseerService } from '../services/farseerService';\nimport { selectByNameOrId, formatAmbiguous } from './nameResolver';\n\nexport function calculateHash(content: string | Buffer): string {\n return crypto.createHash('md5').update(content).digest('hex');\n}\n\nexport function getAppsDir(): string {\n return path.join(process.cwd(), 'farseer-apps');\n}\n\nexport function getTenantDir(tenant: string): string {\n return path.join(getAppsDir(), tenant);\n}\n\nexport function getTenantFilesDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'files');\n}\n\n/**\n * Human-readable path string for log output. Renders the directory the\n * CLI actually scans, so users who copy-paste the displayed path land\n * on the right files.\n *\n * Earlier `status` hard-coded the literal `apps/<tenant>/files/` which\n * had drifted from the real `farseer-apps/<tenant>/files/` layout \u2014\n * users who followed the displayed path edited files the CLI never\n * looked at. Deriving from the same helper as the operation prevents\n * the strings from drifting again.\n *\n * Edge cases handled:\n * \u2022 If a `path.relative(cwd, absDir)` would point UP (`../`) or to\n * the cwd itself, we fall back to the absolute path \u2014 the user is\n * running the CLI from outside / at the synced directory, and\n * showing `\"../\"` or an empty relative string is more confusing\n * than the absolute form.\n * \u2022 macOS resolves `/tmp` \u2192 `/private/tmp` via `fs.realpathSync`,\n * which makes `path.relative` from cwd `/tmp/x` to absDir\n * `/private/tmp/x/...` emit `../../../...`. We resolve both sides\n * through `realpathSync` before comparing so the symlink doesn't\n * leak into the displayed path.\n */\nexport function displayLocalPath(absDir: string): string {\n // Resolve symlinks on both sides so /tmp vs /private/tmp on macOS\n // doesn't blow up the relative path with `../../../`.\n const resolvedCwd = safeRealpath(process.cwd());\n const resolvedDir = safeRealpath(absDir);\n const rel = path.relative(resolvedCwd, resolvedDir);\n // `..` prefix means absDir is OUTSIDE cwd. Falling back to the\n // absolute form is clearer than a deep `../` chain \u2014 and it stays\n // copy-pasteable. An empty string means cwd === absDir, which would\n // otherwise render as just `/`; show `./` instead so the trailing\n // slash convention stays consistent.\n if (rel === '') return './';\n if (rel.startsWith('..')) return resolvedDir + '/';\n return rel + '/';\n}\n\n/**\n * `fs.realpathSync` with a graceful fallback: returns the input\n * unchanged when the path doesn't exist or can't be resolved. Used by\n * `displayLocalPath` so we can render a still-to-be-created tenant\n * folder without throwing.\n */\nfunction safeRealpath(p: string): string {\n try {\n return fs.realpathSync(p);\n } catch {\n return p;\n }\n}\n\n// Legacy - for backwards compatibility with run command\nexport function getTenantSrcDir(tenant: string): string {\n return path.join(getTenantFilesDir(tenant), 'Scripts');\n}\n\nexport function getSyncFilePath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-sync.json');\n}\n\nexport function getAuditLogPath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-audit.log');\n}\n\nexport function getTenantAppsDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'apps');\n}\n\nexport function ensureDirectoryExists(dirPath: string): void {\n if (!fs.existsSync(dirPath)) {\n fs.mkdirSync(dirPath, { recursive: true });\n }\n}\n\n/**\n * Returns `fullPath` relative to `basePath`, always with POSIX separators.\n *\n * On Windows `path.relative` returns backslash-separated paths. Those flow\n * through `getAllFilesInDir` / `getAllFiles` and become KEYS in the sync\n * state, `localFileHashes`, `localPresenceSet`, etc. Remote keys come back\n * from the API as POSIX (`/`-separated), so without this normalisation the\n * key comparison fails and every file looks like a local-delete + remote-add\n * pair. Normalising once here means every caller \u2014 sync state, status\n * comparator, blocklist matcher \u2014 sees the same shape regardless of OS.\n */\nexport function getRelativePath(fullPath: string, basePath: string): string {\n return path.relative(basePath, fullPath).split(path.sep).join('/');\n}\n\n/**\n * Resolve `filePath` against `baseDir` and verify the resolved path stays\n * inside it. Anything that escapes (`..`, absolute paths, symlink-style\n * tricks once resolved) throws \u2014 callers that build paths from REMOTE\n * data must use this so a backend bug or compromised tenant returning\n * `../../etc/passwd` can't write or unlink outside the tenant's files\n * folder.\n *\n * Use everywhere we touch the filesystem with a path that came from\n * remote: pull's writes/unlinks, the merge_markers `.remote` sibling\n * write, push/wipe candidate iteration, etc.\n */\nexport function safeResolveWithinBase(baseDir: string, filePath: string): string {\n const resolvedBase = path.resolve(baseDir);\n const resolved = path.resolve(resolvedBase, filePath);\n // path.resolve normalises `..`; check the result is inside the base\n // directory (allow exact match for the base itself, but require a\n // separator suffix for descendants to avoid `/foo/bar` vs `/foo/barbaz`).\n if (resolved !== resolvedBase && !resolved.startsWith(resolvedBase + path.sep)) {\n throw new Error(\n `Path escapes base directory: '${filePath}' resolves to '${resolved}' (base: '${resolvedBase}')`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolves a list of relative paths against `baseDir` and partitions\n * them into resolved-to-real-file vs. missing. Used by `push --only`\n * to validate the user's whitelist before any network call.\n *\n * \"Missing\" covers all the ways a path can fail to point at a real\n * file under the base:\n * - filename typo / wrong case / double slash\n * - file was deleted locally after the user typed the command\n * - traversal attempt (`../foo`) \u2014 safeResolveWithinBase throws, we\n * catch and treat it as missing rather than crashing the whole\n * pre-flight on the first offender. Without the catch, the user\n * would see one error and never get the consolidated \"here's\n * everything that didn't resolve\" output.\n *\n * Order is preserved in `missing` so the error message lists paths\n * in the same order the user wrote them.\n */\nexport function validateOnlyFilePaths(baseDir: string, paths: string[]): { missing: string[] } {\n const missing: string[] = [];\n for (const p of paths) {\n try {\n const fullPath = safeResolveWithinBase(baseDir, p);\n if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {\n missing.push(p);\n }\n } catch {\n missing.push(p);\n }\n }\n return { missing };\n}\n\n/**\n * OS-generated metadata files / folders that should NEVER be synced.\n *\n * These accumulate locally without the user creating them and would otherwise\n * leak into the remote workspace (and trip backend filename validation).\n * Match against the basename of any path segment, including nested copies\n * (e.g. `Scripts/.DS_Store`, `__MACOSX/Apps/foo.ts`).\n *\n * Lives in helpers (not syncService) so the file-listing helper itself can\n * apply the filter \u2014 keeping it in syncService meant every call site had to\n * remember to `.filter((f) => !isOsMetadataFile(f))` and a single forgotten\n * one would silently leak `.DS_Store` (which is exactly how PR #1878 started).\n */\nconst OS_METADATA_BASENAMES = new Set([\n '.DS_Store', // macOS Finder\n '.AppleDouble', // macOS Time Machine / netatalk\n '.LSOverride', // macOS Launch Services\n '.Spotlight-V100', // macOS Spotlight\n '.Trashes', // macOS\n '.fseventsd', // macOS\n '.DocumentRevisions-V100', // macOS\n '.TemporaryItems', // macOS\n '.VolumeIcon.icns', // macOS\n '.com.apple.timemachine.donotpresent',\n 'Thumbs.db', // Windows Explorer\n 'Thumbs.db:encryptable',\n 'ehthumbs.db', // Windows Explorer\n 'ehthumbs_vista.db',\n 'desktop.ini', // Windows\n '$RECYCLE.BIN', // Windows\n '__MACOSX', // macOS zip artefact\n]);\n\n/**\n * Returns true when any segment of the path is an OS metadata file/folder\n * we always want to hide from sync \u2014 irrespective of `--all` or includes\n * config. Used as the bottom-line filter in `getAllFilesInDir` and applied\n * defensively to remote listings so old clients can't get metadata files\n * stuck on a tenant.\n */\nexport function isOsMetadataFile(filePath: string): boolean {\n const segments = filePath.split('/');\n for (const seg of segments) {\n if (OS_METADATA_BASENAMES.has(seg)) return true;\n // The `._<name>` prefix is reserved for macOS AppleDouble resource\n // forks (created by tar/zip/AFP when copying across HFS+ boundaries)\n // and is therefore aggressive: any user-named file starting with\n // `._` is silently dropped from sync. We accept this \u2014 collisions\n // are rare in practice and the alternative (uploading bookkeeping\n // junk) is the worse failure mode.\n if (seg.startsWith('._')) return true;\n }\n return false;\n}\n\n/**\n * Returns true when the path contains any segment starting with `.` that is\n * NOT covered by `isOsMetadataFile`. Things like `.env`, `.git/`, `.vscode/`\n * fall here. The CLI's `shouldIncludeFile` requires explicit opt-in for\n * these (via `--include-ext` / `--include-folder` / persistent sync-includes\n * config) \u2014 they are never picked up by `--all` alone, so a stray credential\n * file in `farseer-apps/<tenant>/files/` doesn't get pushed by accident.\n */\nexport function isHiddenFile(filePath: string): boolean {\n if (isOsMetadataFile(filePath)) return false; // those have their own rule\n const segments = filePath.split('/');\n return segments.some((seg) => seg.length > 0 && seg.startsWith('.'));\n}\n\nexport function getAllFiles(dirPath: string, basePath?: string): string[] {\n if (!fs.existsSync(dirPath)) {\n return [];\n }\n\n const base = basePath || dirPath;\n const files: string[] = [];\n\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n files.push(...getAllFiles(fullPath, base));\n } else if (item.isFile() && isScriptFile(item.name)) {\n files.push(getRelativePath(fullPath, base));\n }\n }\n\n return files;\n}\n\n/**\n * Get all files in a directory recursively, with OS metadata stripped.\n *\n * The OS-metadata filter is the default behavior \u2014 every call site needs it,\n * and forgetting to add a `.filter((f) => !isOsMetadataFile(f))` at a new\n * call site is exactly how `.DS_Store` started leaking into pushes. Pass\n * `{ includeOsMetadata: true }` only when you have a specific reason to see\n * those files (e.g. a debug listing, audit dump). Hidden files are NOT\n * filtered here \u2014 that gate lives in `shouldIncludeFile` because the user\n * can opt in to specific dotfile patterns via the includes config.\n *\n * Pass `shouldSkipDir(relPath)` to short-circuit the walk into directories\n * the caller knows it will discard anyway. This is how callers actually\n * bound memory \u2014 without it a tenant containing `.git/` or `node_modules/`\n * still materialises every filename before any filter runs.\n */\nexport function getAllFilesInDir(\n dirPath: string,\n basePathOrOptions?: string | { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n optionsArg?: { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n): string[] {\n // Backwards-compat with the old (dirPath, basePath?) signature.\n const basePath = typeof basePathOrOptions === 'string' ? basePathOrOptions : undefined;\n const options = typeof basePathOrOptions === 'object' ? basePathOrOptions : (optionsArg ?? {});\n\n if (!fs.existsSync(dirPath)) return [];\n\n const base = basePath || dirPath;\n const files: string[] = [];\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n const relPath = getRelativePath(fullPath, base);\n // Skip whole OS-metadata directories at recursion time \u2014 saves a\n // pointless walk into `__MACOSX/` etc. when we'd just discard\n // every entry afterwards.\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) {\n continue;\n }\n // Caller-supplied skip: lets sync callers prune hidden/`node_modules`\n // subtrees before we materialise their contents.\n if (options.shouldSkipDir && options.shouldSkipDir(relPath)) {\n continue;\n }\n files.push(...getAllFilesInDir(fullPath, base, options));\n } else if (item.isFile()) {\n const relPath = getRelativePath(fullPath, base);\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) continue;\n files.push(relPath);\n }\n }\n\n return files;\n}\n\nexport function isScriptFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase();\n return ['.ts', '.js', '.mjs', '.cjs'].includes(ext);\n}\n\nexport function isTextFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase().slice(1); // remove leading dot\n return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(ext);\n}\n\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function formatDate(date: Date | string): string {\n const d = typeof date === 'string' ? new Date(date) : date;\n return d.toLocaleString();\n}\n\nexport function getCredentialsHint(tenant: string): string {\n return `Use: farseer login\n Or: farseer config set ${tenant} --api-key <key> --org <organisation>`;\n}\n\n/**\n * The headline for a failed credential probe. Shared by `config test` and\n * `login` so the same failure cannot be described two ways, and separate from\n * ConnectionCheck itself so the MCP surface can word it differently.\n */\nexport function connectionFailureMessage(reason: ConnectionFailure, host: string, tenant: string): string {\n switch (reason) {\n case 'rejected':\n return 'Connection failed: the server rejected this API key.';\n case 'tenant-unknown':\n return `Connection failed: ${host} has no tenant \"${tenant}\". The key is fine \u2014 check the organisation.`;\n case 'server-error':\n return `Connection failed: ${host} answered with an error.`;\n case 'unreachable':\n return `Connection failed: could not reach ${host}.`;\n }\n}\n\n/**\n * Resolve tenant from argument or the FARSEER_TENANT env.\n * If tenant is provided, use it. Otherwise, use the env tenant.\n * Returns null if no tenant is available.\n */\nexport interface ResolvedCheckout {\n organisation: string;\n tenant: string;\n}\n\n/**\n * Per-shell target from the environment. There is no persisted global default\n * any more \u2014 a command takes its tenant from an explicit argument or from\n * FARSEER_TENANT in the calling shell, and errors if neither is set. Two shells\n * can therefore hold different tenants at once, and a bare command never\n * silently retargets to a stale machine-global checkout.\n *\n * Org resolves the same way the MCP launch path does (mcp/utils/launchPin.ts):\n * FARSEER_ORG > saved tenant->org mapping > the tenant name. So once a confirmed\n * `farseer pull <org> <tenant>` has recorded the mapping, `export FARSEER_TENANT=x`\n * alone is enough; only new org != tenant tenants also need FARSEER_ORG.\n */\nexport function getEnvCheckout(): ResolvedCheckout | null {\n const tenant = process.env.FARSEER_TENANT;\n if (!tenant) return null;\n const organisation = process.env.FARSEER_ORG || getTenantOrg(tenant) || tenant;\n if (organisation === tenant) {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant}`);\n } else {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant} (org: ${organisation})`);\n }\n return { organisation, tenant };\n}\n\n/**\n * Resolve organisation and tenant from argument or the FARSEER_TENANT env.\n * When only tenant is provided, assumes organisation = tenant.\n */\nexport function resolveOrgAndTenant(tenantArg?: string): ResolvedCheckout | null {\n if (tenantArg) {\n // When tenant is specified as arg, assume org = tenant\n // (org != tenant tenants are resolved via the mapping in the\n // richer resolveTenantWithOrgMapping path).\n return { organisation: tenantArg, tenant: tenantArg };\n }\n\n return getEnvCheckout();\n}\n\nexport function resolveTenant(tenantArg?: string): string | null {\n const resolved = resolveOrgAndTenant(tenantArg);\n return resolved?.tenant || null;\n}\n\n/**\n * Resolve tenant or exit with error if not available.\n */\nexport function resolveTenantOrExit(tenantArg?: string): string {\n const tenant = resolveTenant(tenantArg);\n if (!tenant) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return tenant;\n}\n\n/**\n * Resolve organisation and tenant with support for org-tenant mapping.\n *\n * Usage patterns:\n * - <org> <tenant>: Explicit org and tenant\n * - <tenant>: Look up org from FARSEER_ORG or the saved mapping\n * - (no args): Fall back to FARSEER_TENANT/FARSEER_ORG from the shell\n *\n * Read-only by design: resolving a pair must not persist it. A typo'd org\n * (`farseer pull wrong-org my-tenant`) would otherwise be remembered as\n * my-tenant's org before anything confirmed it, and every later one-arg command\n * would inherit the wrong host \u2014 silently, since `*.farseer.io` is a wildcard.\n * The mapping is written by the preflight instead, and only for a pair the\n * organisation itself confirmed.\n *\n * @param arg1 - Organisation (if 2 args) or tenant (if 1 arg)\n * @param arg2 - Tenant (if 2 args)\n * @returns ResolvedCheckout or exits with error\n */\nexport function resolveTenantWithOrgMapping(arg1?: string, arg2?: string): ResolvedCheckout {\n // Case 1: Two arguments - <org> <tenant>\n if (arg1 && arg2) {\n const org = arg1;\n const tenant = arg2;\n\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n\n return { organisation: org, tenant };\n }\n\n // Case 2: One argument - <tenant>\n if (arg1) {\n const tenant = arg1;\n\n // FARSEER_ORG pairs with FARSEER_TENANT (it's the org for the shell's\n // env tenant), so only honour it when this explicit tenant IS that env\n // tenant \u2014 otherwise a shell-level FARSEER_ORG would leak onto an\n // unrelated tenant and build the wrong host. Else use the saved mapping.\n const envOrg = tenant === process.env.FARSEER_TENANT ? process.env.FARSEER_ORG : undefined;\n const org = envOrg || getTenantOrg(tenant);\n if (org) {\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n return { organisation: org, tenant };\n }\n\n // An API-key tenant needs no remembered org: the stored credential\n // carries its own base URL and the organisation is ignored on that path.\n // Only confirmed pairs get recorded now, so these tenants often have no\n // mapping at all \u2014 don't demand an org we would never use.\n if (getCredential(tenant)) {\n logger.dim(`Using tenant: ${tenant}`);\n return { organisation: tenant, tenant };\n }\n\n // Org for this tenant is unknown - fail loud rather than guess a host.\n logger.error(`Organisation unknown for tenant \"${tenant}\".`);\n logger.dim('Pass both: farseer <command> <organisation> <tenant>');\n logger.dim(`Or set them per shell: export FARSEER_TENANT=${tenant} FARSEER_ORG=<organisation>`);\n process.exit(1);\n }\n\n // Case 3: No arguments - fall back to FARSEER_TENANT from the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return envCheckout;\n }\n\n // Nothing to go on - fail loud instead of guessing a tenant.\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant> (FARSEER_ORG=<org> if org differs)');\n process.exit(1);\n}\n\n/**\n * Resolve organisation and tenant or exit with error.\n */\nexport function resolveOrgAndTenantOrExit(tenantArg?: string): ResolvedCheckout {\n const resolved = resolveOrgAndTenant(tenantArg);\n if (!resolved) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return resolved;\n}\n\n/**\n * Check if a string is a known tenant (has credentials configured).\n */\nexport function isKnownTenant(name: string): boolean {\n return !!getCredential(name);\n}\n\nexport interface ParsedAppArgs {\n organisation: string;\n tenant: string;\n appName: string;\n}\n\n/**\n * Parse variadic arguments to extract tenant and app name.\n * If first arg is a known tenant, use it as tenant and rest as app name.\n * Otherwise, use checked-out tenant and all args as app name.\n *\n * @param args Array of arguments (from variadic command)\n * @returns { organisation: string, tenant: string, appName: string }\n */\nexport function parseAppArgs(\n args: string[],\n options: { allowEmptyName?: boolean; command?: string } = {},\n): ParsedAppArgs {\n if (args.length === 0) {\n if (options.allowEmptyName) {\n // `--id` path: no app name was typed, so the tenant can only come\n // from FARSEER_TENANT in the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: '' };\n }\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer app show <tenant> --id <id>');\n logger.dim('Or set FARSEER_TENANT in your shell.');\n process.exit(1);\n }\n logger.error('App name is required.');\n process.exit(1);\n }\n\n // `--id` path with a single positional. It reads as a tenant \u2014 but the\n // collision message that sends people here had them type an app *name*, so\n // reading it as a tenant is how adding `--id` to a failed command silently\n // moves it to a different tenant.\n if (options.allowEmptyName && args.length === 1) {\n const only = args[0];\n const envCheckout = getEnvCheckout();\n const namesATenant = isKnownTenant(only) || !!getTenantOrg(only);\n\n if (envCheckout && namesATenant && only !== envCheckout.tenant) {\n // Both readings are real and they target different tenants, which is\n // the one case worth stopping for: on `app delete` the wrong guess\n // destroys something in a tenant the user never named.\n const command = options.command ?? 'app show';\n logger.error(`\"${only}\" is both a configured tenant and the name you are selecting by id.`);\n logger.dim('With --id the name is not used, so drop it and let the tenant say itself:');\n logger.dim(` farseer ${command} --id <id> (tenant ${envCheckout.tenant})`);\n logger.dim(` FARSEER_TENANT=${only} farseer ${command} --id <id> (tenant ${only})`);\n process.exit(1);\n }\n\n // An env tenant means the command already had a target before `--id` was\n // added, and adding it must not move that target.\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: only };\n }\n\n return { organisation: getTenantOrg(only) || only, tenant: only, appName: '' };\n }\n\n // First arg looks like a tenant when either:\n // (a) we have API-key credentials saved for it, or\n // (b) we have a saved tenantOrgMapping entry for it (from a previous\n // `farseer pull <org> <tenant>`).\n // In both cases we prefer the saved organisation over args[0] so\n // run/apps/etc. build the right URL when org != tenant.\n if (args.length >= 2) {\n const first = args[0];\n const knownViaCredential = isKnownTenant(first);\n const savedOrg = getTenantOrg(first);\n if (knownViaCredential || savedOrg) {\n return {\n organisation: savedOrg || first,\n tenant: first,\n appName: args.slice(1).join(' '),\n };\n }\n }\n\n // Fall back to FARSEER_TENANT from the shell; all args are the app name.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return {\n organisation: envCheckout.organisation,\n tenant: envCheckout.tenant,\n appName: args.join(' '),\n };\n }\n\n // No env tenant and first arg isn't a known tenant\n // Assume first arg is tenant (will fail later if invalid)\n if (args.length >= 2) {\n return {\n organisation: args[0],\n tenant: args[0],\n appName: args.slice(1).join(' '),\n };\n }\n\n // Only one arg and no env tenant - could be tenant or app name\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer app show <tenant> <app-name>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n}\n\n/**\n * Run a lookup that reports absence as null and everything else by throwing,\n * and end the command on the everything else. Commander does not await an\n * action, so without a boundary here the rejection escapes to the process\n * handler, which is the wrong place to explain that one read failed.\n */\nexport async function orExit<T>(work: Promise<T>, message: string): Promise<T> {\n try {\n return await work;\n } catch (error) {\n logger.error(message);\n logger.dim(await formatClientError(error));\n return process.exit(1);\n }\n}\n\n/**\n * Resolve an app to its folder list item, or exit with a clear message. An\n * explicit `--id` wins; a name that matches more than one app aborts, listing\n * the candidates, rather than picking the first.\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 resolveAppItemOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<AppListItem> {\n const apps = await orExit(api.listApps(), 'Failed to list apps.');\n const selection = selectByNameOrId(apps, { name: selector.appName, id: selector.id }, (a) => a.reference);\n\n if (selection.kind === 'found') {\n return selection.entity;\n }\n\n if (selection.kind === 'ambiguous') {\n logger.error(formatAmbiguous('apps', selector.appName ?? '', selection.matches, (a) => a.reference));\n logger.dim('Re-run with --id <id> in place of the name to pick one.');\n process.exit(1);\n }\n\n if (selection.kind === 'conflict') {\n const { entity: app, name } = selection;\n logger.error(\n `App ${app.reference} is \"${app.name}\", not \"${name}\". The id and the name point at different apps, so nothing was done.`,\n );\n logger.dim(\n `To act on app ${app.reference}${selector.tenant ? ` in tenant \"${selector.tenant}\"` : ''}, drop the name.`,\n );\n if (!/\\s/.test(name)) {\n logger.dim(\n `If \"${name}\" is a tenant, select it and re-run with only the id: export FARSEER_TENANT=${name}`,\n );\n }\n process.exit(1);\n }\n\n logger.error(selector.id ? `App not found: id ${selector.id}` : `App not found: ${selector.appName}`);\n logger.dim('List apps with: farseer app list <tenant>');\n process.exit(1);\n}\n\n/**\n * Resolve an app for a CLI command to its full details, or exit with a clear\n * message. Wraps `resolveAppItemOrExit` + `getApp` so the commands that need\n * the whole `RemoteApp` (show, run) don't repeat the fetch.\n */\nexport async function resolveAppOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<RemoteApp> {\n const item = await resolveAppItemOrExit(api, selector);\n const app = await orExit(api.getApp(item.reference), `Failed to load app details: ${item.name}`);\n if (!app) {\n logger.error(`Failed to load app details: ${item.name}`);\n process.exit(1);\n }\n return app;\n}\n\n// Credential injection/stripping for local development\n// Matches: const farseerClient = new farseer.FarseerClient();\n// and: const fClient = new farseer.FarseerClient();\n\ninterface CredentialConfig {\n basePath: string;\n tenantId: string;\n apiKey: string;\n}\n\n// Pattern to match empty FarseerClient() constructor (no /g flag to avoid lastIndex issues)\nconst EMPTY_CLIENT_PATTERNS = [\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n];\n\n// Pattern to match FarseerClient with injected credentials (multiline, no /g flag)\nconst INJECTED_CLIENT_PATTERN =\n /const (farseerClient|fClient) = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/;\n\nexport function injectCredentials(code: string, credential: CredentialConfig): string {\n const clientConfig = `{\n basePath: '${credential.basePath}',\n headers: {\n 'X-TENANT-ID': '${credential.tenantId}',\n 'X-API-KEY': '${credential.apiKey}',\n }\n }`;\n\n let modified = code;\n\n // Pattern 1: const farseerClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const farseerClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n // Pattern 2: const fClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const fClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n return modified;\n}\n\nexport function stripCredentials(code: string): string {\n // Replace injected credentials back to empty constructor\n let modified = code;\n\n // Match farseerClient with credentials\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const farseerClient = new farseer.FarseerClient();',\n );\n\n // Match fClient with credentials\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const fClient = new farseer.FarseerClient();',\n );\n\n return modified;\n}\n\nexport function hasInjectedCredentials(code: string): boolean {\n return INJECTED_CLIENT_PATTERN.test(code);\n}\n\nexport function hasEmptyFarseerClient(code: string): boolean {\n return EMPTY_CLIENT_PATTERNS.some((pattern) => pattern.test(code));\n}\n\n// Process all script files in a directory\nexport function injectCredentialsInDir(srcDir: string, credential: CredentialConfig): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = injectCredentials(content, credential);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\nexport function stripCredentialsInDir(srcDir: string): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = stripCredentials(content);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\n// Audit log helpers\nexport interface AuditLogEntry {\n operation: 'pulled' | 'pushed' | 'deleted';\n filePath: string;\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n}\n\n/**\n * Execute async operations with limited concurrency.\n * Processes items in chunks to avoid overwhelming the API.\n *\n * @param items Array of items to process\n * @param fetcher Async function to call for each item\n * @param concurrency Maximum number of concurrent requests (default: 15)\n * @returns Array of results in the same order as input items\n */\nexport async function fetchWithConcurrency<T, R>(\n items: T[],\n fetcher: (item: T, index: number) => Promise<R>,\n concurrency: number = 15,\n): Promise<R[]> {\n const results: R[] = [];\n\n for (let i = 0; i < items.length; i += concurrency) {\n const chunk = items.slice(i, i + concurrency);\n const chunkResults = await Promise.all(chunk.map((item, chunkIndex) => fetcher(item, i + chunkIndex)));\n results.push(...chunkResults);\n }\n\n return results;\n}\n\nexport function appendToAuditLog(tenant: string, entries: AuditLogEntry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const logPath = getAuditLogPath(tenant);\n const timestamp = new Date().toISOString();\n\n let logContent = '';\n for (const entry of entries) {\n const uploaderInfo = entry.uploaderName\n ? `${entry.uploaderName} (${entry.uploaderEmail})`\n : entry.uploaderEmail || 'Unknown';\n\n const uploadedAt = entry.uploadTime ? new Date(entry.uploadTime).toLocaleString() : 'Unknown';\n\n logContent += `${timestamp} | ${entry.operation} | ${entry.filePath} | Modified by: ${uploaderInfo} | Uploaded: ${uploadedAt}\\n`;\n }\n\n fs.appendFileSync(logPath, logContent, 'utf-8');\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,aAAwB;AACxB,WAAsB;AACtB,SAAoB;AACpB,2BAA4C;AAC5C,oBAAuB;AACvB,4BAAkC;AAGlC,0BAAkD;AAE3C,SAAS,cAAc,SAA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U,gBAAgB,MAAM;AACtC,QAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AAEzC,MAAI,aAAa;AACjB,aAAW,SAAS,SAAS;AACzB,UAAM,eAAe,MAAM,eACrB,GAAG,MAAM,YAAY,KAAK,MAAM,aAAa,MAC7C,MAAM,iBAAiB;AAE7B,UAAM,aAAa,MAAM,aAAa,IAAI,KAAK,MAAM,UAAU,EAAE,eAAe,IAAI;AAEpF,kBAAc,GAAG,SAAS,MAAM,MAAM,SAAS,MAAM,MAAM,QAAQ,mBAAmB,YAAY,gBAAgB,UAAU;AAAA;AAAA,EAChI;AAEA,KAAG,eAAe,SAAS,YAAY,OAAO;AAClD;",
4
+ "sourcesContent": ["import * as crypto from 'crypto';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport { getCredential, getTenantOrg } from '../services/configService';\nimport { logger } from './logger';\nimport { formatClientError } from './errorFormatter';\nimport type { AppListItem, RemoteApp } from '../services/apps';\nimport type { ConnectionFailure, FarseerService } from '../services/farseerService';\nimport { selectByNameOrId, formatAmbiguous } from './nameResolver';\n\nexport function calculateHash(content: string | Buffer): string {\n return crypto.createHash('md5').update(content).digest('hex');\n}\n\n/**\n * Where tenant folders live: `<FARSEER_APPS_DIR>/farseer-apps/<tenant>`, or the working\n * directory when the variable is unset. A host that starts `farseer mcp-server` from a\n * different directory than the project it manages (Mindseer starts it from the project\n * root and keeps each instance's files under `instances/<slug>/`) points it here.\n */\nexport function getAppsDir(): string {\n const base = process.env.FARSEER_APPS_DIR?.trim();\n return path.join(base ? path.resolve(process.cwd(), base) : process.cwd(), 'farseer-apps');\n}\n\nexport function getTenantDir(tenant: string): string {\n return path.join(getAppsDir(), tenant);\n}\n\nexport function getTenantFilesDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'files');\n}\n\n/**\n * Human-readable path string for log output. Renders the directory the\n * CLI actually scans, so users who copy-paste the displayed path land\n * on the right files.\n *\n * Earlier `status` hard-coded the literal `apps/<tenant>/files/` which\n * had drifted from the real `farseer-apps/<tenant>/files/` layout \u2014\n * users who followed the displayed path edited files the CLI never\n * looked at. Deriving from the same helper as the operation prevents\n * the strings from drifting again.\n *\n * Edge cases handled:\n * \u2022 If a `path.relative(cwd, absDir)` would point UP (`../`) or to\n * the cwd itself, we fall back to the absolute path \u2014 the user is\n * running the CLI from outside / at the synced directory, and\n * showing `\"../\"` or an empty relative string is more confusing\n * than the absolute form.\n * \u2022 macOS resolves `/tmp` \u2192 `/private/tmp` via `fs.realpathSync`,\n * which makes `path.relative` from cwd `/tmp/x` to absDir\n * `/private/tmp/x/...` emit `../../../...`. We resolve both sides\n * through `realpathSync` before comparing so the symlink doesn't\n * leak into the displayed path.\n */\nexport function displayLocalPath(absDir: string): string {\n // Resolve symlinks on both sides so /tmp vs /private/tmp on macOS\n // doesn't blow up the relative path with `../../../`.\n const resolvedCwd = safeRealpath(process.cwd());\n const resolvedDir = safeRealpath(absDir);\n const rel = path.relative(resolvedCwd, resolvedDir);\n // `..` prefix means absDir is OUTSIDE cwd. Falling back to the\n // absolute form is clearer than a deep `../` chain \u2014 and it stays\n // copy-pasteable. An empty string means cwd === absDir, which would\n // otherwise render as just `/`; show `./` instead so the trailing\n // slash convention stays consistent.\n if (rel === '') return './';\n if (rel.startsWith('..')) return resolvedDir + '/';\n return rel + '/';\n}\n\n/**\n * `fs.realpathSync` with a graceful fallback: returns the input\n * unchanged when the path doesn't exist or can't be resolved. Used by\n * `displayLocalPath` so we can render a still-to-be-created tenant\n * folder without throwing.\n */\nfunction safeRealpath(p: string): string {\n try {\n return fs.realpathSync(p);\n } catch {\n return p;\n }\n}\n\n// Legacy - for backwards compatibility with run command\nexport function getTenantSrcDir(tenant: string): string {\n return path.join(getTenantFilesDir(tenant), 'Scripts');\n}\n\nexport function getSyncFilePath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-sync.json');\n}\n\nexport function getAuditLogPath(tenant: string): string {\n return path.join(getTenantDir(tenant), '.farseer-audit.log');\n}\n\nexport function getTenantAppsDir(tenant: string): string {\n return path.join(getTenantDir(tenant), 'apps');\n}\n\nexport function ensureDirectoryExists(dirPath: string): void {\n if (!fs.existsSync(dirPath)) {\n fs.mkdirSync(dirPath, { recursive: true });\n }\n}\n\n/**\n * Returns `fullPath` relative to `basePath`, always with POSIX separators.\n *\n * On Windows `path.relative` returns backslash-separated paths. Those flow\n * through `getAllFilesInDir` / `getAllFiles` and become KEYS in the sync\n * state, `localFileHashes`, `localPresenceSet`, etc. Remote keys come back\n * from the API as POSIX (`/`-separated), so without this normalisation the\n * key comparison fails and every file looks like a local-delete + remote-add\n * pair. Normalising once here means every caller \u2014 sync state, status\n * comparator, blocklist matcher \u2014 sees the same shape regardless of OS.\n */\nexport function getRelativePath(fullPath: string, basePath: string): string {\n return path.relative(basePath, fullPath).split(path.sep).join('/');\n}\n\n/**\n * Resolve `filePath` against `baseDir` and verify the resolved path stays\n * inside it. Anything that escapes (`..`, absolute paths, symlink-style\n * tricks once resolved) throws \u2014 callers that build paths from REMOTE\n * data must use this so a backend bug or compromised tenant returning\n * `../../etc/passwd` can't write or unlink outside the tenant's files\n * folder.\n *\n * Use everywhere we touch the filesystem with a path that came from\n * remote: pull's writes/unlinks, the merge_markers `.remote` sibling\n * write, push/wipe candidate iteration, etc.\n */\nexport function safeResolveWithinBase(baseDir: string, filePath: string): string {\n const resolvedBase = path.resolve(baseDir);\n const resolved = path.resolve(resolvedBase, filePath);\n // path.resolve normalises `..`; check the result is inside the base\n // directory (allow exact match for the base itself, but require a\n // separator suffix for descendants to avoid `/foo/bar` vs `/foo/barbaz`).\n if (resolved !== resolvedBase && !resolved.startsWith(resolvedBase + path.sep)) {\n throw new Error(\n `Path escapes base directory: '${filePath}' resolves to '${resolved}' (base: '${resolvedBase}')`,\n );\n }\n return resolved;\n}\n\n/**\n * Resolves a list of relative paths against `baseDir` and partitions\n * them into resolved-to-real-file vs. missing. Used by `push --only`\n * to validate the user's whitelist before any network call.\n *\n * \"Missing\" covers all the ways a path can fail to point at a real\n * file under the base:\n * - filename typo / wrong case / double slash\n * - file was deleted locally after the user typed the command\n * - traversal attempt (`../foo`) \u2014 safeResolveWithinBase throws, we\n * catch and treat it as missing rather than crashing the whole\n * pre-flight on the first offender. Without the catch, the user\n * would see one error and never get the consolidated \"here's\n * everything that didn't resolve\" output.\n *\n * Order is preserved in `missing` so the error message lists paths\n * in the same order the user wrote them.\n */\nexport function validateOnlyFilePaths(baseDir: string, paths: string[]): { missing: string[] } {\n const missing: string[] = [];\n for (const p of paths) {\n try {\n const fullPath = safeResolveWithinBase(baseDir, p);\n if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {\n missing.push(p);\n }\n } catch {\n missing.push(p);\n }\n }\n return { missing };\n}\n\n/**\n * OS-generated metadata files / folders that should NEVER be synced.\n *\n * These accumulate locally without the user creating them and would otherwise\n * leak into the remote workspace (and trip backend filename validation).\n * Match against the basename of any path segment, including nested copies\n * (e.g. `Scripts/.DS_Store`, `__MACOSX/Apps/foo.ts`).\n *\n * Lives in helpers (not syncService) so the file-listing helper itself can\n * apply the filter \u2014 keeping it in syncService meant every call site had to\n * remember to `.filter((f) => !isOsMetadataFile(f))` and a single forgotten\n * one would silently leak `.DS_Store` (which is exactly how PR #1878 started).\n */\nconst OS_METADATA_BASENAMES = new Set([\n '.DS_Store', // macOS Finder\n '.AppleDouble', // macOS Time Machine / netatalk\n '.LSOverride', // macOS Launch Services\n '.Spotlight-V100', // macOS Spotlight\n '.Trashes', // macOS\n '.fseventsd', // macOS\n '.DocumentRevisions-V100', // macOS\n '.TemporaryItems', // macOS\n '.VolumeIcon.icns', // macOS\n '.com.apple.timemachine.donotpresent',\n 'Thumbs.db', // Windows Explorer\n 'Thumbs.db:encryptable',\n 'ehthumbs.db', // Windows Explorer\n 'ehthumbs_vista.db',\n 'desktop.ini', // Windows\n '$RECYCLE.BIN', // Windows\n '__MACOSX', // macOS zip artefact\n]);\n\n/**\n * Returns true when any segment of the path is an OS metadata file/folder\n * we always want to hide from sync \u2014 irrespective of `--all` or includes\n * config. Used as the bottom-line filter in `getAllFilesInDir` and applied\n * defensively to remote listings so old clients can't get metadata files\n * stuck on a tenant.\n */\nexport function isOsMetadataFile(filePath: string): boolean {\n const segments = filePath.split('/');\n for (const seg of segments) {\n if (OS_METADATA_BASENAMES.has(seg)) return true;\n // The `._<name>` prefix is reserved for macOS AppleDouble resource\n // forks (created by tar/zip/AFP when copying across HFS+ boundaries)\n // and is therefore aggressive: any user-named file starting with\n // `._` is silently dropped from sync. We accept this \u2014 collisions\n // are rare in practice and the alternative (uploading bookkeeping\n // junk) is the worse failure mode.\n if (seg.startsWith('._')) return true;\n }\n return false;\n}\n\n/**\n * Returns true when the path contains any segment starting with `.` that is\n * NOT covered by `isOsMetadataFile`. Things like `.env`, `.git/`, `.vscode/`\n * fall here. The CLI's `shouldIncludeFile` requires explicit opt-in for\n * these (via `--include-ext` / `--include-folder` / persistent sync-includes\n * config) \u2014 they are never picked up by `--all` alone, so a stray credential\n * file in `farseer-apps/<tenant>/files/` doesn't get pushed by accident.\n */\nexport function isHiddenFile(filePath: string): boolean {\n if (isOsMetadataFile(filePath)) return false; // those have their own rule\n const segments = filePath.split('/');\n return segments.some((seg) => seg.length > 0 && seg.startsWith('.'));\n}\n\nexport function getAllFiles(dirPath: string, basePath?: string): string[] {\n if (!fs.existsSync(dirPath)) {\n return [];\n }\n\n const base = basePath || dirPath;\n const files: string[] = [];\n\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n files.push(...getAllFiles(fullPath, base));\n } else if (item.isFile() && isScriptFile(item.name)) {\n files.push(getRelativePath(fullPath, base));\n }\n }\n\n return files;\n}\n\n/**\n * Get all files in a directory recursively, with OS metadata stripped.\n *\n * The OS-metadata filter is the default behavior \u2014 every call site needs it,\n * and forgetting to add a `.filter((f) => !isOsMetadataFile(f))` at a new\n * call site is exactly how `.DS_Store` started leaking into pushes. Pass\n * `{ includeOsMetadata: true }` only when you have a specific reason to see\n * those files (e.g. a debug listing, audit dump). Hidden files are NOT\n * filtered here \u2014 that gate lives in `shouldIncludeFile` because the user\n * can opt in to specific dotfile patterns via the includes config.\n *\n * Pass `shouldSkipDir(relPath)` to short-circuit the walk into directories\n * the caller knows it will discard anyway. This is how callers actually\n * bound memory \u2014 without it a tenant containing `.git/` or `node_modules/`\n * still materialises every filename before any filter runs.\n */\nexport function getAllFilesInDir(\n dirPath: string,\n basePathOrOptions?: string | { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n optionsArg?: { includeOsMetadata?: boolean; shouldSkipDir?: (relPath: string) => boolean },\n): string[] {\n // Backwards-compat with the old (dirPath, basePath?) signature.\n const basePath = typeof basePathOrOptions === 'string' ? basePathOrOptions : undefined;\n const options = typeof basePathOrOptions === 'object' ? basePathOrOptions : (optionsArg ?? {});\n\n if (!fs.existsSync(dirPath)) return [];\n\n const base = basePath || dirPath;\n const files: string[] = [];\n const items = fs.readdirSync(dirPath, { withFileTypes: true });\n\n for (const item of items) {\n const fullPath = path.join(dirPath, item.name);\n\n if (item.isDirectory()) {\n const relPath = getRelativePath(fullPath, base);\n // Skip whole OS-metadata directories at recursion time \u2014 saves a\n // pointless walk into `__MACOSX/` etc. when we'd just discard\n // every entry afterwards.\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) {\n continue;\n }\n // Caller-supplied skip: lets sync callers prune hidden/`node_modules`\n // subtrees before we materialise their contents.\n if (options.shouldSkipDir && options.shouldSkipDir(relPath)) {\n continue;\n }\n files.push(...getAllFilesInDir(fullPath, base, options));\n } else if (item.isFile()) {\n const relPath = getRelativePath(fullPath, base);\n if (!options.includeOsMetadata && isOsMetadataFile(relPath)) continue;\n files.push(relPath);\n }\n }\n\n return files;\n}\n\nexport function isScriptFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase();\n return ['.ts', '.js', '.mjs', '.cjs'].includes(ext);\n}\n\nexport function isTextFile(filename: string): boolean {\n const ext = path.extname(filename).toLowerCase().slice(1); // remove leading dot\n return ['ts', 'js', 'mjs', 'cjs', 'json', 'txt', 'md', 'csv', 'xml', 'html', 'css', 'yaml', 'yml'].includes(ext);\n}\n\nexport function formatFileSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function formatDate(date: Date | string): string {\n const d = typeof date === 'string' ? new Date(date) : date;\n return d.toLocaleString();\n}\n\nexport function getCredentialsHint(tenant: string): string {\n return `Use: farseer login\n Or: farseer config set ${tenant} --api-key <key> --org <organisation>`;\n}\n\n/**\n * The headline for a failed credential probe. Shared by `config test` and\n * `login` so the same failure cannot be described two ways, and separate from\n * ConnectionCheck itself so the MCP surface can word it differently.\n */\nexport function connectionFailureMessage(reason: ConnectionFailure, host: string, tenant: string): string {\n switch (reason) {\n case 'rejected':\n return 'Connection failed: the server rejected this API key.';\n case 'tenant-unknown':\n return `Connection failed: ${host} has no tenant \"${tenant}\". The key is fine \u2014 check the organisation.`;\n case 'server-error':\n return `Connection failed: ${host} answered with an error.`;\n case 'unreachable':\n return `Connection failed: could not reach ${host}.`;\n }\n}\n\n/**\n * Resolve tenant from argument or the FARSEER_TENANT env.\n * If tenant is provided, use it. Otherwise, use the env tenant.\n * Returns null if no tenant is available.\n */\nexport interface ResolvedCheckout {\n organisation: string;\n tenant: string;\n}\n\n/**\n * Per-shell target from the environment. There is no persisted global default\n * any more \u2014 a command takes its tenant from an explicit argument or from\n * FARSEER_TENANT in the calling shell, and errors if neither is set. Two shells\n * can therefore hold different tenants at once, and a bare command never\n * silently retargets to a stale machine-global checkout.\n *\n * Org resolves the same way the MCP launch path does (mcp/utils/launchPin.ts):\n * FARSEER_ORG > saved tenant->org mapping > the tenant name. So once a confirmed\n * `farseer pull <org> <tenant>` has recorded the mapping, `export FARSEER_TENANT=x`\n * alone is enough; only new org != tenant tenants also need FARSEER_ORG.\n */\nexport function getEnvCheckout(): ResolvedCheckout | null {\n const tenant = process.env.FARSEER_TENANT;\n if (!tenant) return null;\n const organisation = process.env.FARSEER_ORG || getTenantOrg(tenant) || tenant;\n if (organisation === tenant) {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant}`);\n } else {\n logger.dim(`Using tenant from FARSEER_TENANT: ${tenant} (org: ${organisation})`);\n }\n return { organisation, tenant };\n}\n\n/**\n * Resolve organisation and tenant from argument or the FARSEER_TENANT env.\n * When only tenant is provided, assumes organisation = tenant.\n */\nexport function resolveOrgAndTenant(tenantArg?: string): ResolvedCheckout | null {\n if (tenantArg) {\n // When tenant is specified as arg, assume org = tenant\n // (org != tenant tenants are resolved via the mapping in the\n // richer resolveTenantWithOrgMapping path).\n return { organisation: tenantArg, tenant: tenantArg };\n }\n\n return getEnvCheckout();\n}\n\nexport function resolveTenant(tenantArg?: string): string | null {\n const resolved = resolveOrgAndTenant(tenantArg);\n return resolved?.tenant || null;\n}\n\n/**\n * Resolve tenant or exit with error if not available.\n */\nexport function resolveTenantOrExit(tenantArg?: string): string {\n const tenant = resolveTenant(tenantArg);\n if (!tenant) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return tenant;\n}\n\n/**\n * Resolve organisation and tenant with support for org-tenant mapping.\n *\n * Usage patterns:\n * - <org> <tenant>: Explicit org and tenant\n * - <tenant>: Look up org from FARSEER_ORG or the saved mapping\n * - (no args): Fall back to FARSEER_TENANT/FARSEER_ORG from the shell\n *\n * Read-only by design: resolving a pair must not persist it. A typo'd org\n * (`farseer pull wrong-org my-tenant`) would otherwise be remembered as\n * my-tenant's org before anything confirmed it, and every later one-arg command\n * would inherit the wrong host \u2014 silently, since `*.farseer.io` is a wildcard.\n * The mapping is written by the preflight instead, and only for a pair the\n * organisation itself confirmed.\n *\n * @param arg1 - Organisation (if 2 args) or tenant (if 1 arg)\n * @param arg2 - Tenant (if 2 args)\n * @returns ResolvedCheckout or exits with error\n */\nexport function resolveTenantWithOrgMapping(arg1?: string, arg2?: string): ResolvedCheckout {\n // Case 1: Two arguments - <org> <tenant>\n if (arg1 && arg2) {\n const org = arg1;\n const tenant = arg2;\n\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n\n return { organisation: org, tenant };\n }\n\n // Case 2: One argument - <tenant>\n if (arg1) {\n const tenant = arg1;\n\n // FARSEER_ORG pairs with FARSEER_TENANT (it's the org for the shell's\n // env tenant), so only honour it when this explicit tenant IS that env\n // tenant \u2014 otherwise a shell-level FARSEER_ORG would leak onto an\n // unrelated tenant and build the wrong host. Else use the saved mapping.\n const envOrg = tenant === process.env.FARSEER_TENANT ? process.env.FARSEER_ORG : undefined;\n const org = envOrg || getTenantOrg(tenant);\n if (org) {\n if (org === tenant) {\n logger.dim(`Using tenant: ${tenant}`);\n } else {\n logger.dim(`Using tenant: ${tenant} (org: ${org})`);\n }\n return { organisation: org, tenant };\n }\n\n // An API-key tenant needs no remembered org: the stored credential\n // carries its own base URL and the organisation is ignored on that path.\n // Only confirmed pairs get recorded now, so these tenants often have no\n // mapping at all \u2014 don't demand an org we would never use.\n if (getCredential(tenant)) {\n logger.dim(`Using tenant: ${tenant}`);\n return { organisation: tenant, tenant };\n }\n\n // Org for this tenant is unknown - fail loud rather than guess a host.\n logger.error(`Organisation unknown for tenant \"${tenant}\".`);\n logger.dim('Pass both: farseer <command> <organisation> <tenant>');\n logger.dim(`Or set them per shell: export FARSEER_TENANT=${tenant} FARSEER_ORG=<organisation>`);\n process.exit(1);\n }\n\n // Case 3: No arguments - fall back to FARSEER_TENANT from the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return envCheckout;\n }\n\n // Nothing to go on - fail loud instead of guessing a tenant.\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant> (FARSEER_ORG=<org> if org differs)');\n process.exit(1);\n}\n\n/**\n * Resolve organisation and tenant or exit with error.\n */\nexport function resolveOrgAndTenantOrExit(tenantArg?: string): ResolvedCheckout {\n const resolved = resolveOrgAndTenant(tenantArg);\n if (!resolved) {\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer <command> <tenant>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n }\n return resolved;\n}\n\n/**\n * Check if a string is a known tenant (has credentials configured).\n */\nexport function isKnownTenant(name: string): boolean {\n return !!getCredential(name);\n}\n\nexport interface ParsedAppArgs {\n organisation: string;\n tenant: string;\n appName: string;\n}\n\n/**\n * Parse variadic arguments to extract tenant and app name.\n * If first arg is a known tenant, use it as tenant and rest as app name.\n * Otherwise, use checked-out tenant and all args as app name.\n *\n * @param args Array of arguments (from variadic command)\n * @returns { organisation: string, tenant: string, appName: string }\n */\nexport function parseAppArgs(\n args: string[],\n options: { allowEmptyName?: boolean; command?: string } = {},\n): ParsedAppArgs {\n if (args.length === 0) {\n if (options.allowEmptyName) {\n // `--id` path: no app name was typed, so the tenant can only come\n // from FARSEER_TENANT in the shell.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: '' };\n }\n logger.error('No tenant specified.');\n logger.dim('Either specify a tenant: farseer app show <tenant> --id <id>');\n logger.dim('Or set FARSEER_TENANT in your shell.');\n process.exit(1);\n }\n logger.error('App name is required.');\n process.exit(1);\n }\n\n // `--id` path with a single positional. It reads as a tenant \u2014 but the\n // collision message that sends people here had them type an app *name*, so\n // reading it as a tenant is how adding `--id` to a failed command silently\n // moves it to a different tenant.\n if (options.allowEmptyName && args.length === 1) {\n const only = args[0];\n const envCheckout = getEnvCheckout();\n const namesATenant = isKnownTenant(only) || !!getTenantOrg(only);\n\n if (envCheckout && namesATenant && only !== envCheckout.tenant) {\n // Both readings are real and they target different tenants, which is\n // the one case worth stopping for: on `app delete` the wrong guess\n // destroys something in a tenant the user never named.\n const command = options.command ?? 'app show';\n logger.error(`\"${only}\" is both a configured tenant and the name you are selecting by id.`);\n logger.dim('With --id the name is not used, so drop it and let the tenant say itself:');\n logger.dim(` farseer ${command} --id <id> (tenant ${envCheckout.tenant})`);\n logger.dim(` FARSEER_TENANT=${only} farseer ${command} --id <id> (tenant ${only})`);\n process.exit(1);\n }\n\n // An env tenant means the command already had a target before `--id` was\n // added, and adding it must not move that target.\n if (envCheckout) {\n return { organisation: envCheckout.organisation, tenant: envCheckout.tenant, appName: only };\n }\n\n return { organisation: getTenantOrg(only) || only, tenant: only, appName: '' };\n }\n\n // First arg looks like a tenant when either:\n // (a) we have API-key credentials saved for it, or\n // (b) we have a saved tenantOrgMapping entry for it (from a previous\n // `farseer pull <org> <tenant>`).\n // In both cases we prefer the saved organisation over args[0] so\n // run/apps/etc. build the right URL when org != tenant.\n if (args.length >= 2) {\n const first = args[0];\n const knownViaCredential = isKnownTenant(first);\n const savedOrg = getTenantOrg(first);\n if (knownViaCredential || savedOrg) {\n return {\n organisation: savedOrg || first,\n tenant: first,\n appName: args.slice(1).join(' '),\n };\n }\n }\n\n // Fall back to FARSEER_TENANT from the shell; all args are the app name.\n const envCheckout = getEnvCheckout();\n if (envCheckout) {\n return {\n organisation: envCheckout.organisation,\n tenant: envCheckout.tenant,\n appName: args.join(' '),\n };\n }\n\n // No env tenant and first arg isn't a known tenant\n // Assume first arg is tenant (will fail later if invalid)\n if (args.length >= 2) {\n return {\n organisation: args[0],\n tenant: args[0],\n appName: args.slice(1).join(' '),\n };\n }\n\n // Only one arg and no env tenant - could be tenant or app name\n logger.error('No tenant specified.');\n logger.dim('Pass it: farseer app show <tenant> <app-name>');\n logger.dim('Or set it (per shell): export FARSEER_TENANT=<tenant>');\n process.exit(1);\n}\n\n/**\n * Run a lookup that reports absence as null and everything else by throwing,\n * and end the command on the everything else. Commander does not await an\n * action, so without a boundary here the rejection escapes to the process\n * handler, which is the wrong place to explain that one read failed.\n */\nexport async function orExit<T>(work: Promise<T>, message: string): Promise<T> {\n try {\n return await work;\n } catch (error) {\n logger.error(message);\n logger.dim(await formatClientError(error));\n return process.exit(1);\n }\n}\n\n/**\n * Resolve an app to its folder list item, or exit with a clear message. An\n * explicit `--id` wins; a name that matches more than one app aborts, listing\n * the candidates, rather than picking the first.\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 resolveAppItemOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<AppListItem> {\n const apps = await orExit(api.listApps(), 'Failed to list apps.');\n const selection = selectByNameOrId(apps, { name: selector.appName, id: selector.id }, (a) => a.reference);\n\n if (selection.kind === 'found') {\n return selection.entity;\n }\n\n if (selection.kind === 'ambiguous') {\n logger.error(formatAmbiguous('apps', selector.appName ?? '', selection.matches, (a) => a.reference));\n logger.dim('Re-run with --id <id> in place of the name to pick one.');\n process.exit(1);\n }\n\n if (selection.kind === 'conflict') {\n const { entity: app, name } = selection;\n logger.error(\n `App ${app.reference} is \"${app.name}\", not \"${name}\". The id and the name point at different apps, so nothing was done.`,\n );\n logger.dim(\n `To act on app ${app.reference}${selector.tenant ? ` in tenant \"${selector.tenant}\"` : ''}, drop the name.`,\n );\n if (!/\\s/.test(name)) {\n logger.dim(\n `If \"${name}\" is a tenant, select it and re-run with only the id: export FARSEER_TENANT=${name}`,\n );\n }\n process.exit(1);\n }\n\n logger.error(selector.id ? `App not found: id ${selector.id}` : `App not found: ${selector.appName}`);\n logger.dim('List apps with: farseer app list <tenant>');\n process.exit(1);\n}\n\n/**\n * Resolve an app for a CLI command to its full details, or exit with a clear\n * message. Wraps `resolveAppItemOrExit` + `getApp` so the commands that need\n * the whole `RemoteApp` (show, run) don't repeat the fetch.\n */\nexport async function resolveAppOrExit(\n api: FarseerService,\n selector: { appName?: string; id?: string; tenant?: string },\n): Promise<RemoteApp> {\n const item = await resolveAppItemOrExit(api, selector);\n const app = await orExit(api.getApp(item.reference), `Failed to load app details: ${item.name}`);\n if (!app) {\n logger.error(`Failed to load app details: ${item.name}`);\n process.exit(1);\n }\n return app;\n}\n\n// Credential injection/stripping for local development\n// Matches: const farseerClient = new farseer.FarseerClient();\n// and: const fClient = new farseer.FarseerClient();\n\ninterface CredentialConfig {\n basePath: string;\n tenantId: string;\n apiKey: string;\n}\n\n// Pattern to match empty FarseerClient() constructor (no /g flag to avoid lastIndex issues)\nconst EMPTY_CLIENT_PATTERNS = [\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/,\n];\n\n// Pattern to match FarseerClient with injected credentials (multiline, no /g flag)\nconst INJECTED_CLIENT_PATTERN =\n /const (farseerClient|fClient) = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/;\n\nexport function injectCredentials(code: string, credential: CredentialConfig): string {\n const clientConfig = `{\n basePath: '${credential.basePath}',\n headers: {\n 'X-TENANT-ID': '${credential.tenantId}',\n 'X-API-KEY': '${credential.apiKey}',\n }\n }`;\n\n let modified = code;\n\n // Pattern 1: const farseerClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const farseerClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n // Pattern 2: const fClient = new farseer.FarseerClient();\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\s*\\);/g,\n `const fClient = new farseer.FarseerClient(${clientConfig});`,\n );\n\n return modified;\n}\n\nexport function stripCredentials(code: string): string {\n // Replace injected credentials back to empty constructor\n let modified = code;\n\n // Match farseerClient with credentials\n modified = modified.replace(\n /const farseerClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const farseerClient = new farseer.FarseerClient();',\n );\n\n // Match fClient with credentials\n modified = modified.replace(\n /const fClient = new farseer\\.FarseerClient\\(\\{[\\s\\S]*?basePath:[\\s\\S]*?headers:[\\s\\S]*?'X-TENANT-ID':[\\s\\S]*?'X-API-KEY':[\\s\\S]*?\\}\\);/g,\n 'const fClient = new farseer.FarseerClient();',\n );\n\n return modified;\n}\n\nexport function hasInjectedCredentials(code: string): boolean {\n return INJECTED_CLIENT_PATTERN.test(code);\n}\n\nexport function hasEmptyFarseerClient(code: string): boolean {\n return EMPTY_CLIENT_PATTERNS.some((pattern) => pattern.test(code));\n}\n\n// Process all script files in a directory\nexport function injectCredentialsInDir(srcDir: string, credential: CredentialConfig): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = injectCredentials(content, credential);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\nexport function stripCredentialsInDir(srcDir: string): number {\n let count = 0;\n const files = getAllFiles(srcDir);\n\n for (const file of files) {\n const filePath = path.join(srcDir, file);\n const content = fs.readFileSync(filePath, 'utf-8');\n const modified = stripCredentials(content);\n\n if (modified !== content) {\n fs.writeFileSync(filePath, modified);\n count++;\n }\n }\n\n return count;\n}\n\n// Audit log helpers\nexport interface AuditLogEntry {\n operation: 'pulled' | 'pushed' | 'deleted';\n filePath: string;\n uploadTime?: string;\n uploaderEmail?: string;\n uploaderName?: string;\n}\n\n/**\n * Execute async operations with limited concurrency.\n * Processes items in chunks to avoid overwhelming the API.\n *\n * @param items Array of items to process\n * @param fetcher Async function to call for each item\n * @param concurrency Maximum number of concurrent requests (default: 15)\n * @returns Array of results in the same order as input items\n */\nexport async function fetchWithConcurrency<T, R>(\n items: T[],\n fetcher: (item: T, index: number) => Promise<R>,\n concurrency: number = 15,\n): Promise<R[]> {\n const results: R[] = [];\n\n for (let i = 0; i < items.length; i += concurrency) {\n const chunk = items.slice(i, i + concurrency);\n const chunkResults = await Promise.all(chunk.map((item, chunkIndex) => fetcher(item, i + chunkIndex)));\n results.push(...chunkResults);\n }\n\n return results;\n}\n\nexport function appendToAuditLog(tenant: string, entries: AuditLogEntry[]): void {\n if (entries.length === 0) {\n return;\n }\n\n const logPath = getAuditLogPath(tenant);\n const timestamp = new Date().toISOString();\n\n let logContent = '';\n for (const entry of entries) {\n const uploaderInfo = entry.uploaderName\n ? `${entry.uploaderName} (${entry.uploaderEmail})`\n : entry.uploaderEmail || 'Unknown';\n\n const uploadedAt = entry.uploadTime ? new Date(entry.uploadTime).toLocaleString() : 'Unknown';\n\n logContent += `${timestamp} | ${entry.operation} | ${entry.filePath} | Modified by: ${uploaderInfo} | Uploaded: ${uploadedAt}\\n`;\n }\n\n fs.appendFileSync(logPath, logContent, 'utf-8');\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,aAAwB;AACxB,WAAsB;AACtB,SAAoB;AACpB,2BAA4C;AAC5C,oBAAuB;AACvB,4BAAkC;AAGlC,0BAAkD;AAE3C,SAAS,cAAc,SAAkC;AAC5D,SAAO,OAAO,WAAW,KAAK,EAAE,OAAO,OAAO,EAAE,OAAO,KAAK;AAChE;AAQO,SAAS,aAAqB;AACjC,QAAM,OAAO,QAAQ,IAAI,kBAAkB,KAAK;AAChD,SA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,YAAY;AAEzC,MAAI,aAAa;AACjB,aAAW,SAAS,SAAS;AACzB,UAAM,eAAe,MAAM,eACrB,GAAG,MAAM,YAAY,KAAK,MAAM,aAAa,MAC7C,MAAM,iBAAiB;AAE7B,UAAM,aAAa,MAAM,aAAa,IAAI,KAAK,MAAM,UAAU,EAAE,eAAe,IAAI;AAEpF,kBAAc,GAAG,SAAS,MAAM,MAAM,SAAS,MAAM,MAAM,QAAQ,mBAAmB,YAAY,gBAAgB,UAAU;AAAA;AAAA,EAChI;AAEA,KAAG,eAAe,SAAS,YAAY,OAAO;AAClD;",
6
6
  "names": ["envCheckout"]
7
7
  }
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var variableValues_exports = {};
20
+ __export(variableValues_exports, {
21
+ normalizeDataType: () => normalizeDataType,
22
+ normalizeRollupType: () => normalizeRollupType,
23
+ writableVariable: () => writableVariable
24
+ });
25
+ module.exports = __toCommonJS(variableValues_exports);
26
+ const ROLLUP_TYPES = {
27
+ sum: "SUM",
28
+ average: "AVERAGE",
29
+ avg: "AVERAGE",
30
+ min: "MIN",
31
+ max: "MAX",
32
+ none: "NONE",
33
+ formula: "FORMULA",
34
+ closingstate: "CLOSING STATE",
35
+ "closing state": "CLOSING STATE",
36
+ "closing-state": "CLOSING STATE",
37
+ last: "CLOSING STATE",
38
+ beginningstate: "BEGINNING STATE",
39
+ "beginning state": "BEGINNING STATE",
40
+ "beginning-state": "BEGINNING STATE",
41
+ first: "BEGINNING STATE"
42
+ };
43
+ function normalizeRollupType(value) {
44
+ const normalized = ROLLUP_TYPES[value.trim().toLowerCase()];
45
+ if (!normalized)
46
+ throw new Error(
47
+ `Invalid rollupType "${value}". Valid types: ${[...new Set(Object.values(ROLLUP_TYPES))].join(", ")}`
48
+ );
49
+ return normalized;
50
+ }
51
+ function normalizeDataType(value) {
52
+ const normalized = value.trim().toUpperCase();
53
+ if (!["INTEGER", "DECIMAL"].includes(normalized))
54
+ throw new Error(`Invalid data type "${value}". Use Decimal or Integer.`);
55
+ return normalized;
56
+ }
57
+ function writableVariable(current = {}) {
58
+ return {
59
+ notes: current.notes ?? null,
60
+ tableGids: current.tableGids ?? [],
61
+ memberGids: current.memberGids ?? [],
62
+ rollupType: current.rollupType ?? "SUM",
63
+ dataType: current.dataType ?? "DECIMAL",
64
+ topDownMapping: current.topDownMapping ?? null,
65
+ measure: current.measure ?? false,
66
+ readonly: current.readonly ?? false,
67
+ calculateOnDemand: current.calculateOnDemand ?? false,
68
+ zConstraint: current.zConstraint ?? false,
69
+ optimizeCalculation: current.optimizeCalculation ?? true
70
+ };
71
+ }
72
+ // Annotate the CommonJS export names for ESM import in node:
73
+ 0 && (module.exports = {
74
+ normalizeDataType,
75
+ normalizeRollupType,
76
+ writableVariable
77
+ });
78
+ //# sourceMappingURL=variableValues.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/utils/variableValues.ts"],
4
+ "sourcesContent": ["// Shared by CLI commands and the existing MCP variable tools.\nconst ROLLUP_TYPES: Record<string, string> = {\n sum: 'SUM',\n average: 'AVERAGE',\n avg: 'AVERAGE',\n min: 'MIN',\n max: 'MAX',\n none: 'NONE',\n formula: 'FORMULA',\n closingstate: 'CLOSING STATE',\n 'closing state': 'CLOSING STATE',\n 'closing-state': 'CLOSING STATE',\n last: 'CLOSING STATE',\n beginningstate: 'BEGINNING STATE',\n 'beginning state': 'BEGINNING STATE',\n 'beginning-state': 'BEGINNING STATE',\n first: 'BEGINNING STATE',\n};\n\nexport function normalizeRollupType(value: string): string {\n const normalized = ROLLUP_TYPES[value.trim().toLowerCase()];\n if (!normalized)\n throw new Error(\n `Invalid rollupType \"${value}\". Valid types: ${[...new Set(Object.values(ROLLUP_TYPES))].join(', ')}`,\n );\n return normalized;\n}\n\nexport function normalizeDataType(value: string): string {\n const normalized = value.trim().toUpperCase();\n if (!['INTEGER', 'DECIMAL'].includes(normalized))\n throw new Error(`Invalid data type \"${value}\". Use Decimal or Integer.`);\n return normalized;\n}\n\n/** Entity updates require the complete variable component; omit read-only response fields. */\nexport function writableVariable(current: Record<string, any> = {}): Record<string, any> {\n return {\n notes: current.notes ?? null,\n tableGids: current.tableGids ?? [],\n memberGids: current.memberGids ?? [],\n rollupType: current.rollupType ?? 'SUM',\n dataType: current.dataType ?? 'DECIMAL',\n topDownMapping: current.topDownMapping ?? null,\n measure: current.measure ?? false,\n readonly: current.readonly ?? false,\n calculateOnDemand: current.calculateOnDemand ?? false,\n zConstraint: current.zConstraint ?? false,\n optimizeCalculation: current.optimizeCalculation ?? true,\n };\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,MAAM,eAAuC;AAAA,EACzC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,MAAM;AAAA,EACN,SAAS;AAAA,EACT,cAAc;AAAA,EACd,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,MAAM;AAAA,EACN,gBAAgB;AAAA,EAChB,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,OAAO;AACX;AAEO,SAAS,oBAAoB,OAAuB;AACvD,QAAM,aAAa,aAAa,MAAM,KAAK,EAAE,YAAY,CAAC;AAC1D,MAAI,CAAC;AACD,UAAM,IAAI;AAAA,MACN,uBAAuB,KAAK,mBAAmB,CAAC,GAAG,IAAI,IAAI,OAAO,OAAO,YAAY,CAAC,CAAC,EAAE,KAAK,IAAI,CAAC;AAAA,IACvG;AACJ,SAAO;AACX;AAEO,SAAS,kBAAkB,OAAuB;AACrD,QAAM,aAAa,MAAM,KAAK,EAAE,YAAY;AAC5C,MAAI,CAAC,CAAC,WAAW,SAAS,EAAE,SAAS,UAAU;AAC3C,UAAM,IAAI,MAAM,sBAAsB,KAAK,4BAA4B;AAC3E,SAAO;AACX;AAGO,SAAS,iBAAiB,UAA+B,CAAC,GAAwB;AACrF,SAAO;AAAA,IACH,OAAO,QAAQ,SAAS;AAAA,IACxB,WAAW,QAAQ,aAAa,CAAC;AAAA,IACjC,YAAY,QAAQ,cAAc,CAAC;AAAA,IACnC,YAAY,QAAQ,cAAc;AAAA,IAClC,UAAU,QAAQ,YAAY;AAAA,IAC9B,gBAAgB,QAAQ,kBAAkB;AAAA,IAC1C,SAAS,QAAQ,WAAW;AAAA,IAC5B,UAAU,QAAQ,YAAY;AAAA,IAC9B,mBAAmB,QAAQ,qBAAqB;AAAA,IAChD,aAAa,QAAQ,eAAe;AAAA,IACpC,qBAAqB,QAAQ,uBAAuB;AAAA,EACxD;AACJ;",
6
+ "names": []
7
+ }
@@ -0,0 +1,67 @@
1
+ # Pipeline authoring for your organisation
2
+
3
+ This page is for the tenant admin and IT team of a Farseer customer who want analysts to build data pipelines with an AI assistant. The assistant's own instructions are in the pipeline skill (`farseer pipeline guide`); this page covers what you decide and what you are agreeing to.
4
+
5
+ New repeatable pipelines use Simple Pipelines. Existing TypeScript apps remain supported through the app tools for inspection, execution, debugging and targeted fixes. A request to fix or extend an existing import does not authorize replacing or migrating it, changing its runner or schedule, or creating a duplicate pipeline. Migration requires an explicit migration request. Pipeline init, source sync and run refuse unrelated or unknown runner images; automatic image pinning applies only to jobs already using a Simple Pipelines runner.
6
+
7
+ ## What data leaves your tenant
8
+
9
+ The assistant works through the Farseer CLI on the analyst's laptop. Everything it reads reaches the model provider the analyst uses (Anthropic, OpenAI or another): run logs, dataset rows returned by `query`, cell values returned by the model tools, and the pipeline source. Query results are capped at 1,000 rows and 256 KiB per call, but a thousand rows of your data is still your data. Confirm that your agreement with the provider covers it before the first pipeline, and tell analysts which sources may be queried this way.
10
+
11
+ ## Two supported ways to work
12
+
13
+ **A sandbox tenant.** Farseer provisions a second tenant with a copy of your model. Analysts build and run pipelines there, with real sources, and the pipeline folder is copied to production once it is right (see "Moving to production"). Mistakes land in the sandbox. This is the recommended shape.
14
+
15
+ **Production, supervised.** With one tenant only, pipelines run against the real model from the first run. Every run has real effects: cells are overwritten at the coordinates a load names, `create_missing_members` adds members to your model, `undo_previous` deletes earlier imports. Datasets are versioned and can be restored; model loads cannot be reversed by the pipeline. Give the right to run remote jobs only to analysts working with a Farseer consultant, and ask the assistant to state every effect before it runs.
16
+
17
+ Before it reads any source, the engine checks a pipeline's shape (valid YAML, scripts that compile, dependencies that resolve, no credentials pasted into YAML, no SQL files) and checks it against your model: the variables, dimension tables and fixed members its loads name, and the Files folders its exports write to. A mismatch stops the run before any data moves. The check is not a security boundary: pipeline code runs with the job's rights.
18
+
19
+ ## Before the first pipeline
20
+
21
+ | Step | Who | How |
22
+ |---|---|---|
23
+ | Install | analyst or IT | Node 20 or newer, then `npm install -g farseer-cli`. The query engine is a native module with builds for Mac, Windows and Linux; the laptop must reach npm and the signed storage links Farseer returns. |
24
+ | Connect the assistant | analyst | Add `farseer mcp-server` to the AI client with `FARSEER_TENANT=<your tenant>`. |
25
+ | Sign in | analyst | `farseer login` (the browser login) or an API key. An API key acts with the permissions of the user it belongs to. Either one needs the permissions below. |
26
+ | Secrets | admin | A source that needs a key or password gets it from a secret-typed argument on the job; the YAML names it as `{{ pipeline_args.NAME }}`. The assistant adds the argument. The value is the argument's default value: either you type it into the web app, which keeps it out of the AI conversation, or the assistant sets it for you. Reads and run logs show it masked. `check` lists any argument the pipeline uses that the job lacks. |
27
+
28
+ ### Permissions the analyst needs
29
+
30
+ | To | Needs |
31
+ |---|---|
32
+ | Create a pipeline and its job (`init`) | the remote jobs feature (FEATURE.REMOTE_JOBS, which makes the Apps folder visible), create remote jobs in the tenant folder, write files |
33
+ | Run, list runs, inspect | run remote jobs, read run history |
34
+ | Read what a load imported (`inspect-import`) | the import feature (FEATURE.IMPORT) and FEATURE.SEE_ALL_IMPORT_JOBS, because the runner creates the import, not the analyst |
35
+ | Read datasets and versions (`query`, `versions`) | run remote jobs |
36
+ | Restore an earlier dataset version | update remote jobs |
37
+ | Create or delete datasets | super user |
38
+
39
+ These are the remote job, file and feature permissions you already manage in the web app. No new permission class. Super user does not stand in for the feature permissions: grant them explicitly. The job itself runs as the tenant's runner identity, which needs the import feature (FEATURE.IMPORT) for a load to commit.
40
+
41
+ The permissions alone are not enough for an analyst who is not a super user: Farseer shows such a user only the folders and model items shared with them. Give the analyst access to the `Files` folder (where `init` creates the pipeline's folder) and to the dimension tables and variables the pipeline loads, or make them a tenant admin. Without that access, `init` fails with `Folder not found: Files` and reading the model's members fails, even though every permission above is granted.
42
+
43
+ ## Keeping things in step
44
+
45
+ The CLI authors for exactly one engine version: the one inside the runner image it was released with. When Farseer releases a new runner image it also releases a CLI, and for a while the backend accepts both. `check` reports a newer CLI as available; below the minimum, pipeline commands stop with "update the CLI". IT should expect to update `farseer-cli` on analysts' laptops a few times a year.
46
+
47
+ A job on an older image is moved to the CLI's image by the next `run` the CLI submits; a run it refuses leaves the job alone. That includes pipelines Farseer consultants built for you earlier: running one from your own CLI may upgrade its engine, and if the newer engine rejects something the assistant will say so and offer to fix it. If you would rather a consultant did that, ask before running an inherited pipeline.
48
+
49
+ ## Moving to production
50
+
51
+ There is no promote button. A pipeline is a folder of files, and it moves the way files do.
52
+
53
+ 1. Copy only `files/<name>/` from the sandbox tenant's folder into the production tenant's folder. Never copy the hidden `.pipelines/` or `.pipeline-runs/` folders; the CLI refuses a profile that belongs to another tenant and says what to delete.
54
+ 2. Point the assistant at production and run `init name=<name>`. It uploads the folder, creates the job and writes a fresh profile.
55
+ 3. Set the secret arguments again on the production job. Secrets never travel between tenants.
56
+ 4. Make sure the variables, members and dimension tables the pipeline loads into exist on the production model, and that the source is production data, not the sandbox copy.
57
+ 5. Run once, inspect, then add a schedule in the web app.
58
+
59
+ **Editing a scheduled pipeline.** You can work on a pipeline that runs on a schedule. Uploading changes to it is the same as releasing them: the next scheduled run uses whatever was uploaded, so test with a run first, or pause the schedule for larger changes. The CLI remembers the schedule it saw at setup, and its check fails, with the command to restore it, if the schedule has disappeared. The assistant cannot start a run while a scheduled run of the same pipeline is still going.
60
+
61
+ ## When something goes wrong
62
+
63
+ - A failed run leaves the previous dataset version current. `versions` shows history; `restore` puts an earlier version back and refuses if someone else changed things in between.
64
+ - Restore does not reverse model imports. `inspect-import` shows what an import did; repairing cells is a model operation, not a dataset one.
65
+ - A run whose jobrunner lost it, for example after a restart, is closed as an error the next time that jobrunner is asked what it is running, which happens whenever the job is opened in the web app or checked from the CLI. A run that stays stuck after that stays open in the run history until someone confirms it is over; ask Farseer rather than retrying.
66
+ - If the assistant reports a submission as unconfirmed, the analyst runs `farseer pipeline recover` in a terminal. It clears the record when the job's history shows no run was accepted, and otherwise lists the runs to choose from with `--uuid`.
67
+ - `check` is the first thing to run when anything looks wrong. Every line names who can fix it.