farseer-cli 1.13.0 → 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.
- package/README.md +23 -8
- package/dist/commands/config.js +4 -3
- package/dist/commands/config.js.map +2 -2
- package/dist/commands/install.js +5 -0
- package/dist/commands/install.js.map +2 -2
- package/dist/commands/login.js +2 -2
- package/dist/commands/login.js.map +2 -2
- package/dist/commands/pipeline.js +158 -0
- package/dist/commands/pipeline.js.map +7 -0
- package/dist/commands/pull.js +2 -1
- package/dist/commands/pull.js.map +2 -2
- package/dist/commands/run.js +9 -0
- package/dist/commands/run.js.map +2 -2
- package/dist/commands/variables.js +17 -8
- package/dist/commands/variables.js.map +2 -2
- package/dist/index.js +45 -46
- package/dist/index.js.map +2 -2
- package/dist/mcp/prompts/workflows.js +13 -68
- package/dist/mcp/prompts/workflows.js.map +2 -2
- package/dist/mcp/resources/documentation.js +14 -0
- package/dist/mcp/resources/documentation.js.map +2 -2
- package/dist/mcp/server.js +14 -2
- package/dist/mcp/server.js.map +2 -2
- package/dist/mcp/skills.js +59 -0
- package/dist/mcp/skills.js.map +7 -0
- package/dist/mcp/tools/appTools.js +4 -0
- package/dist/mcp/tools/appTools.js.map +2 -2
- package/dist/mcp/tools/authTools.js +5 -3
- package/dist/mcp/tools/authTools.js.map +2 -2
- package/dist/mcp/tools/cellTools.js +3 -2
- package/dist/mcp/tools/cellTools.js.map +2 -2
- package/dist/mcp/tools/dashboardTools.js +23 -18
- package/dist/mcp/tools/dashboardTools.js.map +2 -2
- package/dist/mcp/tools/dataTools.js +16 -12
- package/dist/mcp/tools/dataTools.js.map +2 -2
- package/dist/mcp/tools/folderTools.js +5 -4
- package/dist/mcp/tools/folderTools.js.map +2 -2
- package/dist/mcp/tools/modelTools.js +33 -58
- package/dist/mcp/tools/modelTools.js.map +2 -2
- package/dist/mcp/tools/pipelineContract.js +320 -0
- package/dist/mcp/tools/pipelineContract.js.map +7 -0
- package/dist/mcp/tools/pipelineTools.js +111 -0
- package/dist/mcp/tools/pipelineTools.js.map +7 -0
- package/dist/mcp/tools/runTools.js +10 -3
- package/dist/mcp/tools/runTools.js.map +2 -2
- package/dist/mcp/tools/sheetTools.js +21 -17
- package/dist/mcp/tools/sheetTools.js.map +2 -2
- package/dist/mcp/tools/syncTools.js +15 -5
- package/dist/mcp/tools/syncTools.js.map +2 -2
- package/dist/mcp/utils/registerTool.js +32 -0
- package/dist/mcp/utils/registerTool.js.map +7 -0
- package/dist/pipeline/compatibility.js +53 -0
- package/dist/pipeline/compatibility.js.map +7 -0
- package/dist/pipeline/connect.js +139 -0
- package/dist/pipeline/connect.js.map +7 -0
- package/dist/pipeline/create.js +158 -0
- package/dist/pipeline/create.js.map +7 -0
- package/dist/pipeline/errors.js +45 -0
- package/dist/pipeline/errors.js.map +7 -0
- package/dist/pipeline/generated-reference.json +115 -0
- package/dist/pipeline/guide.js +33 -0
- package/dist/pipeline/guide.js.map +7 -0
- package/dist/pipeline/init.js +204 -0
- package/dist/pipeline/init.js.map +7 -0
- package/dist/pipeline/operations.js +106 -0
- package/dist/pipeline/operations.js.map +7 -0
- package/dist/pipeline/query.js +121 -0
- package/dist/pipeline/query.js.map +7 -0
- package/dist/pipeline/queryDownloads.js +72 -0
- package/dist/pipeline/queryDownloads.js.map +7 -0
- package/dist/pipeline/queryWorker.js +96 -0
- package/dist/pipeline/queryWorker.js.map +7 -0
- package/dist/pipeline/readiness.js +62 -0
- package/dist/pipeline/readiness.js.map +7 -0
- package/dist/pipeline/reference.js +73 -0
- package/dist/pipeline/reference.js.map +7 -0
- package/dist/pipeline/requests.js +122 -0
- package/dist/pipeline/requests.js.map +7 -0
- package/dist/pipeline/runArguments.js +68 -0
- package/dist/pipeline/runArguments.js.map +7 -0
- package/dist/pipeline/runtime.js +106 -0
- package/dist/pipeline/runtime.js.map +7 -0
- package/dist/pipeline/service.js +1027 -0
- package/dist/pipeline/service.js.map +7 -0
- package/dist/services/agentApprovalFetch.js +86 -0
- package/dist/services/agentApprovalFetch.js.map +7 -0
- package/dist/services/appSyncService.js.map +1 -1
- package/dist/services/configService.js +40 -4
- package/dist/services/configService.js.map +2 -2
- package/dist/services/credentials.js +2 -0
- package/dist/services/credentials.js.map +2 -2
- package/dist/services/farseerService.js +33 -3
- package/dist/services/farseerService.js.map +2 -2
- package/dist/services/modelExport.js.map +1 -1
- package/dist/services/preflight.js +4 -0
- package/dist/services/preflight.js.map +2 -2
- package/dist/services/syncService.js +6 -0
- package/dist/services/syncService.js.map +2 -2
- package/dist/skills/pipeline.js +71 -0
- package/dist/skills/pipeline.js.map +7 -0
- package/dist/utils/agentSandbox.js +35 -0
- package/dist/utils/agentSandbox.js.map +7 -0
- package/dist/utils/helpers.js +2 -1
- package/dist/utils/helpers.js.map +2 -2
- package/dist/utils/variableValues.js +78 -0
- package/dist/utils/variableValues.js.map +7 -0
- package/docs/pipeline-client-guide.md +67 -0
- package/docs/pipeline-reference.md +2064 -0
- package/package.json +5 -1
- package/skills/pipeline-authoring/SKILL.md +95 -0
- package/skills/pipeline-authoring/practices.md +325 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/pipeline/service.ts"],
|
|
4
|
+
"sourcesContent": ["import { resolveRunArguments } from './runArguments';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { createHash, randomUUID } from 'crypto';\nimport { z } from 'zod';\nimport { FarseerService, RemoteFile } from '../services/farseerService';\nimport { SyncService, SyncState } from '../services/syncService';\nimport { DEFAULT_LIMITS, queryFiles } from './query';\nimport { PIPELINE_ENGINE_PROFILE, CLI_UPDATE_INSTRUCTION, engineReport } from './reference';\nimport { assertPipelineRuntime, compareRuntime, compareVersions, PIPELINE_RUNNER_IMAGE } from './runtime';\nimport { CLI_VERSION } from '../utils/constants';\nimport { resolveRunnerImage, type RemoteApp } from '../services/apps';\nimport { setTimeout as delay } from 'timers/promises';\nimport { boundedPipelineClient } from './requests';\nimport { probeParquetAccess, probeParquetPrefix } from './readiness';\nimport { PipelineError, httpStatus } from './errors';\nimport { inAgentSandbox } from '../utils/agentSandbox';\n\nconst relative = z\n .string()\n .min(1)\n .refine(\n (s) =>\n !s.includes('\\\\') &&\n !s.startsWith('/') &&\n s.split('/').every((p) => p && p !== '.' && p !== '..' && !p.startsWith('.')),\n 'Expected a non-hidden relative path',\n );\n// Owner statements, filled in by hand after init writes the blank record. The profile loads whatever\n// the owner has written so far, so a record part-way through never stops the other commands; only a\n// complete record passes check, and check names what is still missing.\nconst recordedSetupSchema = z\n .object({\n owner: z.string().min(1),\n checkedAt: z.string().datetime({ offset: true }),\n evidence: z.string().min(1),\n retentionDays: z.number().int().positive(),\n otherWritersExcluded: z.literal(true),\n runtimeVerified: z.literal(true),\n })\n .strict();\nexport const profileSchema = z\n .object({\n organisation: z.string().min(1),\n tenant: z.string().min(1),\n author: z.string().min(1).default('shared'),\n datasetIds: z.array(z.string().uuid()).max(100).default([]),\n jobId: z.number().int().positive(),\n sourceFolderId: z.number().int().positive(),\n workspace: relative,\n entrypoint: relative,\n /** Recorded by older profiles; the job's live image is what counts. */\n runnerImage: z.string().min(1).optional(),\n /** The job's schedule when init ran; null for none, absent in profiles from before this was recorded. */\n schedule: z.string().min(1).nullable().optional(),\n engine: z.string().min(1),\n configFiles: z.array(relative).default([]),\n setup: z.record(z.unknown()).optional(),\n })\n .strict();\nexport type PipelineProfile = z.infer<typeof profileSchema>;\nexport type RecordedSetup = z.infer<typeof recordedSetupSchema>;\nexport function readPipelineProfileFile(file: string): PipelineProfile {\n return profileSchema.parse(JSON.parse(fs.readFileSync(file, 'utf8')));\n}\nexport const BLANK_SETUP = {\n owner: '',\n checkedAt: '',\n evidence: '',\n retentionDays: 0,\n otherWritersExcluded: false,\n runtimeVerified: false,\n};\n/** The complete record, or the fields that keep it from being one, in the order the record lists them. */\nfunction readSetup(setup: PipelineProfile['setup']): { recorded: RecordedSetup } | { missing: string } {\n const parsed = recordedSetupSchema.safeParse(setup ?? {});\n if (parsed.success) return { recorded: parsed.data };\n const fields = parsed.error.issues.flatMap((issue) =>\n issue.code === 'unrecognized_keys'\n ? issue.keys.map((key) => `${key} (not a setup field)`)\n : [String(issue.path[0])],\n );\n return { missing: [...new Set(fields)].join(', ') };\n}\nexport interface Run {\n id: number;\n uuid: string;\n remoteJobId: number;\n status: string;\n logs: string[];\n startedAt: string;\n}\n/**\n * How far the laptop's clock may run ahead of the backend's before a run the backend admitted could\n * look older than the receipt that submitted it. Generous on purpose: a wider window only lists more\n * runs for the author to choose from, never clears a receipt whose run exists.\n */\nconst CLOCK_SKEW_MARGIN_MS = 10 * 60 * 1000;\nconst RECOVER_HINT =\n 'In a terminal, `farseer pipeline recover` clears the receipt if run history has no run since the submission, and `farseer pipeline recover --uuid <uuid>` attaches the run that is this submission.';\nexport type PipelineClient = FarseerService & {\n pipelineRequest<T>(method: 'GET' | 'POST', route: string, body?: unknown): Promise<T>;\n};\ntype Receipt = {\n organisation: string;\n tenant: string;\n jobId: number;\n workspace: string;\n author: string;\n submittedAt: string;\n phase: 'unconfirmed' | 'accepted';\n runUuid?: string;\n};\nconst terminal = (status: string) => ['FINISHED', 'ERROR'].includes(status);\nconst digest = (data: string | Buffer) => createHash('sha256').update(data).digest('hex');\n// The existing tenant-wide baseline is a shared mutable JSON file. Separate workspace\n// baselines prevent two simultaneous syncs from losing each other's recorded hashes.\nclass WorkspaceSync extends SyncService {\n constructor(\n tenant: string,\n client: FarseerService,\n private stateFile: string,\n ) {\n super(tenant, client);\n }\n loadSyncState(): SyncState {\n return fs.existsSync(this.stateFile)\n ? JSON.parse(fs.readFileSync(this.stateFile, 'utf8'))\n : { lastSync: '', files: {} };\n }\n saveSyncState(state: SyncState) {\n const tmp = `${this.stateFile}.${randomUUID()}`;\n fs.writeFileSync(tmp, JSON.stringify(state), { mode: 0o600 });\n fs.renameSync(tmp, this.stateFile);\n }\n}\n\n/** Every distinct `pipeline_args.NAME` the given source files reference, in first-seen order. */\nexport function pipelineArgumentNames(files: string[]): string[] {\n const names: string[] = [];\n for (const file of files) {\n if (!fs.existsSync(file)) continue;\n for (const match of fs.readFileSync(file, 'utf8').matchAll(/pipeline_args\\.([A-Za-z_][A-Za-z0-9_]*)/g))\n if (!names.includes(match[1])) names.push(match[1]);\n }\n return names;\n}\n\nexport const SCHEDULE_NOTE =\n 'Source you push runs at the next scheduled start. Verify it with run first, or pause the schedule for multi-step edits.';\n\n/**\n * A scheduled job is allowed, but its schedule must never be lost by accident: init records it,\n * and a schedule that has since been removed or changed fails check with the way back.\n */\nexport function scheduleCheck(recorded: string | null | undefined, live: string | null | undefined, jobId: number) {\n // init refuses force together with name, so the way back names the job.\n const restore = (cron: string) =>\n `Restore it with farseer_configure_app schedule=\"${cron}\" when done, or rerun init jobId=${jobId} force=true if the change was intended.`;\n if (recorded && !live)\n return {\n status: 'fail' as const,\n detail: `The job's schedule \"${recorded}\" was removed since init. ${restore(recorded)}`,\n };\n if (recorded && live && recorded !== live)\n return {\n status: 'fail' as const,\n detail: `The job's schedule changed from \"${recorded}\" to \"${live}\" since init. ${restore(recorded)}`,\n };\n if (live) return { status: 'pass' as const, detail: `Job runs on schedule \"${live}\". ${SCHEDULE_NOTE}` };\n return { status: 'pass' as const, detail: 'Job has no schedule' };\n}\n\n/** The engine's PIPELINE_VISUALIZATION_MARKER payloads in the given log lines, in order. */\nfunction parseMarkers(lines: string[]): Record<string, unknown>[] {\n return lines.flatMap((line) => {\n const pos = line.indexOf('PIPELINE_VISUALIZATION_MARKER');\n if (pos < 0) return [];\n try {\n return [JSON.parse(line.slice(line.indexOf('{', pos)))];\n } catch {\n return [{ event: 'unreadable_marker' }];\n }\n });\n}\n\nexport interface LoadOutcome {\n name: string;\n importId: number | null;\n outcome: string;\n}\n\n/**\n * Every import each load ran, in the order they ran, with its last reported outcome: commit_confirmed,\n * not_committed or unknown. A load runs one import per cells entry, all observed under the load's\n * name, so an import is told apart by its id. An import whose create failed is observed once, with\n * no id, and is an import of its own.\n */\nexport function loadOutcomes(markers: Record<string, unknown>[]): LoadOutcome[] {\n const loads: LoadOutcome[] = [];\n for (const m of markers) {\n if (m.event !== 'import_observation') continue;\n const name = String(m.name);\n const importId = typeof m.import_id === 'number' ? m.import_id : null;\n const known = importId === null ? undefined : loads.find((l) => l.name === name && l.importId === importId);\n if (known) known.outcome = String(m.outcome);\n else loads.push({ name, importId, outcome: String(m.outcome) });\n }\n return loads;\n}\n\nexport interface SkippedOutput {\n name: string;\n type: 'load' | 'export';\n reason: string;\n}\n\n/**\n * Loads and exports the run skipped. An optional source that is missing skips everything that\n * depends on it, and the run still finishes successfully, so this is the only place it shows.\n */\nexport function skippedOutputs(markers: Record<string, unknown>[]): SkippedOutput[] {\n const types = new Map<string, unknown>();\n for (const m of markers) if (m.event === 'dataset_registered') types.set(String(m.name), m.type);\n return markers.flatMap((m) => {\n const type = types.get(String(m.name));\n return m.event === 'step_skipped' && (type === 'load' || type === 'export')\n ? [{ name: String(m.name), type, reason: String(m.reason ?? '') }]\n : [];\n });\n}\n\nfunction skippedAttention(status: string, skipped: SkippedOutput[]): string {\n const count = (type: 'load' | 'export') => skipped.filter((s) => s.type === type).length;\n const phrase = (n: number, word: string) => (n ? `${n} ${word}${n > 1 ? 's' : ''}` : '');\n const parts = [phrase(count('load'), 'load'), phrase(count('export'), 'export')].filter(Boolean);\n const verb = skipped.length > 1 ? 'were' : 'was';\n const ended = status === 'FINISHED' ? 'Finished' : `Ended ${status}`;\n return `${ended}, but ${parts.join(' and ')} ${verb} skipped: ${skipped\n .map((s) => `${s.name} (${s.reason})`)\n .join(\n ', ',\n )}. Nothing reached the model or Files through them. While building a pipeline, treat this as a defect to fix.`;\n}\n\n/** The fields of a profile that decide which files are pipeline source. */\nexport type SourceScope = Pick<PipelineProfile, 'workspace' | 'entrypoint' | 'configFiles'>;\n\nexport function sourcePath(profile: SourceScope, file: string): boolean {\n if (!relative.safeParse(file).success || !file.startsWith(profile.workspace + '/')) return false;\n const inner = file.slice(profile.workspace.length + 1);\n if (inner.split('/').some((p) => ['Data', 'node_modules', '__pycache__'].includes(p))) return false;\n return (\n inner === profile.entrypoint ||\n profile.configFiles.includes(inner) ||\n (/^(Models|Code)\\//.test(inner) && /\\.(py|ya?ml|json|md)$/.test(inner))\n );\n}\n\n/** Workspace source files in the pull/push scope, as tenant-relative paths. */\nexport function localSourceFiles(profile: SourceScope, filesDir: string): string[] {\n const found: string[] = [];\n const walk = (dir: string, rel: string) => {\n if (!fs.existsSync(dir)) return;\n if (fs.lstatSync(dir).isSymbolicLink()) throw new Error(`Workspace symlinks are not supported: ${rel}`);\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (entry.name.startsWith('.') || ['Data', 'node_modules', '__pycache__'].includes(entry.name)) continue;\n const next = `${rel}/${entry.name}`;\n if (entry.isSymbolicLink()) throw new Error(`Workspace symlinks are not supported: ${next}`);\n if (entry.isDirectory()) walk(path.join(dir, entry.name), next);\n else if (sourcePath(profile, next)) found.push(next);\n }\n };\n // Check every ancestor as well; otherwise a linked parent escapes the workspace.\n let dir = filesDir;\n for (const part of profile.workspace.split('/')) {\n dir = path.join(dir, part);\n if (fs.existsSync(dir) && fs.lstatSync(dir).isSymbolicLink())\n throw new Error('Workspace symlinks are not supported');\n }\n walk(dir, profile.workspace);\n return found;\n}\n\nexport class PipelineService {\n readonly profile: PipelineProfile;\n readonly stateDir: string;\n private readonly operationDir: string;\n private readonly sync: SyncService;\n constructor(\n profile: PipelineProfile,\n private client: PipelineClient,\n private filesDir: string,\n stateRoot: string,\n sync?: SyncService,\n ) {\n this.client = boundedPipelineClient(client);\n this.profile = profileSchema.parse(profile);\n // The profile records the grammar line it was set up with. An older line of the same major\n // still opens after a CLI update: push checks the job's own runtime before anything is written.\n const grammar = /^(\\d+)\\.(\\d+)(?:\\.\\d+)?$/.exec(this.profile.engine)?.slice(1).map(Number);\n const [major, minor] = PIPELINE_ENGINE_PROFILE.split('.').map(Number);\n if (grammar && (grammar[0] > major || (grammar[0] === major && grammar[1] > minor)))\n throw new Error(\n `This CLI's bundled grammar is ${PIPELINE_ENGINE_PROFILE}; the profile was set up for ${this.profile.engine}. ${CLI_UPDATE_INSTRUCTION}`,\n );\n if (!grammar || grammar[0] < major)\n throw new Error(\n `The profile was set up for grammar ${this.profile.engine}, which this CLI (${PIPELINE_ENGINE_PROFILE}) does not continue. Set the profile up again with init jobId=${this.profile.jobId} force=true${inAgentSandbox() ? '' : `, or keep using the CLI release that targets ${this.profile.engine}`}.`,\n );\n if (!profile.entrypoint.endsWith('.py'))\n throw new PipelineError(\n 'refused',\n 'PIPELINE_ENTRYPOINT_UNSUPPORTED',\n 'Pipeline entrypoint must be Python. The existing app must be preserved.',\n 'Use the existing app tools to inspect, run or maintain this app. Do not replace its entrypoint; migration to Simple Pipelines requires an explicit migration request.',\n );\n // Local receipts/baselines are job-scoped, without server ownership.\n this.stateDir = path.join(stateRoot, digest(`${profile.organisation}/${profile.tenant}/${profile.jobId}`));\n this.operationDir = this.stateDir;\n fs.mkdirSync(this.stateDir, { recursive: true, mode: 0o700 });\n this.sync = sync ?? new WorkspaceSync(profile.tenant, this.client, path.join(this.stateDir, 'sync.json'));\n }\n async versions(datasetId: string) {\n z.string().uuid().parse(datasetId);\n const [dataset, versions] = await Promise.all([\n this.client.pipelineRequest('GET', `/labs/datasets/${datasetId}`),\n this.client.pipelineRequest('GET', `/labs/datasets/${datasetId}/versions`),\n ]);\n return { dataset, versions };\n }\n async check(signal?: AbortSignal) {\n const checks: { name: string; status: 'pass' | 'fail' | 'pending'; detail: string }[] = [];\n const attempt = async (name: string, fn: () => Promise<string>) => {\n signal?.throwIfAborted();\n try {\n checks.push({ name, status: 'pass', detail: await fn() });\n } catch (error) {\n signal?.throwIfAborted();\n checks.push({ name, status: 'fail', detail: redact(String(error)) });\n }\n };\n await attempt('prepared-job', async () => {\n await this.verifyJob();\n return 'Job, entrypoint and source folder match';\n });\n let job: RemoteApp | null = null;\n try {\n signal?.throwIfAborted();\n job = await this.client.getApp(String(this.profile.jobId));\n if (job)\n checks.push({\n name: 'schedule',\n ...scheduleCheck(this.profile.schedule, job.schedule, this.profile.jobId),\n });\n const runtime = compareRuntime(job?.runnerImage ?? '');\n checks.push({\n name: 'runner-image',\n status:\n runtime.status === 'match'\n ? 'pass'\n : runtime.status === 'behind' || runtime.status === 'incompatible'\n ? 'fail'\n : 'pending',\n detail:\n runtime.status === 'match'\n ? `Job runs ${PIPELINE_RUNNER_IMAGE}, the image this CLI authors for`\n : runtime.nextAction,\n });\n } catch (error) {\n signal?.throwIfAborted();\n checks.push({ name: 'runner-image', status: 'fail', detail: redact(String(error)) });\n }\n // Secrets reach a pipeline only through job arguments the YAML names as\n // {{ pipeline_args.NAME }}; a name the job does not define fails at run time.\n if (job) {\n const used = pipelineArgumentNames(this.localSources().map((f) => path.join(this.filesDir, f)));\n const defined = new Set((job.expectedArguments ?? []).map((a) => a.name));\n const unset = used.filter((name) => !defined.has(name));\n // main.py may compute an argument and write it into FARSEER_ARGS before run_pipeline\n // (the practices guide's pattern for a canonical MONTH); that one exists at run time.\n const entry = path.join(this.filesDir, this.profile.workspace, this.profile.entrypoint);\n const setByMain = setArgumentNames(fs.existsSync(entry) ? fs.readFileSync(entry, 'utf8') : '');\n const missing = unset.filter((name) => !setByMain.has(name));\n const derived = unset.filter((name) => setByMain.has(name));\n checks.push(\n missing.length\n ? {\n name: 'job-arguments',\n status: 'fail',\n detail: `The source uses pipeline_args ${missing.join(', ')} but the job defines no such argument. Add each one to the job (secret: true for keys and passwords) with farseer_configure_app or in the web app, then set its value.`,\n }\n : derived.length\n ? {\n name: 'job-arguments',\n status: 'pending',\n detail: `${derived.join(', ')} ${derived.length === 1 ? 'is' : 'are'} not job arguments: main.py sets ${derived.length === 1 ? 'it' : 'them'} before run_pipeline, so ${derived.length === 1 ? 'it is' : 'they are'} not checked here. Make sure main.py sets ${derived.length === 1 ? 'it' : 'them'} on every path. The job defines the rest.`,\n }\n : {\n name: 'job-arguments',\n status: 'pass',\n detail: used.length\n ? `Job defines every argument the source uses (${used.join(', ')})`\n : 'Source uses no job arguments',\n },\n );\n }\n // The engine creates a dataset on its first write, so a profile without IDs is\n // a pipeline that has not run yet, not a broken setup.\n const models = this.localSources().filter((f) => /\\/Models\\/.+\\.ya?ml$/.test(f));\n if (!this.profile.datasetIds.length)\n checks.push({\n name: 'declared-outputs',\n status: 'pending',\n detail: models.length\n ? `No output dataset IDs recorded yet; datasets are created on the first run. After it, rerun init jobId=${this.profile.jobId} force=true to record their IDs.`\n : 'No dataset YAML under Models/ yet. Write the first one there: the guide topics FarseerFilesExtractConfig, TransformConfig and LoadCellsConfig each end with a complete example.',\n });\n else\n await attempt('declared-outputs', async () => {\n return `${this.profile.datasetIds.length} prepared output(s); this is configuration, not an ownership lock`;\n });\n let latestCli: string | undefined;\n try {\n signal?.throwIfAborted();\n ({ latestCliVersion: latestCli } = await this.client.pipelineRequest<{ latestCliVersion?: string }>(\n 'GET',\n '/pipelineAuthoring',\n ));\n } catch (error) {\n signal?.throwIfAborted();\n checks.push({ name: 'cli-version', status: 'fail', detail: redact(String(error)) });\n }\n if (latestCli !== undefined)\n checks.push(\n compareVersions(CLI_VERSION, latestCli) < 0\n ? {\n name: 'cli-version',\n status: 'pending',\n detail: `CLI ${CLI_VERSION} is installed; ${latestCli} is the CLI released with this tenant's current runner image. ${CLI_UPDATE_INSTRUCTION}`,\n }\n : { name: 'cli-version', status: 'pass', detail: `CLI ${CLI_VERSION} is current` },\n );\n for (const datasetId of this.profile.datasetIds) {\n await attempt(`dataset:${datasetId}`, async () => {\n const dataset = await this.client.pipelineRequest<{ id: string; currentVersionId?: string | null }>(\n 'GET',\n `/labs/datasets/${datasetId}`,\n );\n if (dataset.id !== datasetId) throw new Error('Dataset identity did not match');\n if (!dataset.currentVersionId) {\n checks.push({\n name: `signed-read:${datasetId}`,\n status: 'pending',\n detail: 'No published version yet. Complete the prepared first run, then check again.',\n });\n return 'Prepared dataset exists; it has no current version';\n }\n const manifest = await this.client.pipelineRequest<{\n files: { filename: string; size: number; signedUrl: string }[];\n }>('GET', `/labs/datasets/${datasetId}/versions/${dataset.currentVersionId}/downloadUrls`);\n if (\n !manifest.files?.length ||\n manifest.files.length > 512 ||\n manifest.files.some(\n (f) => !f.filename.endsWith('.parquet') || !Number.isSafeInteger(f.size) || f.size < 0,\n )\n )\n throw new Error('A complete supported Parquet manifest is required');\n const bytes = manifest.files.reduce((sum, f) => sum + f.size, 0);\n if (bytes > DEFAULT_LIMITS.inputBytes)\n throw new Error(\n 'This version exceeds the 256 MiB query download limit; prepare a smaller pipeline output',\n );\n // A sandbox reaches only the API, so a turn key probes through it, as query does.\n const versionId = dataset.currentVersionId;\n const first = manifest.files[0];\n if (this.client.agentSession)\n await probeParquetPrefix((probeSignal) =>\n this.client.downloadDatasetVersionFile(datasetId, versionId, first.filename, probeSignal),\n );\n else await probeParquetAccess(first.signedUrl);\n const access = this.client.agentSession ? 'Read through the API' : 'Signed GET';\n return `Version ${versionId}: ${manifest.files.length} Parquet file(s), ${bytes} bytes. ${access} verified on the first file; full-query performance is not established by this probe.`;\n });\n }\n const automatedReady = checks.every((c) => c.status === 'pass');\n const setup = readSetup(this.profile.setup);\n checks.push(\n 'recorded' in setup\n ? {\n name: 'setup-evidence',\n status: 'pass',\n detail: `Recorded by ${setup.recorded.owner} at ${setup.recorded.checkedAt}: ${setup.recorded.retentionDays} days retention, other writers excluded, runtime contents verified. Evidence: ${setup.recorded.evidence}. Reconfirm after setup changes; these are owner statements, not API-verified facts.`,\n }\n : {\n name: 'setup-evidence',\n status: 'pending',\n detail: `Setup owner must record runtime verification, agreed retention and exclusion of other writers in the profile setup field. Not yet recorded: ${setup.missing}. This command cannot verify them from the APIs.`,\n },\n );\n return {\n tenant: this.profile.tenant,\n jobId: this.profile.jobId,\n automatedReady,\n readyForAcceptance: checks.every((c) => c.status === 'pass'),\n checks,\n limits: DEFAULT_LIMITS,\n remainingAcceptance:\n 'Run the two-person client exercise and the configured source/reconciliation task. This read-only check does not validate source credentials, replay, business results or client-provider agreements.',\n };\n }\n async queryVersions(\n bindings: { name: string; datasetId: string; versionId: string }[],\n sql: string,\n signal?: AbortSignal,\n ) {\n z.array(\n z\n .object({\n name: z.string().regex(/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/),\n datasetId: z.string().uuid(),\n versionId: z.string().uuid(),\n })\n .strict(),\n )\n .min(1)\n .max(16)\n .parse(bindings);\n if (new Set(bindings.map((b) => b.name.toLowerCase())).size !== bindings.length)\n throw new Error('SQL binding names must be distinct');\n type VersionFile = { filename: string; size: number; signedUrl: string };\n // Typed, not inferred: the sandbox download callback below reads it, and strict tsc cannot\n // infer an empty array's element type inside a callback.\n const inputs: ((typeof bindings)[number] & { files: VersionFile[] })[] = [];\n for (const b of bindings) {\n const result = await this.client.pipelineRequest<{\n files: VersionFile[];\n }>('GET', `/labs/datasets/${b.datasetId}/versions/${b.versionId}/downloadUrls`);\n if (!result.files?.length || result.files.some((f) => !f.filename.endsWith('.parquet')))\n throw new Error('This version has no supported Parquet contents');\n inputs.push({ ...b, files: result.files });\n }\n const total = inputs.reduce((sum, b) => sum + b.files.reduce((n, f) => n + f.size, 0), 0);\n if (total > DEFAULT_LIMITS.inputBytes) throw new Error('Input download byte limit exceeded');\n const result = await queryFiles(\n {\n bindings: inputs.map((b) => ({ name: b.name, urls: b.files.map((f) => f.signedUrl) })),\n sql,\n limits: DEFAULT_LIMITS,\n },\n signal,\n this.client.agentSession\n ? (binding, file, downloadSignal) => {\n const input = inputs[binding];\n return this.client.downloadDatasetVersionFile(\n input.datasetId,\n input.versionId,\n input.files[file].filename,\n downloadSignal,\n );\n }\n : undefined,\n );\n return {\n ...result,\n tenant: this.profile.tenant,\n semantics: 'explicit immutable dataset versions',\n inputs: inputs.map(({ files, ...binding }) => ({\n ...binding,\n files: files.map(({ signedUrl: _url, ...file }) => file),\n })),\n };\n }\n async restore(datasetId: string, versionId: string, expectedCurrentVersionId: string) {\n [datasetId, versionId, expectedCurrentVersionId].forEach((id) => z.string().uuid().parse(id));\n if (!this.profile.datasetIds.includes(datasetId))\n throw new PipelineError(\n 'refused',\n 'RESTORE_SCOPE',\n 'Restore only a declared output dataset',\n 'Use an output dataset from the prepared profile.',\n );\n return this.exclusive(async () => {\n await this.idle();\n let dataset: unknown;\n try {\n dataset = await this.client.pipelineRequest(\n 'POST',\n `/labs/datasets/${datasetId}/versions/${versionId}/restore`,\n { expectedCurrentVersionId },\n );\n } catch (error) {\n const refused = [400, 401, 403, 404, 409].includes(httpStatus(error) ?? 0);\n throw new PipelineError(\n refused ? 'refused' : 'unknown',\n refused ? 'RESTORE_REFUSED' : 'RESTORE_UNCONFIRMED',\n redact(String(error)),\n 'Read versions and current dataset state before any further restore. Do not blindly retry.',\n );\n }\n return {\n dataset,\n note: 'A state-changing restore also cancels outstanding unpublished candidates and restores the matching reading position. Inspect model imports separately.',\n };\n });\n }\n private receipt(): Receipt | undefined {\n const name = path.join(this.stateDir, 'current.json');\n return fs.existsSync(name) ? JSON.parse(fs.readFileSync(name, 'utf8')) : undefined;\n }\n private save(receipt: Receipt) {\n const tmp = path.join(this.stateDir, randomUUID());\n fs.writeFileSync(tmp, JSON.stringify(receipt, null, 2), { mode: 0o600 });\n fs.renameSync(tmp, path.join(this.stateDir, 'current.json'));\n if (receipt.runUuid)\n fs.writeFileSync(path.join(this.stateDir, `${receipt.runUuid}.json`), JSON.stringify(receipt), {\n mode: 0o600,\n });\n }\n private async exclusive<T>(fn: () => Promise<T>): Promise<T> {\n const name = path.join(this.operationDir, 'operation.lock');\n let fd: number;\n try {\n fd = fs.openSync(name, 'wx', 0o600);\n } catch (error: any) {\n if (error.code !== 'EEXIST') throw error;\n throw new PipelineError(\n 'refused',\n 'PIPELINE_LOCAL_BUSY',\n 'Workspace operation in progress. An abandoned lock requires local recovery; do not resubmit.',\n 'Inspect the existing local command; use CLI recovery only after its process has stopped.',\n );\n }\n fs.writeFileSync(fd, String(process.pid));\n fs.closeSync(fd);\n try {\n return await fn();\n } finally {\n fs.unlinkSync(name);\n }\n }\n /**\n * Ends a queued run of this job: one a runner never started, which would otherwise stay queued\n * in the job's history. A running run is refused: stopping work part-way is a person's call, made\n * with Stop in the web app. The result reads the run back, so it says whether the run closed.\n */\n async terminate(uuid: string): Promise<{ runUuid: string; status: string; terminated: boolean; note?: string }> {\n z.string().uuid().parse(uuid);\n const run = await this.findRun(uuid);\n if (!run)\n throw new PipelineError(\n 'refused',\n 'RUN_NOT_FOUND',\n `Run ${uuid} is not a run of job ${this.profile.jobId}.`,\n 'Take the run UUID from runs or from the refusal that named it.',\n );\n if (run.status === 'RUNNING')\n throw new PipelineError(\n 'refused',\n 'RUN_NOT_QUEUED',\n `Run ${uuid} is running. Stopping a run part-way is a person's call. Nothing was sent.`,\n 'Ask a person to stop it with Stop in the web app, then wait for it to end. Do not retry terminate.',\n uuid,\n );\n if (run.status !== 'QUEUED')\n throw new PipelineError(\n 'refused',\n 'RUN_NOT_QUEUED',\n `Run ${uuid} has already ended (${run.status}).`,\n 'Nothing to terminate; inspect it if you need its outcome.',\n uuid,\n );\n try {\n await this.client.pipelineRequest('POST', `/remoteJobs/${this.profile.jobId}/cancelQueued/${uuid}`);\n } catch (error) {\n if (httpStatus(error) === 409)\n throw new PipelineError(\n 'refused',\n 'RUN_NOT_QUEUED',\n `Run ${uuid} started before cancellation. It was not stopped.`,\n 'Ask a person to stop it with Stop in the web app. Do not retry terminate.',\n uuid,\n );\n if (httpStatus(error) === 404 || httpStatus(error) === 405)\n throw new PipelineError(\n 'refused',\n 'QUEUED_CANCELLATION_UNAVAILABLE',\n 'Queued-only cancellation is unavailable, or the job or run no longer exists.',\n 'Inspect the run and check that the backend supports queued-only cancellation. Do not fall back to the general Stop endpoint.',\n uuid,\n );\n throw error;\n }\n const status = (await this.findRun(uuid))?.status ?? 'unknown';\n if (status !== 'QUEUED')\n return { runUuid: uuid, status, terminated: status === 'ERROR' || status === 'FINISHED' };\n return {\n runUuid: uuid,\n status,\n terminated: false,\n note: 'The termination was sent, but the run is still queued. Check it again with inspect; if it stays queued, ask a person to look at it in the web app.',\n };\n }\n async findRun(uuid: string): Promise<Run | undefined> {\n if (!/^[a-f0-9-]{36}$/i.test(uuid)) throw new Error('Invalid run UUID');\n return (await this.history()).find((r) => r.uuid === uuid);\n }\n private async history(): Promise<Run[]> {\n const runs = await this.client.pipelineRequest<Run[]>('GET', `/remoteJobs/${this.profile.jobId}/remoteJobRuns`);\n return runs.filter((r) => r.remoteJobId === this.profile.jobId);\n }\n private async idle(requireRun = false) {\n const receipt = this.receipt();\n if (!receipt) {\n if (requireRun) throw new Error('Run this workspace before querying outputs');\n return;\n }\n if (!receipt.runUuid)\n throw new PipelineError(\n 'unknown',\n 'SUBMISSION_UNCONFIRMED',\n `Submission outcome unknown; no automatic retry. ${RECOVER_HINT}`,\n 'Ask the author to run farseer pipeline recover in a terminal: it clears the receipt when history shows no run was accepted, or attaches the exact run with --uuid. Do not resubmit.',\n );\n const run = await this.findRun(receipt.runUuid);\n if (!run || !terminal(run.status))\n throw new PipelineError(\n run ? 'refused' : 'unknown',\n run ? 'RUN_ACTIVE' : 'RUN_UNCONFIRMED',\n `Workspace run ${receipt.runUuid} is ${run?.status ?? 'unconfirmed'}`,\n 'Inspect this run by UUID before any further changes or submission.',\n receipt.runUuid,\n );\n }\n private async verifyJob() {\n const p = this.profile;\n const job = await this.client.getApp(String(p.jobId));\n // Check the live family before reporting setup drift: a TypeScript app must not\n // be reconfigured back to the profile's Python entrypoint as a \"repair\".\n if (job) assertPipelineRuntime(job.runnerImage ?? '');\n const folder = await this.client.resolveSourceFolder(p.workspace);\n if (\n !job ||\n !folder ||\n job.sourceFolderId !== p.sourceFolderId ||\n folder.id !== p.sourceFolderId ||\n !folder.scripts.some((s) => s.id === job.mainScriptFileId && s.name === p.entrypoint)\n ) {\n throw new PipelineError(\n 'refused',\n 'SETUP_CHANGED',\n 'Prepared job, entrypoint or workspace changed. Repair pipeline setup before continuing.',\n 'Ask the setup owner to reconcile the prepared job and profile before continuing.',\n );\n }\n return job;\n }\n /** Workspace source files in the pull/push scope, as tenant-relative paths. */\n localSources(): string[] {\n return localSourceFiles(this.profile, this.filesDir);\n }\n /** The job's run history, newest first, with whether a local receipt names each run. */\n async runs(limit = 20) {\n z.number().int().positive().parse(limit);\n const history = await this.client.pipelineRequest<(Run & { startedAt: string; finishedAt?: string })[]>(\n 'GET',\n `/remoteJobs/${this.profile.jobId}/remoteJobRuns`,\n );\n const runs = history\n .filter((r) => r.remoteJobId === this.profile.jobId)\n .sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt) || b.id - a.id)\n .slice(0, limit)\n .map((r) => ({\n uuid: r.uuid,\n status: r.status,\n startedAt: r.startedAt,\n ...(r.finishedAt ? { finishedAt: r.finishedAt } : {}),\n receipt: fs.existsSync(path.join(this.stateDir, `${r.uuid}.json`)),\n }));\n return { tenant: this.profile.tenant, jobId: this.profile.jobId, runs };\n }\n private async sources() {\n const local = this.localSources();\n const remote = (await this.client.listFiles(['Files', ...this.profile.workspace.split('/')])).filter((f) =>\n sourcePath(this.profile, f.path),\n );\n const onlyFiles = [\n ...new Set([\n ...local,\n ...remote.map((f) => f.path),\n ...Object.keys(this.sync.loadSyncState().files).filter((f) => sourcePath(this.profile, f)),\n ]),\n ];\n if (!onlyFiles.length) throw new Error('Empty source scope; refusing tenant-wide fallback');\n return { local, remote, onlyFiles };\n }\n async syncSources(direction: 'pull' | 'push') {\n return this.exclusive(async () => {\n await this.idle();\n const job = await this.verifyJob();\n // Source written with this CLI's grammar may use what an older engine does not know.\n const runtime = compareRuntime(job.runnerImage ?? '');\n if (direction === 'push' && runtime.status === 'behind')\n throw new PipelineError(\n 'refused',\n 'RUNTIME_UPGRADE_REQUIRED',\n `The job runs ${job.runnerImage}, older than ${PIPELINE_RUNNER_IMAGE} this CLI authors for. Nothing was pushed.`,\n runtime.nextAction,\n );\n // Nothing here keeps this CLI's source off another engine major on a newer image or a moving\n // tag: the tag does not show the engine major (runner 1.12.2 runs engine 2.9), and\n // minimumCliVersion is not tied to it. Before an engine major ships, the engine must refuse\n // source that does not declare that major.\n const { onlyFiles } = await this.sources();\n // Calls file sync directly: never the generic MCP push that also updates apps.\n let result: Awaited<ReturnType<SyncService['push']>> | Awaited<ReturnType<SyncService['pull']>>;\n try {\n result = await (direction === 'pull' ? this.sync.pull({ onlyFiles }) : this.sync.push({ onlyFiles }));\n } catch (error) {\n throw new PipelineError(\n 'unknown',\n 'SYNC_INCOMPLETE',\n redact(String(error)),\n 'Some files may already have changed. Pull and reconcile source differences before running.',\n );\n }\n // On a scheduled job a push is a deploy: say so in the result the author reads.\n return direction === 'push' && job.schedule\n ? { ...result, schedule: { cron: job.schedule, note: SCHEDULE_NOTE } }\n : result;\n });\n }\n /**\n * Move the job to the image this CLI authors for. Only a job behind it moves: a job on a\n * moving tag or digest may already run a newer engine, and a job ahead needs a newer CLI.\n */\n async upgradeRuntime(): Promise<{\n jobId: number;\n from: string;\n to: string;\n changed: boolean;\n schedule?: { cron: string; note: string };\n }> {\n return this.exclusive(async () => {\n await this.idle();\n const job = await this.verifyJob();\n const from = job.runnerImage ?? '';\n const runtime = compareRuntime(from);\n if (runtime.status === 'match') return { jobId: job.id, from, to: from, changed: false };\n if (runtime.status === 'ahead')\n throw new PipelineError(\n 'refused',\n 'CLI_UPDATE_REQUIRED',\n `The job runs ${from}, newer than ${PIPELINE_RUNNER_IMAGE} this CLI authors for.`,\n CLI_UPDATE_INSTRUCTION,\n );\n if (runtime.status !== 'behind')\n throw new PipelineError(\n 'refused',\n 'RUNTIME_UNVERSIONED',\n `The job runs ${from}, a moving tag or digest, so this CLI cannot tell whether ${PIPELINE_RUNNER_IMAGE} is older or newer.`,\n 'Leave the job on its image, or pin an exact image deliberately in the web app.',\n );\n const image = resolveRunnerImage(PIPELINE_RUNNER_IMAGE, await this.client.getRunnerImageRepositories());\n if ('error' in image) throw new Error(image.error);\n try {\n await this.client.updateApp(String(job.id), { runnerImage: image.image }, job);\n } catch (error) {\n // A 4xx changed nothing. Anything else may have saved the new image, and a scheduled\n // job would then run it at its next start, so the outcome is unknown, not failed.\n const status = httpStatus(error) ?? 0;\n if (status >= 400 && status < 500)\n throw new PipelineError(\n 'refused',\n 'RUNTIME_UPGRADE_REFUSED',\n `The backend refused the image change; the job stays on ${from}. ${redact(String(error))}`,\n 'Read the reason, fix the setup it names or ask the setup owner, then try again.',\n );\n throw new PipelineError(\n 'unknown',\n 'RUNTIME_UPGRADE_UNCONFIRMED',\n `The image change may have been saved: the job is on ${from} or ${image.image}. ${redact(String(error))}`,\n \"Run check to read the job's image before anything else. Do not retry blindly.\",\n );\n }\n const moved = { jobId: job.id, from, to: image.image, changed: true };\n return job.schedule\n ? {\n ...moved,\n schedule: {\n cron: job.schedule,\n note: 'The next scheduled run uses the new engine with the source already on the tenant. Run it once now to see what the new engine refuses.',\n },\n }\n : moved;\n });\n }\n async submit(args: string[] = []) {\n z.array(z.string()).parse(args);\n return this.exclusive(async () => {\n await this.idle();\n // A scheduled run or another workspace's: no receipt here names it, and nothing on the\n // backend refuses a second run of the job. Read just before submitting, so not a lock.\n const active = (await this.history()).find((r) => !terminal(r.status));\n if (active)\n throw new PipelineError(\n 'refused',\n 'RUN_ACTIVE',\n `Run ${active.uuid} of job ${this.profile.jobId} is ${active.status} (startedAt ${active.startedAt}), and a second run would overlap it. No receipt here names it, so it is the schedule's or a colleague's.`,\n \"Wait until runs shows it ended, then run again. Ask the user before terminating it: a run waiting behind other jobs in the runner's queue also stays queued with no start in its log. Do not retry run while it is active.\",\n active.uuid,\n );\n const job = await this.verifyJob();\n const runArguments = resolveRunArguments(job.expectedArguments ?? [], args);\n const { local, remote } = await this.sources();\n const differences: string[] = [];\n for (const file of new Set([...local, ...remote.map((f) => f.path)])) {\n const reference = remote.find((r) => r.path === file);\n if (\n !local.includes(file) ||\n !reference ||\n digest(fs.readFileSync(path.join(this.filesDir, file))) !==\n digest(await this.client.getFileContentAsBuffer(reference.reference))\n )\n differences.push(file);\n }\n if (!local.includes(`${this.profile.workspace}/${this.profile.entrypoint}`))\n differences.push(this.profile.entrypoint);\n if (differences.length)\n throw new PipelineError(\n 'refused',\n 'UNSYNCED_SOURCES',\n `Unsynced source files: ${differences.join(', ')}`,\n 'Pull and reconcile the listed source files, then push the intended changes before running.',\n );\n const { organisation, tenant, jobId, workspace, author } = this.profile;\n const receipt: Receipt = {\n organisation,\n tenant,\n jobId,\n workspace,\n author,\n submittedAt: new Date().toISOString(),\n phase: 'unconfirmed',\n };\n const previousReceipt = this.receipt();\n this.save(receipt); // Before POST: a lost response must survive client restart.\n let result: { runUuid: string };\n try {\n result = await this.client.pipelineRequest<{ runUuid: string }>('POST', `/remoteJobs/${jobId}/run`, {\n arguments: runArguments.positional,\n });\n } catch (error: any) {\n const status = httpStatus(error);\n // Every 4xx is the backend refusing before any runner received the job: permissions,\n // validation, or no runner to dispatch to (the backend closes the recorded row in that\n // case). No run was accepted, so keep the previous receipt.\n if (status >= 400 && status < 500) {\n if (previousReceipt) this.save(previousReceipt);\n else fs.rmSync(path.join(this.stateDir, 'current.json'), { force: true });\n const reason = error.response?.data?.message ?? String(error);\n throw new PipelineError(\n 'refused',\n 'REQUEST_REFUSED',\n `Submission refused by the backend (HTTP ${status}). No new run was accepted. ${redact(String(reason))}`,\n 'Read the reason, fix the setup it names or ask the setup owner, then run again.',\n );\n }\n throw new PipelineError(\n 'unknown',\n 'SUBMISSION_UNCONFIRMED',\n `Submission outcome unconfirmed; the receipt was saved. ${RECOVER_HINT} ${redact(String(error))}`,\n 'Ask the author to run farseer pipeline recover in a terminal: it clears the receipt when history shows no run was accepted, or attaches the exact run with --uuid. Do not resubmit.',\n );\n }\n if (!result?.runUuid || !/^[a-f0-9-]{36}$/i.test(result.runUuid))\n throw new PipelineError(\n 'unknown',\n 'SUBMISSION_UNCONFIRMED',\n 'Backend did not return a run UUID; submission remains unconfirmed',\n 'Ask the author to run farseer pipeline recover in a terminal: it clears the receipt when history shows no run was accepted, or attaches the exact run with --uuid. Do not resubmit.',\n );\n try {\n this.save({ ...receipt, runUuid: result.runUuid, phase: 'accepted' });\n } catch (error) {\n throw new PipelineError(\n 'unknown',\n 'RECEIPT_SAVE_FAILED',\n `Run accepted but its local receipt could not be updated. ${redact(String(error))}`,\n 'Save this runUuid and inspect it. Do not resubmit.',\n result.runUuid,\n );\n }\n return {\n ...receipt,\n ...result,\n phase: 'accepted',\n observation: 'pending',\n arguments: runArguments.given,\n };\n });\n }\n async inspect(uuid = this.receipt()?.runUuid, offset = 0) {\n z.number().int().nonnegative().parse(offset);\n const receipt = this.receipt();\n // Only a receipt is a submission whose outcome can be unconfirmed; with none there is no run.\n if (!uuid && !receipt)\n throw new PipelineError(\n 'refused',\n 'NO_RUN_RECORDED',\n 'No run has been submitted from this profile, so there is no run to inspect.',\n 'Pass a uuid from runs to inspect an earlier run, or run the pipeline.',\n );\n if (!uuid) return { status: 'unconfirmed', receipt };\n const run = await this.findRun(uuid);\n if (!run) return { runUuid: uuid, status: 'unconfirmed', receipt: this.receipt() };\n const logs = run.logs ?? [];\n const page: string[] = [];\n let bytes = 0;\n let next = Math.max(0, offset);\n for (; next < logs.length && page.length < 100; next++) {\n const line = redact(logs[next]).slice(0, 4000);\n if (bytes + Buffer.byteLength(line) > 32_000) break;\n page.push(line);\n bytes += Buffer.byteLength(line);\n }\n // Markers come from the whole log, not the page: what each load did, and what was skipped,\n // must be answered by the first call, wherever in the log the run printed it.\n const observations = parseMarkers(logs.map((line) => redact(line).slice(0, 4000)));\n const skipped = skippedOutputs(observations);\n return {\n tenant: this.profile.tenant,\n workspace: this.profile.workspace,\n jobId: this.profile.jobId,\n runUuid: uuid,\n status: run.status,\n logs: page,\n observations,\n engine: engineReport(observations),\n loads: loadOutcomes(observations),\n skippedOutputs: skipped,\n ...(skipped.length ? { attention: skippedAttention(run.status, skipped) } : {}),\n // Until the run ends more lines can come, so null means the run ended and nothing is left.\n nextOffset: next < logs.length || !terminal(run.status) ? next : null,\n // From what this run reported, not the profile: before init records dataset IDs, a run\n // that writes datasets still reports their versions and never an output_written marker.\n outputSemantics: observations.some((o) => String(o.event).startsWith('dataset_'))\n ? 'version identifiers are reported in dataset observations'\n : observations.some((o) => o.event === 'output_written')\n ? 'current files; writes require an observed output_written marker'\n : 'no output markers observed yet',\n };\n }\n async query(bindings: { name: string; file: string }[], sql: string, signal?: AbortSignal) {\n z.array(z.object({ name: z.string().regex(/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/), file: relative }).strict())\n .min(1)\n .max(16)\n .parse(bindings);\n if (new Set(bindings.map((b) => b.name.toLowerCase())).size !== bindings.length)\n throw new Error('SQL binding names must be distinct');\n return this.exclusive(async () => {\n await this.idle(true);\n const inputs: (RemoteFile & { name: string; url: string })[] = [];\n for (const binding of bindings) {\n relative.parse(binding.file);\n if (!binding.file.startsWith('Data/') || !binding.file.endsWith('.parquet'))\n throw new Error('Query inputs must be Parquet files under this workspace\u2019s Data/');\n const file = await this.client.getFileByPath(`${this.profile.workspace}/${binding.file}`);\n if (!file || file.path !== `${this.profile.workspace}/${binding.file}`)\n throw new Error('Workspace output not found');\n // A sandbox reaches only the API, so a turn key reads the file through it instead.\n let url = `farseer-file:${file.reference}`;\n if (!this.client.agentSession) {\n const access = await this.client.pipelineRequest<{ url: string }>(\n 'GET',\n `/farseerFiles/${encodeURIComponent(file.reference)}/downloadUrl`,\n );\n if (!access?.url?.startsWith('https://')) throw new Error('Signed object read access unavailable');\n url = access.url;\n }\n inputs.push({\n ...file,\n metadata: (await this.client.getFileMetadata(file.reference)) ?? undefined,\n name: binding.name,\n url,\n });\n }\n // The API's file route buffers a whole file before its first byte, which the streaming cap\n // cannot stop, so refuse on the recorded sizes first. A missing size falls back to that cap.\n const total = inputs.reduce((sum, input) => sum + (input.metadata?.size ?? 0), 0);\n if (total > DEFAULT_LIMITS.inputBytes) throw new Error('Input download byte limit exceeded');\n const result = await queryFiles(\n { bindings: inputs, sql, limits: DEFAULT_LIMITS },\n signal,\n this.client.agentSession\n ? (binding, _file, downloadSignal) =>\n this.client.downloadFarseerFile(inputs[binding].reference, downloadSignal)\n : undefined,\n );\n return {\n ...result,\n tenant: this.profile.tenant,\n workspace: this.profile.workspace,\n queryTime: new Date().toISOString(),\n semantics: 'current-file read; not a historical run snapshot',\n inputs: inputs.map(({ url: _url, ...file }) => file),\n };\n });\n }\n async inspectImport(importId: number) {\n z.number().int().positive().parse(importId);\n const job = await this.client\n .pipelineRequest<{\n id: number;\n title: string;\n status: string;\n createdAt: string;\n }>('GET', `/importJobs/${importId}`)\n .catch((error) => {\n // A later run's undo_previous deletes the earlier import, so its ID then answers 404.\n if (httpStatus(error) !== 404) throw error;\n throw new PipelineError(\n 'refused',\n 'IMPORT_NOT_FOUND',\n `Import ${importId} does not exist on ${this.profile.tenant}.`,\n \"A later run's undo_previous may have removed it: look for import_undone in that run's inspect, and read the import it committed instead. Do not retry.\",\n );\n });\n return {\n tenant: this.profile.tenant,\n importId: job.id,\n title: redact(job.title).slice(0, 500),\n status: job.status,\n createdAt: job.createdAt,\n commitConfirmed: job.status === 'COMMITED',\n note: 'An uncommitted status does not rule out an in-flight commit. Inspect before retrying; no automatic retry.',\n };\n }\n /**\n * Direct CLI recovery only, after the author resolves submission uncertainty in history. With a\n * uuid, attach that run. Without one, clear a receipt whose submission history shows was never\n * accepted: the backend records an admitted run before dispatching it, so no run of this job since\n * the submission means none was accepted. Any run in that window is listed, never guessed at.\n */\n async recover(uuid?: string) {\n return this.exclusive(async () => {\n const receipt = this.receipt();\n if (!receipt) throw new Error('No submission receipt to recover');\n if (uuid !== undefined) {\n const run = await this.findRun(uuid);\n if (!run) throw new Error('Cannot attach an unobserved run');\n this.save({ ...receipt, runUuid: uuid, phase: 'accepted' });\n return this.inspect(uuid);\n }\n if (receipt.runUuid)\n throw new Error(`The receipt already names run ${receipt.runUuid}; inspect it instead`);\n const since = Date.parse(receipt.submittedAt) - CLOCK_SKEW_MARGIN_MS;\n const candidates = (await this.history()).filter((r) => Date.parse(r.startedAt) >= since);\n if (candidates.length)\n throw new Error(\n `Run history has ${candidates.length} run(s) of this job since the submission at ${receipt.submittedAt}: ` +\n candidates.map((r) => `${r.uuid} (${r.status}, started ${r.startedAt})`).join('; ') +\n '. If one is this submission, attach it with recover --uuid <uuid>. Nothing was cleared.',\n );\n fs.rmSync(path.join(this.stateDir, 'current.json'), { force: true });\n return {\n cleared: true,\n submittedAt: receipt.submittedAt,\n note: 'Run history has no run of this job since the submission, so it was never accepted. The receipt was cleared; run again when ready.',\n };\n });\n }\n /** A local operator resolves a crashed command. Never clears its submission receipt. */\n unlockAbandonedOperation() {\n const name = path.join(this.operationDir, 'operation.lock');\n if (!fs.existsSync(name)) return { unlocked: false };\n const pid = Number(fs.readFileSync(name, 'utf8'));\n if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error('Unrecognized lock; inspect it manually');\n try {\n process.kill(pid, 0);\n } catch (error: any) {\n if (error.code === 'ESRCH') {\n fs.unlinkSync(name);\n return { unlocked: true, receiptRetained: true };\n }\n throw error;\n }\n throw new Error('The workspace command is still running');\n }\n}\nexport function redact(s: string) {\n return s.replace(/https?:\\/\\/[^\\s'\"<>]+/g, '[URL redacted]');\n}\n\n/** Names main.py assigns into its arguments: args[\"NAME\"] = ..., .setdefault(\"NAME\", ...), or a \"NAME\": dict key. */\nfunction setArgumentNames(source: string): Set<string> {\n const names = new Set<string>();\n for (const pattern of [\n /\\[\\s*[\"']([A-Za-z_][A-Za-z0-9_]*)[\"']\\s*\\]\\s*=(?!=)/g,\n /\\.setdefault\\(\\s*[\"']([A-Za-z_][A-Za-z0-9_]*)[\"']/g,\n /[\"']([A-Za-z_][A-Za-z0-9_]*)[\"']\\s*:/g,\n ])\n for (const match of source.matchAll(pattern)) names.add(match[1]);\n return names;\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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|
|
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 agentApprovalFetch_exports = {};
|
|
20
|
+
__export(agentApprovalFetch_exports, {
|
|
21
|
+
installAgentApprovalFetch: () => installAgentApprovalFetch,
|
|
22
|
+
withAgentApprovals: () => withAgentApprovals
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(agentApprovalFetch_exports);
|
|
25
|
+
var import_promises = require("node:timers/promises");
|
|
26
|
+
var import_requests = require("../pipeline/requests");
|
|
27
|
+
var import_configService = require("./configService");
|
|
28
|
+
function withAgentApprovals(transport, backendUrl, secret, notify = (message) => process.stderr.write(message + "\n"), pollMs = 1e3) {
|
|
29
|
+
const base = new URL(backendUrl.replace(/\/api\/v3\/?$/, "").replace(/\/$/, "") + "/");
|
|
30
|
+
return async (input, init) => {
|
|
31
|
+
const request = new Request(input, init);
|
|
32
|
+
const url = new URL(request.url);
|
|
33
|
+
if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname + "api/v3/") || request.headers.get("X-API-KEY") !== secret)
|
|
34
|
+
return transport(request);
|
|
35
|
+
const response = await transport(request.clone());
|
|
36
|
+
if (response.status !== 428) return response;
|
|
37
|
+
const receipt = await response.clone().json().catch(() => null);
|
|
38
|
+
if (receipt?.code !== "FARSEER_WRITE_APPROVAL_REQUIRED" || !/^write-[0-9a-f-]{36}$/.test(receipt.approval_id))
|
|
39
|
+
return response;
|
|
40
|
+
const statusUrl = new URL("api/v3/agent/write-approvals/" + receipt.approval_id, base);
|
|
41
|
+
const signal = AbortSignal.any([request.signal, AbortSignal.timeout(36e5)]);
|
|
42
|
+
const waiting = () => notify("Waiting for approval in Farseer chat before changing Farseer data.");
|
|
43
|
+
waiting();
|
|
44
|
+
const heartbeat = setInterval(waiting, 5e3);
|
|
45
|
+
const resumeDeadline = (0, import_requests.pausePipelineDeadlines)();
|
|
46
|
+
try {
|
|
47
|
+
for (; ; ) {
|
|
48
|
+
await (0, import_promises.setTimeout)(pollMs, void 0, { signal });
|
|
49
|
+
const statusResponse = await transport(statusUrl, {
|
|
50
|
+
headers: { "X-API-KEY": secret, "X-TENANT-ID": request.headers.get("X-TENANT-ID") ?? "" },
|
|
51
|
+
signal
|
|
52
|
+
}).catch((error) => {
|
|
53
|
+
if (signal.aborted) throw error;
|
|
54
|
+
return null;
|
|
55
|
+
});
|
|
56
|
+
if (!statusResponse || statusResponse.status >= 500) continue;
|
|
57
|
+
if (!statusResponse.ok)
|
|
58
|
+
throw new Error("Farseer write approval expired or the turn was cancelled. No write was retried.");
|
|
59
|
+
const { status } = await statusResponse.json();
|
|
60
|
+
if (status === "pending") continue;
|
|
61
|
+
if (status !== "approved")
|
|
62
|
+
throw new Error(
|
|
63
|
+
"Farseer write was rejected or already attempted. Inspect its result before proposing another write."
|
|
64
|
+
);
|
|
65
|
+
const headers = new Headers(request.headers);
|
|
66
|
+
headers.set("X-Farseer-Approval", receipt.approval_id);
|
|
67
|
+
resumeDeadline();
|
|
68
|
+
return await transport(new Request(request, { headers, signal }));
|
|
69
|
+
}
|
|
70
|
+
} finally {
|
|
71
|
+
clearInterval(heartbeat);
|
|
72
|
+
resumeDeadline();
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
function installAgentApprovalFetch() {
|
|
77
|
+
const { FARSEER_API_KEY: secret, FARSEER_URL: backendUrl } = process.env;
|
|
78
|
+
if (!secret?.startsWith(import_configService.AGENT_API_KEY_PREFIX) || !backendUrl) return;
|
|
79
|
+
globalThis.fetch = withAgentApprovals(globalThis.fetch, backendUrl, secret);
|
|
80
|
+
}
|
|
81
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
82
|
+
0 && (module.exports = {
|
|
83
|
+
installAgentApprovalFetch,
|
|
84
|
+
withAgentApprovals
|
|
85
|
+
});
|
|
86
|
+
//# sourceMappingURL=agentApprovalFetch.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/services/agentApprovalFetch.ts"],
|
|
4
|
+
"sourcesContent": ["import { setTimeout as delay } from 'node:timers/promises';\nimport { pausePipelineDeadlines } from '../pipeline/requests';\nimport { AGENT_API_KEY_PREFIX } from './configService';\n\n/** CLI commands and the MCP server both use the SDK/global fetch transport.\n * Only ephemeral agent turn keys enable this; normal CLI logins are unchanged. */\nexport function withAgentApprovals(\n transport: typeof fetch,\n backendUrl: string,\n secret: string,\n notify: (message: string) => void = (message) => process.stderr.write(message + '\\n'),\n pollMs = 1000,\n): typeof fetch {\n const base = new URL(backendUrl.replace(/\\/api\\/v3\\/?$/, '').replace(/\\/$/, '') + '/');\n return async (input, init) => {\n const request = new Request(input, init);\n const url = new URL(request.url);\n if (\n url.origin !== base.origin ||\n !url.pathname.startsWith(base.pathname + 'api/v3/') ||\n request.headers.get('X-API-KEY') !== secret\n )\n return transport(request);\n // Keep an immutable copy, including multipart boundary and file bytes, for the\n // single retry the backend explicitly says has NOT executed yet.\n const response = await transport(request.clone());\n if (response.status !== 428) return response;\n const receipt = await response\n .clone()\n .json()\n .catch(() => null);\n if (receipt?.code !== 'FARSEER_WRITE_APPROVAL_REQUIRED' || !/^write-[0-9a-f-]{36}$/.test(receipt.approval_id))\n return response;\n const statusUrl = new URL('api/v3/agent/write-approvals/' + receipt.approval_id, base);\n const signal = AbortSignal.any([request.signal, AbortSignal.timeout(3600_000)]);\n const waiting = () => notify('Waiting for approval in Farseer chat before changing Farseer data.');\n waiting();\n // OpenHands' terminal yields after a period without output. stderr also keeps\n // MCP stdout clean: it contains protocol messages only.\n const heartbeat = setInterval(waiting, 5000);\n const resumeDeadline = pausePipelineDeadlines();\n try {\n for (;;) {\n await delay(pollMs, undefined, { signal });\n // The poll is a read, so an outage or a starting API pod only delays the decision.\n const statusResponse = await transport(statusUrl, {\n headers: { 'X-API-KEY': secret, 'X-TENANT-ID': request.headers.get('X-TENANT-ID') ?? '' },\n signal,\n }).catch((error: unknown) => {\n if (signal.aborted) throw error;\n return null;\n });\n if (!statusResponse || statusResponse.status >= 500) continue;\n if (!statusResponse.ok)\n throw new Error('Farseer write approval expired or the turn was cancelled. No write was retried.');\n const { status } = await statusResponse.json();\n if (status === 'pending') continue;\n if (status !== 'approved')\n throw new Error(\n 'Farseer write was rejected or already attempted. Inspect its result before proposing another write.',\n );\n const headers = new Headers(request.headers);\n headers.set('X-Farseer-Approval', receipt.approval_id);\n resumeDeadline(); // The approved write is network work again.\n // Never retry a network error or a handler error: the outcome could be uncertain.\n return await transport(new Request(request, { headers, signal }));\n }\n } finally {\n clearInterval(heartbeat);\n resumeDeadline();\n }\n };\n}\n\nexport function installAgentApprovalFetch(): void {\n const { FARSEER_API_KEY: secret, FARSEER_URL: backendUrl } = process.env;\n if (!secret?.startsWith(AGENT_API_KEY_PREFIX) || !backendUrl) return;\n globalThis.fetch = withAgentApprovals(globalThis.fetch, backendUrl, secret);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAoC;AACpC,sBAAuC;AACvC,2BAAqC;AAI9B,SAAS,mBACZ,WACA,YACA,QACA,SAAoC,CAAC,YAAY,QAAQ,O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B,eAAe,UAAU,IAAK;AACrD,YAAI,CAAC,eAAe;AAChB,gBAAM,IAAI,MAAM,iFAAiF;AACrG,cAAM,EAAE,OAAO,IAAI,MAAM,eAAe,KAAK;AAC7C,YAAI,WAAW,UAAW;AAC1B,YAAI,WAAW;AACX,gBAAM,IAAI;AAAA,YACN;AAAA,UACJ;AACJ,cAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;AAC3C,gBAAQ,IAAI,sBAAsB,QAAQ,WAAW;AACrD,uBAAe;AAEf,eAAO,MAAM,UAAU,IAAI,QAAQ,SAAS,EAAE,SAAS,OAAO,CAAC,CAAC;AAAA,MACpE;AAAA,IACJ,UAAE;AACE,oBAAc,SAAS;AACvB,qBAAe;AAAA,IACnB;AAAA,EACJ;AACJ;AAEO,SAAS,4BAAkC;AAC9C,QAAM,EAAE,iBAAiB,QAAQ,aAAa,WAAW,IAAI,QAAQ;AACrE,MAAI,CAAC,QAAQ,WAAW,yCAAoB,KAAK,CAAC,WAAY;AAC9D,aAAW,QAAQ,mBAAmB,WAAW,OAAO,YAAY,MAAM;AAC9E;",
|
|
6
|
+
"names": ["delay"]
|
|
7
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/appSyncService.ts"],
|
|
4
|
-
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport {\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,QAAG;AAAA,IACH,QAAG;AAAA;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