farseer-cli 1.14.1 → 1.14.2

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 (63) hide show
  1. package/dist/commands/config.js +4 -3
  2. package/dist/commands/config.js.map +2 -2
  3. package/dist/commands/install.js +5 -0
  4. package/dist/commands/install.js.map +2 -2
  5. package/dist/commands/login.js +2 -2
  6. package/dist/commands/login.js.map +2 -2
  7. package/dist/commands/pull.js +2 -1
  8. package/dist/commands/pull.js.map +2 -2
  9. package/dist/commands/run.js +9 -0
  10. package/dist/commands/run.js.map +2 -2
  11. package/dist/index.js +7 -2
  12. package/dist/index.js.map +2 -2
  13. package/dist/mcp/tools/appTools.js.map +2 -2
  14. package/dist/mcp/tools/authTools.js +5 -3
  15. package/dist/mcp/tools/authTools.js.map +2 -2
  16. package/dist/mcp/tools/cellTools.js +3 -2
  17. package/dist/mcp/tools/cellTools.js.map +2 -2
  18. package/dist/mcp/tools/dashboardTools.js +23 -18
  19. package/dist/mcp/tools/dashboardTools.js.map +2 -2
  20. package/dist/mcp/tools/dataTools.js +14 -12
  21. package/dist/mcp/tools/dataTools.js.map +2 -2
  22. package/dist/mcp/tools/folderTools.js +5 -4
  23. package/dist/mcp/tools/folderTools.js.map +2 -2
  24. package/dist/mcp/tools/modelTools.js +27 -17
  25. package/dist/mcp/tools/modelTools.js.map +2 -2
  26. package/dist/mcp/tools/pipelineContract.js +5 -2
  27. package/dist/mcp/tools/pipelineContract.js.map +2 -2
  28. package/dist/mcp/tools/runTools.js +8 -3
  29. package/dist/mcp/tools/runTools.js.map +2 -2
  30. package/dist/mcp/tools/sheetTools.js +21 -17
  31. package/dist/mcp/tools/sheetTools.js.map +2 -2
  32. package/dist/mcp/tools/syncTools.js +11 -5
  33. package/dist/mcp/tools/syncTools.js.map +2 -2
  34. package/dist/mcp/utils/registerTool.js +32 -0
  35. package/dist/mcp/utils/registerTool.js.map +7 -0
  36. package/dist/pipeline/generated-reference.json +3 -3
  37. package/dist/pipeline/operations.js +4 -1
  38. package/dist/pipeline/operations.js.map +2 -2
  39. package/dist/pipeline/query.js +58 -40
  40. package/dist/pipeline/query.js.map +2 -2
  41. package/dist/pipeline/queryDownloads.js +72 -0
  42. package/dist/pipeline/queryDownloads.js.map +7 -0
  43. package/dist/pipeline/queryWorker.js +8 -31
  44. package/dist/pipeline/queryWorker.js.map +2 -2
  45. package/dist/pipeline/readiness.js +15 -8
  46. package/dist/pipeline/readiness.js.map +2 -2
  47. package/dist/pipeline/reference.js +2 -1
  48. package/dist/pipeline/reference.js.map +2 -2
  49. package/dist/pipeline/runtime.js +4 -3
  50. package/dist/pipeline/runtime.js.map +2 -2
  51. package/dist/pipeline/service.js +110 -50
  52. package/dist/pipeline/service.js.map +2 -2
  53. package/dist/services/appSyncService.js.map +1 -1
  54. package/dist/services/configService.js +11 -4
  55. package/dist/services/configService.js.map +2 -2
  56. package/dist/services/farseerService.js +23 -0
  57. package/dist/services/farseerService.js.map +2 -2
  58. package/dist/services/modelExport.js.map +1 -1
  59. package/dist/utils/agentSandbox.js +35 -0
  60. package/dist/utils/agentSandbox.js.map +7 -0
  61. package/docs/pipeline-client-guide.md +2 -2
  62. package/package.json +1 -1
  63. package/skills/pipeline-authoring/SKILL.md +4 -4
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/services/appSyncService.ts"],
4
- "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n RemoteApp,\n AppArgument,\n AppArgumentDataType,\n AppUpdateChanges,\n ComputeChoice,\n formatCompute,\n parseComputeChoice,\n} from './apps';\nimport type { FarseerService } from './farseerService';\nimport { getTenantAppsDir, ensureDirectoryExists, fetchWithConcurrency } from '../utils/helpers';\nimport { logger } from '../utils/logger';\nimport { formatClientError } from '../utils/errorFormatter';\n\n// Local app config format (stored in apps/*.json) \u2014 mirrors AppArgument so\n// pull/push round-trips don't drop any axis.\n//\n// The run settings below are managed by key presence, not by value: a file that\n// has the key declares that setting and push enforces it, a file without the key\n// leaves whatever the tenant has. That keeps a config written before these\n// existed from clearing a schedule the first time it is pushed.\n//\n// Two settings are deliberately not in the file, and are set with `app configure`\n// or `farseer_configure_app` instead:\n//\n// - the runner, because the backend assigns one to an unassigned scheduled job\n// by itself and stores it. A file cannot tell that assignment from a choice:\n// pull would write the scheduler's pick in as a pin that travels with the\n// file to other tenants, and push would clear it only for the scheduler to\n// assign it again, so the app never reads as in sync.\n// - predefined actions, because the backend returns their values readable even\n// for arguments marked secret. Writing them to a file puts secrets in the\n// workspace and in git; leaving them out of the file leaves them untouched on\n// the tenant, since an update carries the current actions forward.\nexport interface LocalAppConfig {\n name: string;\n description: string;\n entrypoint: string | null; // Script filename (e.g., \"index.ts\")\n arguments: {\n name: string;\n // `dataType` defaults to 'string' on legacy configs that pre-date typed\n // parameters. Without round-tripping the full axes (`dataType`,\n // `fixed`, `options`), a pull \u2192 push cycle silently demoted a boolean /\n // dropdown / locked arg back to a plain string variable.\n dataType?: AppArgumentDataType;\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n }[];\n schedule?: string | null;\n runnerImage?: string | null;\n compute?: ComputeChoice;\n _remote?: {\n id: number;\n reference: string;\n };\n}\n\nexport interface AppSyncResult {\n created: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n}\n\nexport interface AppSyncStatus {\n newLocal: string[]; // Local apps not on remote\n newRemote: string[]; // Remote apps not locally\n modified: string[]; // Apps that differ\n synced: string[]; // Apps in sync\n}\n\n/**\n * Sanitize Croatian diacritics and other special characters to ASCII equivalents\n */\nfunction sanitizeDiacritics(text: string): string {\n const diacriticMap: Record<string, string> = {\n // Croatian\n \u010D: 'c',\n \u010C: 'C',\n \u0107: 'c',\n \u0106: 'C',\n \u0161: 's',\n \u0160: 'S',\n \u017E: 'z',\n \u017D: 'Z',\n \u0111: 'd',\n \u0110: 'D',\n // German/Other common\n \u00E4: 'a',\n \u00C4: 'A',\n \u00F6: 'o',\n \u00D6: 'O',\n \u00FC: 'u',\n \u00DC: 'U',\n \u00DF: 'ss',\n // Polish\n \u0105: 'a',\n \u0104: 'A',\n \u0119: 'e',\n \u0118: 'E',\n \u0142: 'l',\n \u0141: 'L',\n \u0144: 'n',\n \u0143: 'N',\n \u00F3: 'o',\n \u00D3: 'O',\n \u015B: 's',\n \u015A: 'S',\n \u017A: 'z',\n \u0179: 'Z',\n \u017C: 'z',\n \u017B: 'Z',\n // French/Spanish\n \u00E0: 'a',\n \u00E1: 'a',\n \u00E2: 'a',\n \u00E8: 'e',\n \u00E9: 'e',\n \u00EA: 'e',\n \u00EB: 'e',\n \u00EC: 'i',\n \u00ED: 'i',\n \u00EE: 'i',\n \u00EF: 'i',\n \u00F2: 'o',\n \u00F4: 'o',\n \u00F9: 'u',\n \u00FA: 'u',\n \u00FB: 'u',\n \u00F1: 'n',\n \u00D1: 'N',\n \u00E7: 'c',\n \u00C7: 'C',\n };\n\n return text\n .split('')\n .map((char) => diacriticMap[char] || char)\n .join('');\n}\n\n/**\n * Migrate legacy `type: 'variable' | 'constant' | 'boolean' | 'dropdown'` on\n * pre-PR pulls to the orthogonal-axes shape used by `localToUpdate` and\n * `areAppsEqual`. Idempotent \u2014 leaves new-shape entries untouched.\n *\n * Without this, a push immediately after upgrade silently demoted locked\n * args (`type: 'constant'` \u2192 no `fixed`) because the new code ignores the\n * legacy `type` key when building the wire payload. `areAppsEqual` flagged\n * the diff but didn't block, so the silent demote slipped through.\n */\nfunction migrateLegacyArguments(config: { arguments?: unknown[] } & Record<string, unknown>): Record<string, unknown> {\n if (!Array.isArray(config.arguments)) return config as Record<string, unknown>;\n config.arguments = config.arguments.map((raw) => {\n if (raw === null || typeof raw !== 'object') return raw;\n const a = raw as Record<string, unknown>;\n if (a.dataType !== undefined || a.type === undefined) return a;\n const legacyType = a.type;\n const rest: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(a)) {\n if (k !== 'type') rest[k] = v;\n }\n switch (legacyType) {\n case 'constant':\n return { ...rest, dataType: 'string', fixed: true };\n case 'boolean':\n return { ...rest, dataType: 'boolean' };\n case 'dropdown':\n case 'variable':\n default:\n return { ...rest, dataType: 'string' };\n }\n });\n return config as Record<string, unknown>;\n}\n\n// The run settings a config file governs by key presence. A file written before\n// they existed has none of them, which `areAppsEqual` reads as \"in sync\" \u2014 so\n// pull would never add them and the app could never adopt the feature. Rewriting\n// such a file once costs nothing: the values it gains are the tenant's own.\nconst RUN_SETTING_KEYS = ['schedule', 'runnerImage', 'compute'] as const;\n\n// Written by builds that still synced them. Pull removes them, so a secret\n// action value or a scheduler-assigned runner does not stay behind in the file.\nconst RETIRED_KEYS = ['runner', 'predefinedActions'] as const;\n\n/** A file pull has to rewrite even when every value it holds is current. */\nfunction fileNeedsRewrite(local: LocalAppConfig): boolean {\n return !RUN_SETTING_KEYS.every((key) => key in local) || RETIRED_KEYS.some((key) => key in local);\n}\n\n/**\n * Service for syncing app configurations between local JSON files and remote Farseer instance\n */\nexport class AppSyncService {\n private api: FarseerService;\n private appsDir: string;\n\n constructor(tenant: string, api: FarseerService) {\n this.api = api;\n this.appsDir = getTenantAppsDir(tenant);\n }\n\n /**\n * Get filename for an app (keep original name, just sanitize for filesystem)\n */\n private getAppFilename(name: string): string {\n return (\n sanitizeDiacritics(name)\n .replace(/[<>:\"/\\\\|?*]/g, '') // Remove invalid filename characters\n .trim() + '.json'\n );\n }\n\n /**\n * Names of locally-tracked apps the next `pull` would delete because\n * remote no longer has them. Uses only `listApps` (no per-app fetch),\n * so pull can preview deletions for the destructive-action prompt\n * without paying for getStatus's full per-app round-trip.\n *\n * Mirrors the deletion gate in `pull()` (`local._remote && !remoteApps.has(key)`):\n * apps the user never pulled (`_remote` undefined) are kept untouched\n * by pull, so they don't belong in this list.\n */\n async getRemoteDeletions(): Promise<string[]> {\n const localApps = this.loadLocalApps();\n const remoteAppList = await this.api.listApps();\n const remoteNames = new Set(remoteAppList.map((a) => a.name.toLowerCase()));\n const deleted: string[] = [];\n for (const [key, local] of localApps) {\n if (local._remote && !remoteNames.has(key)) {\n deleted.push(local.name);\n }\n }\n return deleted;\n }\n\n /**\n * Load all local app configs\n */\n loadLocalApps(): Map<string, LocalAppConfig> {\n const apps = new Map<string, LocalAppConfig>();\n\n if (!fs.existsSync(this.appsDir)) {\n return apps;\n }\n\n const files = fs.readdirSync(this.appsDir).filter((f) => f.endsWith('.json'));\n\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(this.appsDir, file), 'utf-8');\n const config = migrateLegacyArguments(JSON.parse(content)) as LocalAppConfig;\n apps.set(config.name.toLowerCase(), config);\n } catch {\n // Skip invalid files\n }\n }\n\n return apps;\n }\n\n /**\n * Save a local app config\n */\n saveLocalApp(config: LocalAppConfig): void {\n ensureDirectoryExists(this.appsDir);\n const filename = this.getAppFilename(config.name);\n const filePath = path.join(this.appsDir, filename);\n fs.writeFileSync(filePath, JSON.stringify(config, null, 2), 'utf-8');\n }\n\n /**\n * Delete a local app config\n */\n deleteLocalApp(name: string): boolean {\n const filename = this.getAppFilename(name);\n const filePath = path.join(this.appsDir, filename);\n\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n return true;\n }\n return false;\n }\n\n /**\n * Convert remote app to local config format\n */\n private remoteToLocal(remote: RemoteApp, reference: string): LocalAppConfig {\n const scriptFiles = remote.scriptFiles ?? [];\n const mainScript = scriptFiles.find((s) => s.id === remote.mainScriptFileId);\n\n // \"No default\" canonical shape locally is `defaultValue: ''` (empty\n // string), NOT an omitted key. The OpenAPI schema makes the field\n // optional, so the backend can emit either; if we passed `undefined`\n // through verbatim, a user who added `defaultValue: ''` locally\n // would see `areAppsEqual` say \"match\" (both normalise to '') but\n // the next pull would strip the key again \u2014 the on-disk JSON would\n // oscillate forever and never reach a steady state. type is treated\n // the same way ('variable' is the implicit default), secret only\n // appears when explicitly true on the backend (boolean is a clear\n // tri-state: true/false/unset, and \"unset\" reads as false anyway).\n return {\n name: remote.name,\n description: remote.description || '',\n entrypoint: mainScript?.name || null,\n arguments: remote.expectedArguments.map((a) => {\n // Pin a steady-state shape so two pulls back-to-back don't\n // oscillate. `defaultValue` is normalized to '' when omitted \u2014\n // a user-edited `defaultValue: ''` locally must compare equal\n // to a remote that omits the field. `dataType` defaults to\n // 'string' (the implicit pre-fix shape). All other axes\n // (`fixed`, `options`, `secret`) are only emitted when the\n // remote populated them, to keep the JSON minimal.\n const arg: LocalAppConfig['arguments'][number] = {\n name: a.name,\n defaultValue: a.defaultValue ?? '',\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n }),\n // Written on every pull, including as null / 'local' / [], so the\n // file says what the tenant holds rather than staying silent and\n // reading as \"not managed\" on the next push.\n schedule: remote.schedule || null,\n runnerImage: remote.runnerImage || null,\n compute: formatCompute(remote.compute),\n _remote: {\n id: remote.id,\n reference: reference,\n },\n };\n }\n\n /**\n * Check if local and remote app configs are equivalent\n */\n private areAppsEqual(local: LocalAppConfig, remote: RemoteApp): boolean {\n // Compare name\n if (local.name !== remote.name) return false;\n\n // Compare description\n if ((local.description || '') !== (remote.description || '')) return false;\n\n // Compare entrypoint\n const remoteScriptFiles = remote.scriptFiles ?? [];\n const remoteEntrypoint = remoteScriptFiles.find((s) => s.id === remote.mainScriptFileId)?.name || null;\n if (local.entrypoint !== remoteEntrypoint) return false;\n\n // Compare arguments. Order matters here: backend renders args in the\n // saved order in the UI, so we treat reordering as a real change.\n // Missing `dataType` defaults to 'string' (the implicit pre-fix value);\n // missing scalar defaults are normalized so '' vs undefined doesn't\n // show up as a spurious diff. All four axes (dataType, fixed, options,\n // defaultValue, secret) are compared so a pull\u2192push round-trip\n // detects changes on any of them.\n if (local.arguments.length !== remote.expectedArguments.length) return false;\n for (let i = 0; i < local.arguments.length; i++) {\n const l = local.arguments[i];\n const r = remote.expectedArguments[i];\n if (l.name !== r.name) return false;\n if ((l.dataType ?? 'string') !== (r.dataType ?? 'string')) return false;\n if (Boolean(l.fixed) !== Boolean(r.fixed)) return false;\n if (JSON.stringify(l.options ?? []) !== JSON.stringify(r.options ?? [])) return false;\n if ((l.defaultValue ?? '') !== (r.defaultValue ?? '')) return false;\n if (Boolean(l.secret) !== Boolean(r.secret)) return false;\n }\n\n // Only what the file declares. A config written before these fields\n // existed omits them, and comparing an absent key against a populated\n // tenant would report that app modified forever.\n if ('schedule' in local && (local.schedule || null) !== (remote.schedule || null)) return false;\n if ('runnerImage' in local && (local.runnerImage || null) !== (remote.runnerImage || null)) return false;\n // Compare on what push would actually send. A local `compute` push cannot\n // express \u2014 `null`, or a string parseComputeChoice rejects \u2014 is drift no\n // push could ever close, so counting it leaves the app modified forever.\n const declaredCompute = 'compute' in local && local.compute ? parseComputeChoice(local.compute) : null;\n if (declaredCompute && formatCompute(declaredCompute) !== formatCompute(remote.compute)) return false;\n\n return true;\n }\n\n /**\n * Pull apps from remote and save locally\n */\n async pull(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n logger.dim(`Fetching ${remoteAppList.length} apps in parallel...`);\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item, index) => {\n const app = await this.api.getApp(item.reference);\n // Show progress every 10 apps\n if ((index + 1) % 10 === 0 || index === remoteAppList.length - 1) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write(`\\r Progress: ${index + 1}/${remoteAppList.length} apps`);\n }\n return { app, reference: item.reference };\n },\n 15,\n );\n // Clear progress line\n if (remoteAppList.length > 0) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Process remote apps\n for (const [key, { app, reference }] of remoteApps) {\n const localConfig = this.remoteToLocal(app, reference);\n const existingLocal = localApps.get(key);\n\n if (!existingLocal) {\n // New app from remote\n this.saveLocalApp(localConfig);\n result.created.push(app.name);\n } else if (!this.areAppsEqual(existingLocal, app) || fileNeedsRewrite(existingLocal)) {\n // App changed on remote, or the file's shape is out of date: it\n // predates the run settings and would never gain them \u2014\n // areAppsEqual ignores keys the file omits \u2014 or it still carries\n // one that is no longer synced.\n this.saveLocalApp(localConfig);\n result.updated.push(app.name);\n } else {\n result.unchanged.push(app.name);\n }\n }\n\n // Check for apps deleted on remote\n for (const [key, local] of localApps) {\n if (!remoteApps.has(key) && local._remote) {\n // App was synced before but now deleted on remote\n this.deleteLocalApp(local.name);\n result.deleted.push(local.name);\n }\n }\n\n return result;\n }\n\n /**\n * Push local apps to remote\n */\n async push(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Get available scripts for ID lookup\n // Build maps for both path-based and filename-based lookup (backward compatibility)\n const availableScripts = await this.api.getScriptFiles();\n const scriptIdByPath = new Map<string, string>();\n const scriptIdByName = new Map<string, string>();\n\n for (const s of availableScripts) {\n // s.name now contains full path (e.g., \"Scripts/test.ts\")\n const pathKey = s.name.toLowerCase();\n const filenameKey = s.name.split('/').pop()?.toLowerCase() || pathKey;\n\n scriptIdByPath.set(pathKey, s.id);\n // For filename lookup, only set if not already set (first match wins for ambiguous names)\n if (!scriptIdByName.has(filenameKey)) {\n scriptIdByName.set(filenameKey, s.id);\n }\n }\n\n // Helper to find script ID by path or filename\n const findScriptId = (scriptRef: string): string | undefined => {\n const key = scriptRef.toLowerCase();\n // Try exact path match first\n const byPath = scriptIdByPath.get(key);\n if (byPath) return byPath;\n // Try with Scripts/ prefix\n const withPrefix = scriptIdByPath.get(`scripts/${key}`);\n if (withPrefix) return withPrefix;\n // Fall back to filename match\n return scriptIdByName.get(key.split('/').pop() || key);\n };\n\n // Process local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n // New local app - create on remote\n try {\n const created = await this.api.createApp(local.name);\n\n // Update with config (API requires name and description)\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n await this.api.updateApp(created.id.toString(), update, created);\n\n // Update local with remote ID\n local._remote = {\n id: created.id,\n reference: created.id.toString(),\n };\n this.saveLocalApp(local);\n\n result.created.push(local.name);\n } catch (error) {\n logger.error(`Failed to create app ${local.name}: ${await formatClientError(error)}`);\n }\n } else if (!this.areAppsEqual(local, remote.app)) {\n // App differs - update remote\n try {\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n\n await this.api.updateApp(remote.reference, update, remote.app);\n result.updated.push(local.name);\n } catch (error) {\n logger.error(`Failed to update app ${local.name}: ${await formatClientError(error)}`);\n }\n } else {\n result.unchanged.push(local.name);\n }\n }\n\n // Note: We don't auto-delete remote apps when deleted locally\n // User must use \"farseer app delete\" explicitly\n\n return result;\n }\n\n /**\n * Build update payload for API\n */\n private buildUpdatePayload(\n local: LocalAppConfig,\n findScriptId: (scriptRef: string) => string | undefined,\n ): AppUpdateChanges {\n const update: AppUpdateChanges = {};\n\n // Arguments \u2014 preserve all axes. `dataType` defaults to 'string' for\n // older app json files that pre-date typed parameters. Always sent\n // (even when empty): the local config is authoritative for the sync\n // path, so an app whose args were cleared locally must push that\n // emptiness through, otherwise `mergeAppUpdate` would keep the remote\n // args and `status` would report the app modified forever.\n update.expectedArguments = local.arguments.map((a) => {\n const arg: AppArgument = {\n name: a.name,\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.defaultValue !== undefined) arg.defaultValue = a.defaultValue;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n });\n\n // Entrypoint - lookup by path or filename\n if (local.entrypoint) {\n const entrypointId = findScriptId(local.entrypoint);\n if (entrypointId) {\n update.mainScriptFileId = entrypointId;\n }\n }\n\n // Key presence is the contract: a declared setting is enforced, an\n // absent one is left to whatever the tenant already holds.\n if ('schedule' in local) {\n update.schedule = local.schedule || null;\n }\n if ('runnerImage' in local) {\n update.runnerImage = local.runnerImage || null;\n }\n if ('compute' in local && local.compute) {\n const compute = parseComputeChoice(local.compute);\n if (compute) {\n update.compute = compute;\n } else {\n logger.warning(\n `Ignoring unknown compute \"${local.compute}\" for app ${local.name}: expected local, batch or batch:<size>.`,\n );\n }\n }\n\n return update;\n }\n\n /**\n * Get sync status without making changes\n */\n async getStatus(): Promise<AppSyncStatus> {\n const status: AppSyncStatus = {\n newLocal: [],\n newRemote: [],\n modified: [],\n synced: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Check local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n status.newLocal.push(local.name);\n } else if (!this.areAppsEqual(local, remote.app)) {\n status.modified.push(local.name);\n } else {\n status.synced.push(local.name);\n }\n }\n\n // Check for new remote apps\n for (const [key, { app }] of remoteApps) {\n if (!localApps.has(key)) {\n status.newRemote.push(app.name);\n }\n }\n\n return status;\n }\n}\n"],
4
+ "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n RemoteApp,\n AppArgument,\n AppArgumentDataType,\n AppUpdateChanges,\n ComputeChoice,\n formatCompute,\n parseComputeChoice,\n} from './apps';\nimport type { FarseerService } from './farseerService';\nimport { getTenantAppsDir, ensureDirectoryExists, fetchWithConcurrency } from '../utils/helpers';\nimport { logger } from '../utils/logger';\nimport { formatClientError } from '../utils/errorFormatter';\n\n// Local app config format (stored in apps/*.json) \u2014 mirrors AppArgument so\n// pull/push round-trips don't drop any axis.\n//\n// The run settings below are managed by key presence, not by value: a file that\n// has the key declares that setting and push enforces it, a file without the key\n// leaves whatever the tenant has. That keeps a config written before these\n// existed from clearing a schedule the first time it is pushed.\n//\n// Two settings are deliberately not in the file, and are set with `app configure`\n// or `farseer_configure_app` instead:\n//\n// - the runner, because the backend assigns one to an unassigned scheduled job\n// by itself and stores it. A file cannot tell that assignment from a choice:\n// pull would write the scheduler's pick in as a pin that travels with the\n// file to other tenants, and push would clear it only for the scheduler to\n// assign it again, so the app never reads as in sync.\n// - predefined actions, because the backend returns their values readable even\n// for arguments marked secret. Writing them to a file puts secrets in the\n// workspace and in git; leaving them out of the file leaves them untouched on\n// the tenant, since an update carries the current actions forward.\nexport interface LocalAppConfig {\n name: string;\n description: string;\n entrypoint: string | null; // Script filename (e.g., \"index.ts\")\n arguments: {\n name: string;\n // `dataType` defaults to 'string' on legacy configs that pre-date typed\n // parameters. Without round-tripping the full axes (`dataType`,\n // `fixed`, `options`), a pull \u2192 push cycle silently demoted a boolean /\n // dropdown / locked arg back to a plain string variable.\n dataType?: AppArgumentDataType;\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n }[];\n schedule?: string | null;\n runnerImage?: string | null;\n compute?: ComputeChoice;\n _remote?: {\n id: number;\n reference: string;\n };\n}\n\nexport interface AppSyncResult {\n created: string[];\n updated: string[];\n deleted: string[];\n unchanged: string[];\n}\n\nexport interface AppSyncStatus {\n newLocal: string[]; // Local apps not on remote\n newRemote: string[]; // Remote apps not locally\n modified: string[]; // Apps that differ\n synced: string[]; // Apps in sync\n}\n\n/**\n * Sanitize Croatian diacritics and other special characters to ASCII equivalents\n */\nfunction sanitizeDiacritics(text: string): string {\n const diacriticMap: Record<string, string> = {\n // Croatian\n \u010D: 'c',\n \u010C: 'C',\n \u0107: 'c',\n \u0106: 'C',\n \u0161: 's',\n \u0160: 'S',\n \u017E: 'z',\n \u017D: 'Z',\n \u0111: 'd',\n \u0110: 'D',\n // German/Other common\n \u00E4: 'a',\n \u00C4: 'A',\n \u00F6: 'o',\n \u00D6: 'O',\n \u00FC: 'u',\n \u00DC: 'U',\n \u00DF: 'ss',\n // Polish\n \u0105: 'a',\n \u0104: 'A',\n \u0119: 'e',\n \u0118: 'E',\n \u0142: 'l',\n \u0141: 'L',\n \u0144: 'n',\n \u0143: 'N',\n \u00F3: 'o',\n \u00D3: 'O',\n \u015B: 's',\n \u015A: 'S',\n \u017A: 'z',\n \u0179: 'Z',\n \u017C: 'z',\n \u017B: 'Z',\n // French/Spanish\n \u00E0: 'a',\n \u00E1: 'a',\n \u00E2: 'a',\n \u00E8: 'e',\n \u00E9: 'e',\n \u00EA: 'e',\n \u00EB: 'e',\n \u00EC: 'i',\n \u00ED: 'i',\n \u00EE: 'i',\n \u00EF: 'i',\n \u00F2: 'o',\n \u00F4: 'o',\n \u00F9: 'u',\n \u00FA: 'u',\n \u00FB: 'u',\n \u00F1: 'n',\n \u00D1: 'N',\n \u00E7: 'c',\n \u00C7: 'C',\n };\n\n return text\n .split('')\n .map((char) => diacriticMap[char] || char)\n .join('');\n}\n\n/**\n * Migrate legacy `type: 'variable' | 'constant' | 'boolean' | 'dropdown'` on\n * pre-PR pulls to the orthogonal-axes shape used by `localToUpdate` and\n * `areAppsEqual`. Idempotent \u2014 leaves new-shape entries untouched.\n *\n * Without this, a push immediately after upgrade silently demoted locked\n * args (`type: 'constant'` \u2192 no `fixed`) because the new code ignores the\n * legacy `type` key when building the wire payload. `areAppsEqual` flagged\n * the diff but didn't block, so the silent demote slipped through.\n */\nfunction migrateLegacyArguments(config: { arguments?: unknown[] } & Record<string, unknown>): Record<string, unknown> {\n if (!Array.isArray(config.arguments)) return config as Record<string, unknown>;\n config.arguments = config.arguments.map((raw) => {\n if (raw === null || typeof raw !== 'object') return raw;\n const a = raw as Record<string, unknown>;\n if (a.dataType !== undefined || a.type === undefined) return a;\n const legacyType = a.type;\n const rest: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(a)) {\n if (k !== 'type') rest[k] = v;\n }\n switch (legacyType) {\n case 'constant':\n return { ...rest, dataType: 'string', fixed: true };\n case 'boolean':\n return { ...rest, dataType: 'boolean' };\n case 'dropdown':\n case 'variable':\n default:\n return { ...rest, dataType: 'string' };\n }\n });\n return config as Record<string, unknown>;\n}\n\n// The run settings a config file governs by key presence. A file written before\n// they existed has none of them, which `areAppsEqual` reads as \"in sync\" \u2014 so\n// pull would never add them and the app could never adopt the feature. Rewriting\n// such a file once costs nothing: the values it gains are the tenant's own.\nconst RUN_SETTING_KEYS = ['schedule', 'runnerImage', 'compute'] as const;\n\n// Written by builds that still synced them. Pull removes them, so a secret\n// action value or a scheduler-assigned runner does not stay behind in the file.\nconst RETIRED_KEYS = ['runner', 'predefinedActions'] as const;\n\n/** A file pull has to rewrite even when every value it holds is current. */\nfunction fileNeedsRewrite(local: LocalAppConfig): boolean {\n return !RUN_SETTING_KEYS.every((key) => key in local) || RETIRED_KEYS.some((key) => key in local);\n}\n\n/**\n * Service for syncing app configurations between local JSON files and remote Farseer instance\n */\nexport class AppSyncService {\n private api: FarseerService;\n private appsDir: string;\n\n constructor(tenant: string, api: FarseerService) {\n this.api = api;\n this.appsDir = getTenantAppsDir(tenant);\n }\n\n /**\n * Get filename for an app (keep original name, just sanitize for filesystem)\n */\n private getAppFilename(name: string): string {\n return (\n sanitizeDiacritics(name)\n .replace(/[<>:\"/\\\\|?*]/g, '') // Remove invalid filename characters\n .trim() + '.json'\n );\n }\n\n /**\n * Names of locally-tracked apps the next `pull` would delete because\n * remote no longer has them. Uses only `listApps` (no per-app fetch),\n * so pull can preview deletions for the destructive-action prompt\n * without paying for getStatus's full per-app round-trip.\n *\n * Mirrors the deletion gate in `pull()` (`local._remote && !remoteApps.has(key)`):\n * apps the user never pulled (`_remote` undefined) are kept untouched\n * by pull, so they don't belong in this list.\n */\n async getRemoteDeletions(): Promise<string[]> {\n const localApps = this.loadLocalApps();\n const remoteAppList = await this.api.listApps();\n const remoteNames = new Set(remoteAppList.map((a) => a.name.toLowerCase()));\n const deleted: string[] = [];\n for (const [key, local] of localApps) {\n if (local._remote && !remoteNames.has(key)) {\n deleted.push(local.name);\n }\n }\n return deleted;\n }\n\n /**\n * Load all local app configs\n */\n loadLocalApps(): Map<string, LocalAppConfig> {\n const apps = new Map<string, LocalAppConfig>();\n\n if (!fs.existsSync(this.appsDir)) {\n return apps;\n }\n\n const files = fs.readdirSync(this.appsDir).filter((f) => f.endsWith('.json'));\n\n for (const file of files) {\n try {\n const content = fs.readFileSync(path.join(this.appsDir, file), 'utf-8');\n const config = migrateLegacyArguments(JSON.parse(content)) as unknown as LocalAppConfig;\n apps.set(config.name.toLowerCase(), config);\n } catch {\n // Skip invalid files\n }\n }\n\n return apps;\n }\n\n /**\n * Save a local app config\n */\n saveLocalApp(config: LocalAppConfig): void {\n ensureDirectoryExists(this.appsDir);\n const filename = this.getAppFilename(config.name);\n const filePath = path.join(this.appsDir, filename);\n fs.writeFileSync(filePath, JSON.stringify(config, null, 2), 'utf-8');\n }\n\n /**\n * Delete a local app config\n */\n deleteLocalApp(name: string): boolean {\n const filename = this.getAppFilename(name);\n const filePath = path.join(this.appsDir, filename);\n\n if (fs.existsSync(filePath)) {\n fs.unlinkSync(filePath);\n return true;\n }\n return false;\n }\n\n /**\n * Convert remote app to local config format\n */\n private remoteToLocal(remote: RemoteApp, reference: string): LocalAppConfig {\n const scriptFiles = remote.scriptFiles ?? [];\n const mainScript = scriptFiles.find((s) => s.id === remote.mainScriptFileId);\n\n // \"No default\" canonical shape locally is `defaultValue: ''` (empty\n // string), NOT an omitted key. The OpenAPI schema makes the field\n // optional, so the backend can emit either; if we passed `undefined`\n // through verbatim, a user who added `defaultValue: ''` locally\n // would see `areAppsEqual` say \"match\" (both normalise to '') but\n // the next pull would strip the key again \u2014 the on-disk JSON would\n // oscillate forever and never reach a steady state. type is treated\n // the same way ('variable' is the implicit default), secret only\n // appears when explicitly true on the backend (boolean is a clear\n // tri-state: true/false/unset, and \"unset\" reads as false anyway).\n return {\n name: remote.name,\n description: remote.description || '',\n entrypoint: mainScript?.name || null,\n arguments: remote.expectedArguments.map((a) => {\n // Pin a steady-state shape so two pulls back-to-back don't\n // oscillate. `defaultValue` is normalized to '' when omitted \u2014\n // a user-edited `defaultValue: ''` locally must compare equal\n // to a remote that omits the field. `dataType` defaults to\n // 'string' (the implicit pre-fix shape). All other axes\n // (`fixed`, `options`, `secret`) are only emitted when the\n // remote populated them, to keep the JSON minimal.\n const arg: LocalAppConfig['arguments'][number] = {\n name: a.name,\n defaultValue: a.defaultValue ?? '',\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n }),\n // Written on every pull, including as null / 'local' / [], so the\n // file says what the tenant holds rather than staying silent and\n // reading as \"not managed\" on the next push.\n schedule: remote.schedule || null,\n runnerImage: remote.runnerImage || null,\n compute: formatCompute(remote.compute),\n _remote: {\n id: remote.id,\n reference: reference,\n },\n };\n }\n\n /**\n * Check if local and remote app configs are equivalent\n */\n private areAppsEqual(local: LocalAppConfig, remote: RemoteApp): boolean {\n // Compare name\n if (local.name !== remote.name) return false;\n\n // Compare description\n if ((local.description || '') !== (remote.description || '')) return false;\n\n // Compare entrypoint\n const remoteScriptFiles = remote.scriptFiles ?? [];\n const remoteEntrypoint = remoteScriptFiles.find((s) => s.id === remote.mainScriptFileId)?.name || null;\n if (local.entrypoint !== remoteEntrypoint) return false;\n\n // Compare arguments. Order matters here: backend renders args in the\n // saved order in the UI, so we treat reordering as a real change.\n // Missing `dataType` defaults to 'string' (the implicit pre-fix value);\n // missing scalar defaults are normalized so '' vs undefined doesn't\n // show up as a spurious diff. All four axes (dataType, fixed, options,\n // defaultValue, secret) are compared so a pull\u2192push round-trip\n // detects changes on any of them.\n if (local.arguments.length !== remote.expectedArguments.length) return false;\n for (let i = 0; i < local.arguments.length; i++) {\n const l = local.arguments[i];\n const r = remote.expectedArguments[i];\n if (l.name !== r.name) return false;\n if ((l.dataType ?? 'string') !== (r.dataType ?? 'string')) return false;\n if (Boolean(l.fixed) !== Boolean(r.fixed)) return false;\n if (JSON.stringify(l.options ?? []) !== JSON.stringify(r.options ?? [])) return false;\n if ((l.defaultValue ?? '') !== (r.defaultValue ?? '')) return false;\n if (Boolean(l.secret) !== Boolean(r.secret)) return false;\n }\n\n // Only what the file declares. A config written before these fields\n // existed omits them, and comparing an absent key against a populated\n // tenant would report that app modified forever.\n if ('schedule' in local && (local.schedule || null) !== (remote.schedule || null)) return false;\n if ('runnerImage' in local && (local.runnerImage || null) !== (remote.runnerImage || null)) return false;\n // Compare on what push would actually send. A local `compute` push cannot\n // express \u2014 `null`, or a string parseComputeChoice rejects \u2014 is drift no\n // push could ever close, so counting it leaves the app modified forever.\n const declaredCompute = 'compute' in local && local.compute ? parseComputeChoice(local.compute) : null;\n if (declaredCompute && formatCompute(declaredCompute) !== formatCompute(remote.compute)) return false;\n\n return true;\n }\n\n /**\n * Pull apps from remote and save locally\n */\n async pull(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n logger.dim(`Fetching ${remoteAppList.length} apps in parallel...`);\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item, index) => {\n const app = await this.api.getApp(item.reference);\n // Show progress every 10 apps\n if ((index + 1) % 10 === 0 || index === remoteAppList.length - 1) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write(`\\r Progress: ${index + 1}/${remoteAppList.length} apps`);\n }\n return { app, reference: item.reference };\n },\n 15,\n );\n // Clear progress line\n if (remoteAppList.length > 0) {\n const stream = process.env.FARSEER_MCP === '1' ? process.stderr : process.stdout;\n stream.write('\\r' + ' '.repeat(50) + '\\r');\n }\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Process remote apps\n for (const [key, { app, reference }] of remoteApps) {\n const localConfig = this.remoteToLocal(app, reference);\n const existingLocal = localApps.get(key);\n\n if (!existingLocal) {\n // New app from remote\n this.saveLocalApp(localConfig);\n result.created.push(app.name);\n } else if (!this.areAppsEqual(existingLocal, app) || fileNeedsRewrite(existingLocal)) {\n // App changed on remote, or the file's shape is out of date: it\n // predates the run settings and would never gain them \u2014\n // areAppsEqual ignores keys the file omits \u2014 or it still carries\n // one that is no longer synced.\n this.saveLocalApp(localConfig);\n result.updated.push(app.name);\n } else {\n result.unchanged.push(app.name);\n }\n }\n\n // Check for apps deleted on remote\n for (const [key, local] of localApps) {\n if (!remoteApps.has(key) && local._remote) {\n // App was synced before but now deleted on remote\n this.deleteLocalApp(local.name);\n result.deleted.push(local.name);\n }\n }\n\n return result;\n }\n\n /**\n * Push local apps to remote\n */\n async push(): Promise<AppSyncResult> {\n const result: AppSyncResult = {\n created: [],\n updated: [],\n deleted: [],\n unchanged: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Get available scripts for ID lookup\n // Build maps for both path-based and filename-based lookup (backward compatibility)\n const availableScripts = await this.api.getScriptFiles();\n const scriptIdByPath = new Map<string, string>();\n const scriptIdByName = new Map<string, string>();\n\n for (const s of availableScripts) {\n // s.name now contains full path (e.g., \"Scripts/test.ts\")\n const pathKey = s.name.toLowerCase();\n const filenameKey = s.name.split('/').pop()?.toLowerCase() || pathKey;\n\n scriptIdByPath.set(pathKey, s.id);\n // For filename lookup, only set if not already set (first match wins for ambiguous names)\n if (!scriptIdByName.has(filenameKey)) {\n scriptIdByName.set(filenameKey, s.id);\n }\n }\n\n // Helper to find script ID by path or filename\n const findScriptId = (scriptRef: string): string | undefined => {\n const key = scriptRef.toLowerCase();\n // Try exact path match first\n const byPath = scriptIdByPath.get(key);\n if (byPath) return byPath;\n // Try with Scripts/ prefix\n const withPrefix = scriptIdByPath.get(`scripts/${key}`);\n if (withPrefix) return withPrefix;\n // Fall back to filename match\n return scriptIdByName.get(key.split('/').pop() || key);\n };\n\n // Process local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n // New local app - create on remote\n try {\n const created = await this.api.createApp(local.name);\n\n // Update with config (API requires name and description)\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n await this.api.updateApp(created.id.toString(), update, created);\n\n // Update local with remote ID\n local._remote = {\n id: created.id,\n reference: created.id.toString(),\n };\n this.saveLocalApp(local);\n\n result.created.push(local.name);\n } catch (error) {\n logger.error(`Failed to create app ${local.name}: ${await formatClientError(error)}`);\n }\n } else if (!this.areAppsEqual(local, remote.app)) {\n // App differs - update remote\n try {\n const update = this.buildUpdatePayload(local, findScriptId);\n update.name = local.name;\n update.description = local.description;\n\n await this.api.updateApp(remote.reference, update, remote.app);\n result.updated.push(local.name);\n } catch (error) {\n logger.error(`Failed to update app ${local.name}: ${await formatClientError(error)}`);\n }\n } else {\n result.unchanged.push(local.name);\n }\n }\n\n // Note: We don't auto-delete remote apps when deleted locally\n // User must use \"farseer app delete\" explicitly\n\n return result;\n }\n\n /**\n * Build update payload for API\n */\n private buildUpdatePayload(\n local: LocalAppConfig,\n findScriptId: (scriptRef: string) => string | undefined,\n ): AppUpdateChanges {\n const update: AppUpdateChanges = {};\n\n // Arguments \u2014 preserve all axes. `dataType` defaults to 'string' for\n // older app json files that pre-date typed parameters. Always sent\n // (even when empty): the local config is authoritative for the sync\n // path, so an app whose args were cleared locally must push that\n // emptiness through, otherwise `mergeAppUpdate` would keep the remote\n // args and `status` would report the app modified forever.\n update.expectedArguments = local.arguments.map((a) => {\n const arg: AppArgument = {\n name: a.name,\n dataType: a.dataType ?? 'string',\n };\n if (a.fixed !== undefined) arg.fixed = a.fixed;\n if (a.options !== undefined) arg.options = a.options;\n if (a.defaultValue !== undefined) arg.defaultValue = a.defaultValue;\n if (a.secret !== undefined) arg.secret = a.secret;\n return arg;\n });\n\n // Entrypoint - lookup by path or filename\n if (local.entrypoint) {\n const entrypointId = findScriptId(local.entrypoint);\n if (entrypointId) {\n update.mainScriptFileId = entrypointId;\n }\n }\n\n // Key presence is the contract: a declared setting is enforced, an\n // absent one is left to whatever the tenant already holds.\n if ('schedule' in local) {\n update.schedule = local.schedule || null;\n }\n if ('runnerImage' in local) {\n update.runnerImage = local.runnerImage || null;\n }\n if ('compute' in local && local.compute) {\n const compute = parseComputeChoice(local.compute);\n if (compute) {\n update.compute = compute;\n } else {\n logger.warning(\n `Ignoring unknown compute \"${local.compute}\" for app ${local.name}: expected local, batch or batch:<size>.`,\n );\n }\n }\n\n return update;\n }\n\n /**\n * Get sync status without making changes\n */\n async getStatus(): Promise<AppSyncStatus> {\n const status: AppSyncStatus = {\n newLocal: [],\n newRemote: [],\n modified: [],\n synced: [],\n };\n\n // Load local apps\n const localApps = this.loadLocalApps();\n\n // Fetch remote apps\n const remoteAppList = await this.api.listApps();\n const remoteApps = new Map<string, { app: RemoteApp; reference: string }>();\n\n // Fetch app details in parallel with concurrency limit\n const appDetails = await fetchWithConcurrency(\n remoteAppList,\n async (item) => {\n const app = await this.api.getApp(item.reference);\n return { app, reference: item.reference };\n },\n 15,\n );\n\n for (const { app, reference } of appDetails) {\n if (app) {\n remoteApps.set(app.name.toLowerCase(), { app, reference });\n }\n }\n\n // Check local apps\n for (const [key, local] of localApps) {\n const remote = remoteApps.get(key);\n\n if (!remote) {\n status.newLocal.push(local.name);\n } else if (!this.areAppsEqual(local, remote.app)) {\n status.modified.push(local.name);\n } else {\n status.synced.push(local.name);\n }\n }\n\n // Check for new remote apps\n for (const [key, { app }] of remoteApps) {\n if (!localApps.has(key)) {\n status.newRemote.push(app.name);\n }\n }\n\n return status;\n }\n}\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,kBAQO;AAEP,qBAA8E;AAC9E,oBAAuB;AACvB,4BAAkC;AAgElC,SAAS,mBAAmB,MAAsB;AAC9C,QAAM,eAAuC;AAAA;AAAA,IAEzC,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA;AAAA,IAEH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAA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AW;AAClC,YAAM,SAAS,WAAW,IAAI,GAAG;AAEjC,UAAI,CAAC,QAAQ;AACT,eAAO,SAAS,KAAK,MAAM,IAAI;AAAA,MACnC,WAAW,CAAC,KAAK,aAAa,OAAO,OAAO,GAAG,GAAG;AAC9C,eAAO,SAAS,KAAK,MAAM,IAAI;AAAA,MACnC,OAAO;AACH,eAAO,OAAO,KAAK,MAAM,IAAI;AAAA,MACjC;AAAA,IACJ;AAGA,eAAW,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,YAAY;AACrC,UAAI,CAAC,UAAU,IAAI,GAAG,GAAG;AACrB,eAAO,UAAU,KAAK,IAAI,IAAI;AAAA,MAClC;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;",
6
6
  "names": []
7
7
  }
@@ -48,7 +48,8 @@ __export(configService_exports, {
48
48
  saveTenantOrgMapping: () => saveTenantOrgMapping,
49
49
  setCredential: () => setCredential,
50
50
  setSyncIncludes: () => setSyncIncludes,
51
- setUserAuth: () => setUserAuth
51
+ setUserAuth: () => setUserAuth,
52
+ storedBasePath: () => storedBasePath
52
53
  });
53
54
  module.exports = __toCommonJS(configService_exports);
54
55
  var fs = __toESM(require("fs"));
@@ -102,7 +103,8 @@ function getCredential(tenant) {
102
103
  return environment;
103
104
  }
104
105
  const config = loadConfig();
105
- return config.credentials[tenant];
106
+ const credential = config.credentials[tenant];
107
+ return credential && process.env.FARSEER_API_URL ? { ...credential, basePath: process.env.FARSEER_API_URL.replace(/\/+$/, "") } : credential;
106
108
  }
107
109
  function setCredential(tenant, credential) {
108
110
  const config = loadConfig();
@@ -157,6 +159,7 @@ function getOrganisationRealm(organisation) {
157
159
  return loadConfig().organisationRealms?.[organisation];
158
160
  }
159
161
  function saveOrganisationRealm(organisation, realm) {
162
+ if (process.env.FARSEER_API_URL) return;
160
163
  const config = loadConfig();
161
164
  config.organisationRealms = { ...config.organisationRealms, [organisation]: realm };
162
165
  saveConfig(config);
@@ -167,9 +170,12 @@ function isUserAuthValid(auth = getUserAuth()) {
167
170
  const bufferMs = 10 * 1e3;
168
171
  return expiresAt.getTime() > Date.now() + bufferMs;
169
172
  }
170
- function generateBasePath(organisation) {
173
+ function storedBasePath(organisation) {
171
174
  return `https://${organisation}.farseer.io/api/v3`;
172
175
  }
176
+ function generateBasePath(organisation) {
177
+ return process.env.FARSEER_API_URL?.replace(/\/+$/, "") || storedBasePath(organisation);
178
+ }
173
179
  function saveTenantOrgMapping(tenant, organisation) {
174
180
  const config = loadConfig();
175
181
  if (!config.tenantOrgMapping) {
@@ -240,6 +246,7 @@ function environmentCredential() {
240
246
  saveTenantOrgMapping,
241
247
  setCredential,
242
248
  setSyncIncludes,
243
- setUserAuth
249
+ setUserAuth,
250
+ storedBasePath
244
251
  });
245
252
  //# sourceMappingURL=configService.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/services/configService.ts"],
4
- "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\n\nexport interface ApiKeyCredential {\n type: 'apiKey';\n tenantId: string;\n apiKey: string;\n basePath: string;\n}\n\nexport interface UserAuth {\n accessToken: string;\n refreshToken: string;\n expiresAt: string;\n tenant?: string; // Tenant used for login (Keycloak client ID)\n realm?: string; // Keycloak realm (default: master)\n}\n\nexport const DEFAULT_REALM = 'master';\n\n// The backend issues agent sandbox turns short-lived API keys with this prefix.\nexport const AGENT_API_KEY_PREFIX = 'agent1.';\n\n// Resolved { org, tenant } pair. No longer persisted as a machine-global\n// default (that made it impossible to work on two tenants in two shells and\n// silently retargeted bare commands). It survives only as the shape the MCP\n// per-process pin and the CLI's env-based resolution both pass around.\nexport interface CurrentCheckout {\n organisation: string; // For URL: https://<organisation>.farseer.io\n tenant: string; // For X-TENANT-ID header\n}\n\nexport interface SyncIncludes {\n extensions?: string[];\n folders?: string[];\n}\n\nexport interface FarseerConfig {\n credentials: Record<string, ApiKeyCredential>;\n // One browser login per Keycloak realm: a token only works at organisations\n // whose tenants live in the realm that issued it.\n userAuths?: Record<string, UserAuth>;\n // The last login made, kept current through its refreshes, for CLIs from\n // before `userAuths` that share this file.\n userAuth?: UserAuth;\n organisationRealms?: Record<string, string>; // Organisation -> Keycloak realm\n tenantOrgMapping?: Record<string, string>; // Tenant -> Organisation mapping\n syncIncludes?: Record<string, SyncIncludes>; // Per-tenant sync includes\n}\n\nconst CONFIG_DIR = path.join(os.homedir(), '.farseer');\nconst CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');\n\nfunction ensureConfigDir(): void {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });\n }\n}\n\nfunction getDefaultConfig(): FarseerConfig {\n return {\n credentials: {},\n };\n}\n\n/**\n * `userAuth` is either the mirror of a login in `userAuths` or one an older CLI\n * wrote since \u2014 never older \u2014 so it wins for its realm.\n */\nfunction mergeLegacyUserAuth(config: FarseerConfig): FarseerConfig {\n if (config.userAuth) {\n const realm = config.userAuth.realm || DEFAULT_REALM;\n config.userAuths = { ...config.userAuths, [realm]: { ...config.userAuth, realm } };\n }\n return config;\n}\n\nexport function loadConfig(): FarseerConfig {\n ensureConfigDir();\n\n if (!fs.existsSync(CONFIG_FILE)) {\n return getDefaultConfig();\n }\n\n try {\n const content = fs.readFileSync(CONFIG_FILE, 'utf-8');\n return mergeLegacyUserAuth(JSON.parse(content) as FarseerConfig);\n } catch {\n return getDefaultConfig();\n }\n}\n\n/**\n * This file holds every stored API key plus the Keycloak refresh and access\n * tokens, so it is owner-only. `mode` on writeFileSync applies to a file being\n * created, not an existing one, and the token refresh rewrites this file from\n * every request \u2014 so an existing 0644 file is corrected explicitly rather than\n * staying world-readable for the life of the install.\n */\nexport function saveConfig(config: FarseerConfig): void {\n ensureConfigDir();\n fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { encoding: 'utf-8', mode: 0o600 });\n try {\n fs.chmodSync(CONFIG_FILE, 0o600);\n } catch {\n // A filesystem that will not take a mode (a Windows volume, a mounted\n // share) is not a reason to fail the write the caller asked for.\n }\n}\n\nexport function getCredential(tenant: string): ApiKeyCredential | undefined {\n const environment = environmentCredential();\n if (environment) {\n if (tenant !== environment.tenantId) throw new Error('Environment credentials are bound to another tenant');\n return environment;\n }\n const config = loadConfig();\n return config.credentials[tenant];\n}\n\nexport function setCredential(tenant: string, credential: ApiKeyCredential): void {\n const config = loadConfig();\n config.credentials[tenant] = credential;\n saveConfig(config);\n}\n\nexport function removeCredential(tenant: string): boolean {\n const config = loadConfig();\n if (config.credentials[tenant]) {\n delete config.credentials[tenant];\n saveConfig(config);\n return true;\n }\n return false;\n}\n\nexport function listCredentials(): Record<string, ApiKeyCredential> {\n const environment = environmentCredential();\n if (environment) return { [environment.tenantId]: environment };\n const config = loadConfig();\n return config.credentials;\n}\n\nexport function getUserAuth(realm: string = DEFAULT_REALM): UserAuth | undefined {\n if (environmentCredential()) return undefined;\n return loadConfig().userAuths?.[realm];\n}\n\n/** Every browser login, keyed by realm. */\nexport function listUserAuths(): Record<string, UserAuth> {\n if (environmentCredential()) return {};\n return loadConfig().userAuths ?? {};\n}\n\n/**\n * A refresh moves the legacy mirror only when it already holds that realm, or\n * an older CLI would follow whichever realm refreshed last and send its token to\n * the wrong organisations. It must still move then: left behind, it would win\n * over the newer token on the next load.\n */\nexport function setUserAuth(auth: UserAuth, { refresh = false }: { refresh?: boolean } = {}): void {\n const config = loadConfig();\n const realm = auth.realm || DEFAULT_REALM;\n config.userAuths = { ...config.userAuths, [realm]: { ...auth, realm } };\n if (!refresh || (config.userAuth?.realm || DEFAULT_REALM) === realm) {\n config.userAuth = config.userAuths[realm];\n }\n saveConfig(config);\n}\n\n/** One realm's login, or every login when no realm is given. */\nexport function clearUserAuth(realm?: string): void {\n const config = loadConfig();\n if (realm === undefined) {\n delete config.userAuths;\n } else if (config.userAuths) {\n delete config.userAuths[realm];\n }\n if (realm === undefined || (config.userAuth?.realm || DEFAULT_REALM) === realm) {\n delete config.userAuth;\n }\n saveConfig(config);\n}\n\nexport function getOrganisationRealm(organisation: string): string | undefined {\n return loadConfig().organisationRealms?.[organisation];\n}\n\nexport function saveOrganisationRealm(organisation: string, realm: string): void {\n const config = loadConfig();\n config.organisationRealms = { ...config.organisationRealms, [organisation]: realm };\n saveConfig(config);\n}\n\n/**\n * Pass `auth` when you already have it. The middleware asks this on every\n * request and re-reading the config file to answer it means a second\n * existsSync + readFileSync + JSON.parse per call.\n */\nexport function isUserAuthValid(auth: UserAuth | undefined = getUserAuth()): boolean {\n if (!auth) return false;\n\n const expiresAt = new Date(auth.expiresAt);\n // Add 10 second buffer to proactively refresh before actual expiry\n // Note: Keycloak tokens typically last 60 seconds, so buffer must be small\n const bufferMs = 10 * 1000;\n return expiresAt.getTime() > Date.now() + bufferMs;\n}\n\nexport function generateBasePath(organisation: string): string {\n return `https://${organisation}.farseer.io/api/v3`;\n}\n\n// There is deliberately no persisted \"current tenant\" any more. A command's\n// target comes from an explicit argument or the FARSEER_TENANT env var (see\n// getEnvCheckout in utils/helpers.ts), and the CLI errors if neither is set\n// rather than falling back to a machine-global default. The tenant->org\n// mapping below is kept: it lets `export FARSEER_TENANT=<tenant>` resolve the\n// org on its own, so only new org != tenant tenants need FARSEER_ORG too.\n\n// Tenant-Organisation mapping\nexport function saveTenantOrgMapping(tenant: string, organisation: string): void {\n const config = loadConfig();\n if (!config.tenantOrgMapping) {\n config.tenantOrgMapping = {};\n }\n config.tenantOrgMapping[tenant] = organisation;\n saveConfig(config);\n}\n\nexport function getTenantOrg(tenant: string): string | undefined {\n const config = loadConfig();\n return config.tenantOrgMapping?.[tenant];\n}\n\n// Sync includes management\nexport function getSyncIncludes(tenant: string): SyncIncludes | null {\n const config = loadConfig();\n return config.syncIncludes?.[tenant] ?? null;\n}\n\nexport function setSyncIncludes(tenant: string, includes: SyncIncludes): void {\n const config = loadConfig();\n if (!config.syncIncludes) {\n config.syncIncludes = {};\n }\n // Clean up empty arrays\n if (includes.extensions?.length === 0) delete includes.extensions;\n if (includes.folders?.length === 0) delete includes.folders;\n // Remove entry entirely if empty\n if (!includes.extensions && !includes.folders) {\n delete config.syncIncludes[tenant];\n } else {\n config.syncIncludes[tenant] = includes;\n }\n // Remove syncIncludes key if no tenants left\n if (Object.keys(config.syncIncludes).length === 0) {\n delete config.syncIncludes;\n }\n saveConfig(config);\n}\n\n/**\n * Non-persistent credentials for an agent sandbox turn, which passes an agent key with\n * the backend URL and tenant. App scripts, the SDK and the data-export guide export the\n * same names with ordinary keys, so only an agent key overrides the saved logins.\n */\nexport function environmentCredential(): ApiKeyCredential | undefined {\n const { FARSEER_API_KEY: apiKey, FARSEER_URL: url, FARSEER_TENANT: tenantId } = process.env;\n if (!apiKey?.startsWith(AGENT_API_KEY_PREFIX)) return undefined;\n if (!url || !tenantId) throw new Error('Set FARSEER_API_KEY, FARSEER_URL and FARSEER_TENANT together');\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error('FARSEER_URL must be an HTTP(S) backend URL');\n }\n if (\n !['http:', 'https:'].includes(parsed.protocol) ||\n parsed.username ||\n parsed.password ||\n parsed.search ||\n parsed.hash\n )\n throw new Error('FARSEER_URL must be an HTTP(S) backend URL without credentials or query parameters');\n const base = parsed.toString().replace(/\\/+$/, '');\n return { type: 'apiKey', tenantId, apiKey, basePath: base.endsWith('/api/v3') ? base : base + '/api/v3' };\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,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AAiBb,MAAM,gBAAgB;AAGtB,MAAM,uBAAuB;AA6BpC,MAAM,aAAa,KAAK,KAAK,GAAG,QAAQ,GAAG,UAAU;AACrD,MAAM,cAAc,KAAK,KAA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AAC/C,WAAO,OAAO;AAAA,EAClB;AACA,aAAW,MAAM;AACrB;AAOO,SAAS,wBAAsD;AAClE,QAAM,EAAE,iBAAiB,QAAQ,aAAa,KAAK,gBAAgB,SAAS,IAAI,QAAQ;AACxF,MAAI,CAAC,QAAQ,WAAW,oBAAoB,EAAG,QAAO;AACtD,MAAI,CAAC,OAAO,CAAC,SAAU,OAAM,IAAI,MAAM,8DAA8D;AACrG,MAAI;AACJ,MAAI;AACA,aAAS,IAAI,IAAI,GAAG;AAAA,EACxB,QAAQ;AACJ,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAChE;AACA,MACI,CAAC,CAAC,SAAS,QAAQ,EAAE,SAAS,OAAO,QAAQ,KAC7C,OAAO,YACP,OAAO,YACP,OAAO,UACP,OAAO;AAEP,UAAM,IAAI,MAAM,oFAAoF;AACxG,QAAM,OAAO,OAAO,SAAS,EAAE,QAAQ,QAAQ,EAAE;AACjD,SAAO,EAAE,MAAM,UAAU,UAAU,QAAQ,UAAU,KAAK,SAAS,SAAS,IAAI,OAAO,OAAO,UAAU;AAC5G;",
4
+ "sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\n\nexport interface ApiKeyCredential {\n type: 'apiKey';\n tenantId: string;\n apiKey: string;\n basePath: string;\n}\n\nexport interface UserAuth {\n accessToken: string;\n refreshToken: string;\n expiresAt: string;\n tenant?: string; // Tenant used for login (Keycloak client ID)\n realm?: string; // Keycloak realm (default: master)\n}\n\nexport const DEFAULT_REALM = 'master';\n\n// The backend issues agent sandbox turns short-lived API keys with this prefix.\nexport const AGENT_API_KEY_PREFIX = 'agent1.';\n\n// Resolved { org, tenant } pair. No longer persisted as a machine-global\n// default (that made it impossible to work on two tenants in two shells and\n// silently retargeted bare commands). It survives only as the shape the MCP\n// per-process pin and the CLI's env-based resolution both pass around.\nexport interface CurrentCheckout {\n organisation: string; // For URL: https://<organisation>.farseer.io\n tenant: string; // For X-TENANT-ID header\n}\n\nexport interface SyncIncludes {\n extensions?: string[];\n folders?: string[];\n}\n\nexport interface FarseerConfig {\n credentials: Record<string, ApiKeyCredential>;\n // One browser login per Keycloak realm: a token only works at organisations\n // whose tenants live in the realm that issued it.\n userAuths?: Record<string, UserAuth>;\n // The last login made, kept current through its refreshes, for CLIs from\n // before `userAuths` that share this file.\n userAuth?: UserAuth;\n organisationRealms?: Record<string, string>; // Organisation -> Keycloak realm\n tenantOrgMapping?: Record<string, string>; // Tenant -> Organisation mapping\n syncIncludes?: Record<string, SyncIncludes>; // Per-tenant sync includes\n}\n\nconst CONFIG_DIR = path.join(os.homedir(), '.farseer');\nconst CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');\n\nfunction ensureConfigDir(): void {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });\n }\n}\n\nfunction getDefaultConfig(): FarseerConfig {\n return {\n credentials: {},\n };\n}\n\n/**\n * `userAuth` is either the mirror of a login in `userAuths` or one an older CLI\n * wrote since \u2014 never older \u2014 so it wins for its realm.\n */\nfunction mergeLegacyUserAuth(config: FarseerConfig): FarseerConfig {\n if (config.userAuth) {\n const realm = config.userAuth.realm || DEFAULT_REALM;\n config.userAuths = { ...config.userAuths, [realm]: { ...config.userAuth, realm } };\n }\n return config;\n}\n\nexport function loadConfig(): FarseerConfig {\n ensureConfigDir();\n\n if (!fs.existsSync(CONFIG_FILE)) {\n return getDefaultConfig();\n }\n\n try {\n const content = fs.readFileSync(CONFIG_FILE, 'utf-8');\n return mergeLegacyUserAuth(JSON.parse(content) as FarseerConfig);\n } catch {\n return getDefaultConfig();\n }\n}\n\n/**\n * This file holds every stored API key plus the Keycloak refresh and access\n * tokens, so it is owner-only. `mode` on writeFileSync applies to a file being\n * created, not an existing one, and the token refresh rewrites this file from\n * every request \u2014 so an existing 0644 file is corrected explicitly rather than\n * staying world-readable for the life of the install.\n */\nexport function saveConfig(config: FarseerConfig): void {\n ensureConfigDir();\n fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { encoding: 'utf-8', mode: 0o600 });\n try {\n fs.chmodSync(CONFIG_FILE, 0o600);\n } catch {\n // A filesystem that will not take a mode (a Windows volume, a mounted\n // share) is not a reason to fail the write the caller asked for.\n }\n}\n\nexport function getCredential(tenant: string): ApiKeyCredential | undefined {\n const environment = environmentCredential();\n if (environment) {\n if (tenant !== environment.tenantId) throw new Error('Environment credentials are bound to another tenant');\n return environment;\n }\n const config = loadConfig();\n const credential = config.credentials[tenant];\n return credential && process.env.FARSEER_API_URL\n ? { ...credential, basePath: process.env.FARSEER_API_URL.replace(/\\/+$/, '') }\n : credential;\n}\n\nexport function setCredential(tenant: string, credential: ApiKeyCredential): void {\n const config = loadConfig();\n config.credentials[tenant] = credential;\n saveConfig(config);\n}\n\nexport function removeCredential(tenant: string): boolean {\n const config = loadConfig();\n if (config.credentials[tenant]) {\n delete config.credentials[tenant];\n saveConfig(config);\n return true;\n }\n return false;\n}\n\nexport function listCredentials(): Record<string, ApiKeyCredential> {\n const environment = environmentCredential();\n if (environment) return { [environment.tenantId]: environment };\n const config = loadConfig();\n return config.credentials;\n}\n\nexport function getUserAuth(realm: string = DEFAULT_REALM): UserAuth | undefined {\n if (environmentCredential()) return undefined;\n return loadConfig().userAuths?.[realm];\n}\n\n/** Every browser login, keyed by realm. */\nexport function listUserAuths(): Record<string, UserAuth> {\n if (environmentCredential()) return {};\n return loadConfig().userAuths ?? {};\n}\n\n/**\n * A refresh moves the legacy mirror only when it already holds that realm, or\n * an older CLI would follow whichever realm refreshed last and send its token to\n * the wrong organisations. It must still move then: left behind, it would win\n * over the newer token on the next load.\n */\nexport function setUserAuth(auth: UserAuth, { refresh = false }: { refresh?: boolean } = {}): void {\n const config = loadConfig();\n const realm = auth.realm || DEFAULT_REALM;\n config.userAuths = { ...config.userAuths, [realm]: { ...auth, realm } };\n if (!refresh || (config.userAuth?.realm || DEFAULT_REALM) === realm) {\n config.userAuth = config.userAuths[realm];\n }\n saveConfig(config);\n}\n\n/** One realm's login, or every login when no realm is given. */\nexport function clearUserAuth(realm?: string): void {\n const config = loadConfig();\n if (realm === undefined) {\n delete config.userAuths;\n } else if (config.userAuths) {\n delete config.userAuths[realm];\n }\n if (realm === undefined || (config.userAuth?.realm || DEFAULT_REALM) === realm) {\n delete config.userAuth;\n }\n saveConfig(config);\n}\n\nexport function getOrganisationRealm(organisation: string): string | undefined {\n return loadConfig().organisationRealms?.[organisation];\n}\n\n/**\n * Remembers the realm an organisation's tenants live in. Not while `FARSEER_API_URL` overrides the\n * host: the realm then comes from the override's server, and saving it under the organisation's\n * name would make the real organisation use it after the variable is unset.\n */\nexport function saveOrganisationRealm(organisation: string, realm: string): void {\n if (process.env.FARSEER_API_URL) return;\n const config = loadConfig();\n config.organisationRealms = { ...config.organisationRealms, [organisation]: realm };\n saveConfig(config);\n}\n\n/**\n * Pass `auth` when you already have it. The middleware asks this on every\n * request and re-reading the config file to answer it means a second\n * existsSync + readFileSync + JSON.parse per call.\n */\nexport function isUserAuthValid(auth: UserAuth | undefined = getUserAuth()): boolean {\n if (!auth) return false;\n\n const expiresAt = new Date(auth.expiresAt);\n // Add 10 second buffer to proactively refresh before actual expiry\n // Note: Keycloak tokens typically last 60 seconds, so buffer must be small\n const bufferMs = 10 * 1000;\n return expiresAt.getTime() > Date.now() + bufferMs;\n}\n\n/** The organisation's API URL, as a saved credential stores it; `FARSEER_API_URL` never reaches it. */\nexport function storedBasePath(organisation: string): string {\n return `https://${organisation}.farseer.io/api/v3`;\n}\n\n/** The API URL a request uses: `FARSEER_API_URL` when set, else the organisation's. */\nexport function generateBasePath(organisation: string): string {\n return process.env.FARSEER_API_URL?.replace(/\\/+$/, '') || storedBasePath(organisation);\n}\n\n// There is deliberately no persisted \"current tenant\" any more. A command's\n// target comes from an explicit argument or the FARSEER_TENANT env var (see\n// getEnvCheckout in utils/helpers.ts), and the CLI errors if neither is set\n// rather than falling back to a machine-global default. The tenant->org\n// mapping below is kept: it lets `export FARSEER_TENANT=<tenant>` resolve the\n// org on its own, so only new org != tenant tenants need FARSEER_ORG too.\n\n// Tenant-Organisation mapping\nexport function saveTenantOrgMapping(tenant: string, organisation: string): void {\n const config = loadConfig();\n if (!config.tenantOrgMapping) {\n config.tenantOrgMapping = {};\n }\n config.tenantOrgMapping[tenant] = organisation;\n saveConfig(config);\n}\n\nexport function getTenantOrg(tenant: string): string | undefined {\n const config = loadConfig();\n return config.tenantOrgMapping?.[tenant];\n}\n\n// Sync includes management\nexport function getSyncIncludes(tenant: string): SyncIncludes | null {\n const config = loadConfig();\n return config.syncIncludes?.[tenant] ?? null;\n}\n\nexport function setSyncIncludes(tenant: string, includes: SyncIncludes): void {\n const config = loadConfig();\n if (!config.syncIncludes) {\n config.syncIncludes = {};\n }\n // Clean up empty arrays\n if (includes.extensions?.length === 0) delete includes.extensions;\n if (includes.folders?.length === 0) delete includes.folders;\n // Remove entry entirely if empty\n if (!includes.extensions && !includes.folders) {\n delete config.syncIncludes[tenant];\n } else {\n config.syncIncludes[tenant] = includes;\n }\n // Remove syncIncludes key if no tenants left\n if (Object.keys(config.syncIncludes).length === 0) {\n delete config.syncIncludes;\n }\n saveConfig(config);\n}\n\n/**\n * Non-persistent credentials for an agent sandbox turn, which passes an agent key with\n * the backend URL and tenant. App scripts, the SDK and the data-export guide export the\n * same names with ordinary keys, so only an agent key overrides the saved logins.\n */\nexport function environmentCredential(): ApiKeyCredential | undefined {\n const { FARSEER_API_KEY: apiKey, FARSEER_URL: url, FARSEER_TENANT: tenantId } = process.env;\n if (!apiKey?.startsWith(AGENT_API_KEY_PREFIX)) return undefined;\n if (!url || !tenantId) throw new Error('Set FARSEER_API_KEY, FARSEER_URL and FARSEER_TENANT together');\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error('FARSEER_URL must be an HTTP(S) backend URL');\n }\n if (\n !['http:', 'https:'].includes(parsed.protocol) ||\n parsed.username ||\n parsed.password ||\n parsed.search ||\n parsed.hash\n )\n throw new Error('FARSEER_URL must be an HTTP(S) backend URL without credentials or query parameters');\n const base = parsed.toString().replace(/\\/+$/, '');\n return { type: 'apiKey', tenantId, apiKey, basePath: base.endsWith('/api/v3') ? base : base + '/api/v3' };\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,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AAiBb,MAAM,gBAAgB;AAGtB,MAAM,uBAAuB;AA6BpC,MAAM,aAAa,KAAK,KAAK,GAAG,QAAQ,GAAG,UAAU;AACrD,MAAM,cAAc,KAAK,KAAK,YAAY,aAAa;AAEvD,SAAS,kBAAwB;AAC7B,MAAI,CAAC,GAAG,WAAW,UAAU,GAAG;AAC5B,OAAG,UAAU,YAAY,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAAA,EAC7D;AACJ;AAEA,SAAS,mBAAkC;AACvC,SAAO;AAAA,IACH,aAAa,CAAC;AAAA,EAClB;AACJ;AAMA,SAAS,oBAAoB,QAAsC;AAC/D,MAAI,OAAO,UAAU;AACjB,UAAM,QAAQ,OAAO,SAAS,SAAS;AACvC,WAAO,YAAY,EAAE,GAAG,OAAO,WAAW,CAAC,KAAK,GAAG,EAAE,GAAG,OAAO,UAAU,MAAM,EAAE;AAAA,EACrF;AACA,SAAO;AACX;AAEO,SAAS,aAA4B;AACxC,kBAAgB;AAEhB,MAAI,CAAC,GAAG,WAAW,WAAW,GAAG;AAC7B,WAAO,iBAAiB;AAAA,EAC5B;AAEA,MAAI;AACA,UAAM,UAAU,GAAG,aAAa,aAAa,OAAO;AACpD,WAAO,oBAAoB,KAAK,MAAM,OAAO,CAAkB;AAAA,EACnE,QAAQ;AACJ,WAAO,iBAAiB;AAAA,EAC5B;AACJ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YACP,OAAO,YACP,OAAO,UACP,OAAO;AAEP,UAAM,IAAI,MAAM,oFAAoF;AACxG,QAAM,OAAO,OAAO,SAAS,EAAE,QAAQ,QAAQ,EAAE;AACjD,SAAO,EAAE,MAAM,UAAU,UAAU,QAAQ,UAAU,KAAK,SAAS,SAAS,IAAI,OAAO,OAAO,UAAU;AAC5G;",
6
6
  "names": []
7
7
  }
@@ -590,6 +590,29 @@ class FarseerService {
590
590
  async pipelineRequest(method, route, body) {
591
591
  return this.apiRequest(route, method, body);
592
592
  }
593
+ get agentSession() {
594
+ return this.auth.kind === "apiKey" && this.auth.credential.apiKey.startsWith(import_configService.AGENT_API_KEY_PREFIX);
595
+ }
596
+ async downloadDatasetVersionFile(datasetId, versionId, filename, signal) {
597
+ const route = `/labs/datasets/${encodeURIComponent(datasetId)}/versions/${encodeURIComponent(versionId)}/file?filename=${encodeURIComponent(filename)}`;
598
+ return this.streamFromApi(route, signal, "Dataset file read failed");
599
+ }
600
+ async downloadFarseerFile(reference, signal) {
601
+ return this.streamFromApi(`/farseerFiles/${encodeURIComponent(reference)}`, signal, "Farseer file read failed");
602
+ }
603
+ /** Keep the turn credential in the parent process and send it only to the configured backend. */
604
+ async streamFromApi(route, signal, failure) {
605
+ const response = await (0, import_requests.pipelineFetch)()(`${basePathOf(this.auth)}${route}`, {
606
+ headers: { "x-api-version": import_apiVersion.API_VERSION, ...authHeaders(this.auth) },
607
+ redirect: "error",
608
+ signal
609
+ });
610
+ if (!response.ok || !response.body) {
611
+ await response.body?.cancel();
612
+ throw new import_httpError.HttpError(response.status, `${failure} (${response.status})`);
613
+ }
614
+ return response;
615
+ }
593
616
  async apiRequest(endpoint, method, body) {
594
617
  const url = `${basePathOf(this.auth)}${endpoint}`;
595
618
  const auth = this.auth.kind === "jwt" ? { ...this.auth, accessToken: await getFreshAccessToken(this.auth.realm) ?? this.auth.accessToken } : this.auth;