farseer-cli 1.18.0 → 1.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/commands/app.js.map +0 -1
- package/dist/commands/apps.js.map +0 -1
- package/dist/commands/cells.js.map +0 -1
- package/dist/commands/code.js.map +0 -1
- package/dist/commands/config.js.map +0 -1
- package/dist/commands/dashboards.js.map +0 -1
- package/dist/commands/diff.js.map +0 -1
- package/dist/commands/dimensions.js.map +0 -1
- package/dist/commands/files.js.map +0 -1
- package/dist/commands/formula.js.map +0 -1
- package/dist/commands/install.js.map +0 -1
- package/dist/commands/list.js.map +0 -1
- package/dist/commands/login.js +3 -3
- package/dist/commands/login.js.map +1 -2
- package/dist/commands/logout.js.map +0 -1
- package/dist/commands/mcp-server.js.map +0 -1
- package/dist/commands/model.js.map +0 -1
- package/dist/commands/pipeline.js.map +0 -1
- package/dist/commands/pull.js +1 -1
- package/dist/commands/pull.js.map +1 -2
- package/dist/commands/push.js +2 -2
- package/dist/commands/push.js.map +1 -2
- package/dist/commands/refresh.js.map +0 -1
- package/dist/commands/run.js.map +0 -1
- package/dist/commands/sheets.js.map +0 -1
- package/dist/commands/status.js.map +0 -1
- package/dist/commands/tool.js.map +0 -1
- package/dist/commands/variables.js.map +0 -1
- package/dist/commands/whoami.js.map +0 -1
- package/dist/index.js +24 -10
- package/dist/index.js.map +1 -2
- package/dist/mcp/index.js.map +0 -1
- package/dist/mcp/prompts/workflows.js.map +0 -1
- package/dist/mcp/resources/documentation.js.map +0 -1
- package/dist/mcp/server.js.map +0 -1
- package/dist/mcp/skills.js.map +0 -1
- package/dist/mcp/tools/appTools.js.map +0 -1
- package/dist/mcp/tools/authTools.js +1 -1
- package/dist/mcp/tools/authTools.js.map +1 -2
- package/dist/mcp/tools/cellTools.js.map +0 -1
- package/dist/mcp/tools/dashboardTools.js.map +0 -1
- package/dist/mcp/tools/dataTools.js.map +0 -1
- package/dist/mcp/tools/folderTools.js.map +0 -1
- package/dist/mcp/tools/modelTools.js.map +0 -1
- package/dist/mcp/tools/pipelineContract.js.map +0 -1
- package/dist/mcp/tools/pipelineTools.js.map +0 -1
- package/dist/mcp/tools/runTools.js.map +0 -1
- package/dist/mcp/tools/sheetTools.js.map +0 -1
- package/dist/mcp/tools/syncTools.js +2 -2
- package/dist/mcp/tools/syncTools.js.map +1 -2
- package/dist/mcp/utils/helpers.js.map +0 -1
- package/dist/mcp/utils/launchPin.js.map +0 -1
- package/dist/mcp/utils/registerTool.js.map +0 -1
- package/dist/mcp/utils/session.js.map +0 -1
- package/dist/mcp/utils/tenantPin.js.map +0 -1
- package/dist/pipeline/compatibility.js.map +0 -1
- package/dist/pipeline/connect.js.map +0 -1
- package/dist/pipeline/create.js.map +0 -1
- package/dist/pipeline/errors.js.map +0 -1
- package/dist/pipeline/generated-reference.json +22 -10
- package/dist/pipeline/guide.js.map +0 -1
- package/dist/pipeline/init.js.map +0 -1
- package/dist/pipeline/operations.js.map +0 -1
- package/dist/pipeline/query.js.map +0 -1
- package/dist/pipeline/queryDownloads.js.map +0 -1
- package/dist/pipeline/queryWorker.js.map +0 -1
- package/dist/pipeline/readiness.js.map +0 -1
- package/dist/pipeline/reference.js.map +0 -1
- package/dist/pipeline/requests.js.map +0 -1
- package/dist/pipeline/runArguments.js.map +0 -1
- package/dist/pipeline/runtime.js.map +0 -1
- package/dist/pipeline/service.js.map +0 -1
- package/dist/services/agentApprovalFetch.js +7 -3
- package/dist/services/agentApprovalFetch.js.map +1 -2
- package/dist/services/appSyncService.js.map +0 -1
- package/dist/services/apps.js.map +0 -1
- package/dist/services/authErrors.js.map +0 -1
- package/dist/services/codefirst/api.js +38 -5
- package/dist/services/codefirst/api.js.map +1 -2
- package/dist/services/codefirst/binaryDisk.js.map +0 -1
- package/dist/services/codefirst/byteHashes.js +5 -0
- package/dist/services/codefirst/byteHashes.js.map +1 -2
- package/dist/services/codefirst/documents.js +41 -15
- package/dist/services/codefirst/documents.js.map +1 -2
- package/dist/services/codefirst/layoutBinaryProjection.js +24 -13
- package/dist/services/codefirst/layoutBinaryProjection.js.map +1 -2
- package/dist/services/codefirst/layoutCompose.js +44 -38
- package/dist/services/codefirst/layoutCompose.js.map +1 -2
- package/dist/services/codefirst/layoutCore.js +14 -1
- package/dist/services/codefirst/layoutCore.js.map +1 -2
- package/dist/services/codefirst/layoutPaths.js +80 -4
- package/dist/services/codefirst/layoutPaths.js.map +1 -2
- package/dist/services/codefirst/layoutProjection.js +73 -39
- package/dist/services/codefirst/layoutProjection.js.map +1 -2
- package/dist/services/codefirst/layoutReadback.js +357 -130
- package/dist/services/codefirst/layoutReadback.js.map +2 -3
- package/dist/services/codefirst/layoutReadbackPlacement.js +94 -57
- package/dist/services/codefirst/layoutReadbackPlacement.js.map +2 -3
- package/dist/services/codefirst/layoutReceipt.js +283 -243
- package/dist/services/codefirst/layoutReceipt.js.map +2 -3
- package/dist/services/codefirst/layoutScan.js +208 -110
- package/dist/services/codefirst/layoutScan.js.map +1 -2
- package/dist/services/codefirst/output.js +76 -10
- package/dist/services/codefirst/output.js.map +1 -2
- package/dist/services/codefirst/types.js.map +0 -1
- package/dist/services/codefirst/workflow.js +65 -29
- package/dist/services/codefirst/workflow.js.map +2 -3
- package/dist/services/codefirst/workspace.js.map +0 -1
- package/dist/services/codefirst/workspaceLock.js.map +0 -1
- package/dist/services/codefirst/workspaceRoot.js +2 -1
- package/dist/services/codefirst/workspaceRoot.js.map +1 -2
- package/dist/services/configService.js.map +0 -1
- package/dist/services/credentials.js.map +0 -1
- package/dist/services/farseerService.js +3 -1
- package/dist/services/farseerService.js.map +1 -2
- package/dist/services/httpError.js.map +0 -1
- package/dist/services/modelExport.js.map +0 -1
- package/dist/services/organisation.js.map +0 -1
- package/dist/services/preflight.js.map +0 -1
- package/dist/services/realms.js.map +0 -1
- package/dist/services/syncService.js +3 -3
- package/dist/services/syncService.js.map +1 -2
- package/dist/skills/pipeline.js.map +0 -1
- package/dist/utils/agentSandbox.js.map +0 -1
- package/dist/utils/cliOptions.js.map +0 -1
- package/dist/utils/constants.js.map +0 -1
- package/dist/utils/entityResolver.js.map +0 -1
- package/dist/utils/errorFormatter.js +59 -11
- package/dist/utils/errorFormatter.js.map +1 -2
- package/dist/utils/fileLogger.js.map +0 -1
- package/dist/utils/fileValidation.js.map +0 -1
- package/dist/utils/folderMatch.js.map +0 -1
- package/dist/utils/formulaFilters.js.map +0 -1
- package/dist/utils/helpers.js.map +0 -1
- package/dist/utils/logger.js.map +0 -1
- package/dist/utils/nameResolver.js.map +0 -1
- package/dist/utils/packageManager.js.map +0 -1
- package/dist/utils/syncReporting.js.map +0 -1
- package/dist/utils/syncScope.js.map +0 -1
- package/dist/utils/updateCheck.js.map +0 -1
- package/dist/utils/variableValues.js.map +0 -1
- package/dist/utils/workspace.js.map +0 -1
- package/docs/cli-guide.md +1 -1
- package/docs/import-workflows.md +14 -14
- package/docs/new-app-template.md +1 -1
- package/docs/pipeline-client-guide.md +1 -1
- package/docs/pipeline-reference.md +292 -3
- package/package.json +2 -2
- package/skills/farseer-analysis/SKILL.md +132 -0
- package/skills/farseer-dashboards/SKILL.md +40 -0
- package/skills/farseer-formulas/SKILL.md +165 -0
- package/skills/farseer-model/SKILL.md +119 -0
- package/skills/pipeline-authoring/SKILL.md +6 -4
- package/skills/pipeline-authoring/practices.md +6 -5
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
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, ParseConfig, 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 !== undefined && 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,\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AAC,CAAC;AACpE,SAAO;AACX;",
|
|
6
5
|
"names": ["dir", "result"]
|
|
7
6
|
}
|
|
@@ -25,7 +25,7 @@ module.exports = __toCommonJS(agentApprovalFetch_exports);
|
|
|
25
25
|
var import_promises = require("node:timers/promises");
|
|
26
26
|
var import_requests = require("../pipeline/requests");
|
|
27
27
|
var import_configService = require("./configService");
|
|
28
|
-
function withAgentApprovals(transport, backendUrl, secret, notify = (message) => process.stderr.write(message + "\n"), pollMs =
|
|
28
|
+
function withAgentApprovals(transport, backendUrl, secret, notify = (message) => process.stderr.write(message + "\n"), pollMs = 5e3) {
|
|
29
29
|
const base = new URL(backendUrl.replace(/\/api\/v3\/?$/, "").replace(/\/$/, "") + "/");
|
|
30
30
|
return async (input, init) => {
|
|
31
31
|
const request = new Request(input, init);
|
|
@@ -35,10 +35,10 @@ function withAgentApprovals(transport, backendUrl, secret, notify = (message) =>
|
|
|
35
35
|
const response = await transport(request.clone());
|
|
36
36
|
if (response.status !== 428) return response;
|
|
37
37
|
const receipt = await response.clone().json().catch(() => null);
|
|
38
|
-
if (receipt?.code !== "FARSEER_WRITE_APPROVAL_REQUIRED" || !/^
|
|
38
|
+
if (receipt?.code !== "FARSEER_WRITE_APPROVAL_REQUIRED" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(receipt.approval_id))
|
|
39
39
|
return response;
|
|
40
40
|
const statusUrl = new URL("api/v3/agent/write-approvals/" + receipt.approval_id, base);
|
|
41
|
-
const signal = AbortSignal.any([request.signal, AbortSignal.timeout(
|
|
41
|
+
const signal = AbortSignal.any([request.signal, AbortSignal.timeout(96e4)]);
|
|
42
42
|
const waiting = () => notify("Waiting for approval in Farseer chat before changing Farseer data.");
|
|
43
43
|
waiting();
|
|
44
44
|
const heartbeat = setInterval(waiting, 5e3);
|
|
@@ -58,6 +58,10 @@ function withAgentApprovals(transport, backendUrl, secret, notify = (message) =>
|
|
|
58
58
|
throw new Error("Farseer write approval expired or the turn was cancelled. No write was retried.");
|
|
59
59
|
const { status } = await statusResponse.json();
|
|
60
60
|
if (status === "pending") continue;
|
|
61
|
+
if (status === "expired")
|
|
62
|
+
throw new Error(
|
|
63
|
+
"Farseer write was not approved within 15 minutes, so it was not made. Tell the user what you wanted to change; propose it again only if they ask."
|
|
64
|
+
);
|
|
61
65
|
if (status !== "approved")
|
|
62
66
|
throw new Error(
|
|
63
67
|
"Farseer write was rejected or already attempted. Inspect its result before proposing another write."
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/agentApprovalFetch.ts"],
|
|
4
|
-
"
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAoC;AACpC,sBAAuC;AACvC,2BAAqC;AAI9B,SAAS,mBACZ,WACA,YACA,QACA,SAAoC,CAAC,YAAY,QAAQ,OAAO,MAAM,UAAU,IAAI,GACpF,SAAS,KACG;AACZ,QAAM,OAAO,IAAI,IAAI,WAAW,QAAQ,iBAAiB,EAAE,EAAE,QAAQ,OAAO,EAAE,IAAI,GAAG;AACrF,SAAO,OAAO,OAAO,SAAS;AAC1B,UAAM,UAAU,IAAI,QAAQ,OAAO,IAAI;AACvC,UAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;AAC/B,QACI,IAAI,WAAW,KAAK,UACpB,CAAC,IAAI,SAAS,WAAW,KAAK,WAAW,SAAS,KAClD,QAAQ,QAAQ,IAAI,WAAW,MAAM;AAErC,aAAO,UAAU,OAAO;AAG5B,UAAM,WAAW,MAAM,UAAU,QAAQ,MAAM,CAAC;AAChD,QAAI,SAAS,WAAW,IAAK,QAAO;AACpC,UAAM,UAAU,MAAM,SACjB,MAAM,EACN,KAAK,EACL,MAAM,MAAM,IAAI;AACrB,QAAI,SAAS,SAAS,qCAAqC,CAAC,wBAAwB,KAAK,QAAQ,WAA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AiB,MAAM,UAAU,WAAW;AAAA,UAC9C,SAAS,EAAE,aAAa,QAAQ,eAAe,QAAQ,QAAQ,IAAI,aAAa,KAAK,GAAG;AAAA,UACxF;AAAA,QACJ,CAAC,EAAE,MAAM,CAAC,UAAmB;AACzB,cAAI,OAAO,QAAS,OAAM;AAC1B,iBAAO;AAAA,QACX,CAAC;AACD,YAAI,CAAC,kBAAkB,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,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
5
|
"names": ["delay"]
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
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 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
4
|
"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;AAAA,IAEH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;AAAA,IACH,QAAG;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A,eAAW,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,YAAY;AACrC,UAAI,CAAC,UAAU,IAAI,GAAG,GAAG;AACrB,eAAO,UAAU,KAAK,IAAI,IAAI;AAAA,MAClC;AAAA,IACJ;AAEA,WAAO;AAAA,EACX;AACJ;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/apps.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Apps (Remote Jobs): their shape, and the rules over it.\n *\n * What belongs here is decided by dependency direction, not by I/O: nothing in\n * this module constructs a client or reads a credential. applySourceFolderChange\n * does make a call, but through an injected one-method resolver, so it stays\n * testable without one.\n */\n\nimport chalk from 'chalk';\nimport * as farseer from 'farseer-client';\n\nexport type AppArgumentDataType = 'string' | 'boolean';\n\nexport interface AppArgument {\n name: string;\n dataType: AppArgumentDataType;\n fixed?: boolean;\n options?: string[];\n defaultValue?: string;\n secret?: boolean;\n}\n\nexport interface AppScriptFile {\n id: string;\n name: string;\n}\n\n// A resolved source folder: its node id (to set on the app) plus the script\n// files it contains (to validate an entrypoint lives inside it).\nexport interface SourceFolderResolution {\n id: number;\n scripts: AppScriptFile[];\n}\n\nexport interface AppPredefinedAction {\n name: string;\n runArguments: Record<string, string>;\n}\n\n/**\n * Shown in place of an action's value for an argument marked secret.\n *\n * The backend returns action values readable even for secret arguments \u2014 its\n * masking covers only defaults \u2014 so every surface that displays an action masks\n * it here. Sent back unchanged in a whole-list update, it means \"keep the value\n * the tenant has\", which is what lets an agent edit one action without having\n * to know, or wipe, another's secret.\n */\nexport const SECRET_PLACEHOLDER = '<secret>';\n\n// Exact names, as the backend holds them: `Token` and `token` are two arguments.\nfunction secretNames(args: AppArgument[]): Set<string> {\n return new Set(args.filter((a) => a.secret).map((a) => a.name));\n}\n\n/** The actions with every secret argument's value replaced by the placeholder. */\nexport function redactActionValues(actions: AppPredefinedAction[], args: AppArgument[]): AppPredefinedAction[] {\n const secret = secretNames(args);\n return actions.map((action) => ({\n name: action.name,\n runArguments: Object.fromEntries(\n Object.entries(action.runArguments ?? {}).map(([name, value]) => [\n name,\n secret.has(name) ? SECRET_PLACEHOLDER : value,\n ]),\n ),\n }));\n}\n\n/**\n * Put the tenant's own values back wherever an incoming action carries the\n * placeholder.\n *\n * Actions have no id, so the stored action a placeholder stands for is the one\n * with exactly its name, and only while that name is unique on both sides: the\n * backend accepts `Daily` beside `daily`, and two actions both named `Daily`,\n * and picking one of those would write its secret into the other. Anything\n * else is refused \u2014 an ambiguous name, a new action, an argument the action\n * did not preset \u2014 since sending the placeholder on would store it as the\n * secret.\n */\nexport function restoreRedactedValues(\n incoming: AppPredefinedAction[],\n current: AppPredefinedAction[],\n): { actions: AppPredefinedAction[] } | { error: string } {\n const named = (actions: AppPredefinedAction[], name: string) => actions.filter((a) => a.name === name);\n const actions: AppPredefinedAction[] = [];\n for (const action of incoming) {\n const stored = named(current, action.name);\n const ambiguous = stored.length > 1 || named(incoming, action.name).length > 1;\n const runArguments: Record<string, string> = {};\n for (const [name, value] of Object.entries(action.runArguments ?? {})) {\n if (value !== SECRET_PLACEHOLDER) {\n runArguments[name] = value;\n continue;\n }\n if (ambiguous) {\n return {\n error: `Action \"${action.name}\" sends ${SECRET_PLACEHOLDER} for \"${name}\", but more than one action is named \"${action.name}\", so which stored value it stands for is unknown \u2014 give the real value.`,\n };\n }\n const kept = stored[0]?.runArguments?.[name];\n if (kept === undefined) {\n return {\n error: `Action \"${action.name}\" sends ${SECRET_PLACEHOLDER} for \"${name}\", but no stored action named exactly \"${action.name}\" has a value for it \u2014 give the real value.`,\n };\n }\n runArguments[name] = kept;\n }\n actions.push({ name: action.name, runArguments });\n }\n return { actions };\n}\n\n// Where a run executes: 'local' is a container on the jobrunner's own machine,\n// 'batch' is a machine created for that one run. Sizes name hardware the\n// jobrunner deployment picks, so 'batch' with no size means its default.\nexport type AppComputeSize = 's' | 'm' | 'l' | 'xl';\n\nexport type AppCompute = { type: 'local' } | { type: 'batch'; options?: { size?: AppComputeSize } | null };\n\n// The same vocabulary the UI's compute selector uses, so one job reads the same\n// whichever surface configured it.\nexport type ComputeChoice = 'local' | 'batch' | `batch:${AppComputeSize}`;\n\n// Hand-written because the generated `RemoteJobComputeSize` enum is not in the\n// client SDK release this CLI pins. The other copy of this vocabulary is\n// `frontend/src/features/remoteJobs/computeChoices.ts`, which does derive from\n// that enum \u2014 a size added to the API reaches the UI and not this list, so add\n// it in both places until the pin can be bumped.\nexport const APP_COMPUTE_SIZES: readonly AppComputeSize[] = ['s', 'm', 'l', 'xl'];\n\nexport const APP_COMPUTE_CHOICES: readonly ComputeChoice[] = [\n 'local',\n 'batch',\n ...APP_COMPUTE_SIZES.map((size) => `batch:${size}` as const),\n];\n\nexport interface RemoteApp {\n id: number;\n name: string;\n description: string;\n expectedArguments: AppArgument[];\n status: string;\n lastHeartbeat: string;\n mainScriptFileId: string | null;\n scriptFiles?: AppScriptFile[];\n sourceFolderId?: number;\n schedule?: string | null;\n runnerName?: string | null;\n runnerImage?: string | null;\n predefinedActions: AppPredefinedAction[];\n compute?: AppCompute;\n /** Base64, as the backend returns it. */\n icon?: string | null;\n}\n\n// The fields a Remote Job update writes. The backend PUT replaces the whole\n// row, so any field omitted here is reset to its default (args/predefined \u2192\n// empty, the rest \u2192 null). `mergeAppUpdate` exists so a caller that only wants\n// to touch one field doesn't silently wipe the others.\n//\n// `compute` is the exception: the backend reads an absent one as \"leave it\" and\n// an explicit null as \"reset to local\", so it is optional here and sent only\n// when there is a value to send.\nexport interface UpdateAppPayload {\n name: string;\n description: string;\n expectedArguments: AppArgument[];\n mainScriptFileId: string | null;\n sourceFolderId: number | null;\n schedule: string | null;\n runnerName: string | null;\n runnerImage: string | null;\n predefinedActions: AppPredefinedAction[];\n compute?: AppCompute;\n icon: string | null;\n}\n\n// `scriptFileIds` is accepted from callers for backwards compatibility but is\n// never sent \u2014 the backend ignores it (scripts derive from the source folder).\nexport type AppUpdateChanges = Partial<UpdateAppPayload> & { scriptFileIds?: string[] };\n\n/**\n * Overlay a caller's changes onto an app's current state to build a full,\n * non-destructive update payload. Every field the caller leaves out keeps its\n * current value \u2014 so changing one setting never clears the others.\n *\n * Nullable fields key off presence, not nullishness: passing `null` is how a\n * caller clears a schedule or a runner, and `??` would read that as \"not\n * specified\" and put the current value straight back.\n */\nexport function mergeAppUpdate(current: RemoteApp, changes: AppUpdateChanges): UpdateAppPayload {\n const payload: UpdateAppPayload = {\n name: changes.name ?? current.name,\n description: changes.description ?? current.description ?? '',\n expectedArguments: changes.expectedArguments ?? current.expectedArguments ?? [],\n mainScriptFileId: ('mainScriptFileId' in changes ? changes.mainScriptFileId : current.mainScriptFileId) ?? null,\n sourceFolderId: ('sourceFolderId' in changes ? changes.sourceFolderId : current.sourceFolderId) ?? null,\n schedule: ('schedule' in changes ? changes.schedule : current.schedule) ?? null,\n runnerName: ('runnerName' in changes ? changes.runnerName : current.runnerName) ?? null,\n runnerImage: ('runnerImage' in changes ? changes.runnerImage : current.runnerImage) ?? null,\n predefinedActions: changes.predefinedActions ?? current.predefinedActions ?? [],\n icon: ('icon' in changes ? changes.icon : current.icon) ?? null,\n };\n\n const compute = changes.compute ?? current.compute;\n if (compute) {\n payload.compute = compute;\n }\n\n return payload;\n}\n\n/**\n * Read a `--compute` value into the shape the API stores. Returns null when the\n * value isn't one of `APP_COMPUTE_CHOICES`, for the caller to report.\n */\nexport function parseComputeChoice(value: string): AppCompute | null {\n const choice = value.trim().toLowerCase();\n if (choice === 'local') {\n return { type: 'local' };\n }\n if (choice === 'batch') {\n return { type: 'batch' };\n }\n const size = choice.startsWith('batch:') ? choice.slice('batch:'.length) : null;\n if (size && (APP_COMPUTE_SIZES as readonly string[]).includes(size)) {\n return { type: 'batch', options: { size: size as AppComputeSize } };\n }\n return null;\n}\n\n/**\n * Render a stored compute selection as the choice a caller would type. An app\n * the backend didn't report one for reads as 'local', which is the default a\n * run gets.\n */\nexport function formatCompute(compute: AppCompute | undefined): ComputeChoice {\n if (compute?.type !== 'batch') {\n return 'local';\n }\n return compute.options?.size ? `batch:${compute.options.size}` : 'batch';\n}\n\nexport interface RunnerImageRepositories {\n registryPrefix: string;\n repositories: string[];\n}\n\n// A jobrunner currently connected to the tenant. `engines` is what it will run:\n// an empty list means it can run nothing for this tenant.\nexport interface ConnectedRunner {\n name: string;\n engines?: AppCompute['type'][];\n}\n\n/**\n * Expand a `--runner-image` value to the full registry reference the backend\n * stores. Accepts `<repository>:<tag>` and expands it with the tenant's registry\n * prefix, or takes an already-prefixed reference as given. Mirrors the backend's\n * own validation so a typo fails here rather than as a 400.\n */\nexport function resolveRunnerImage(\n value: string,\n registry: RunnerImageRepositories,\n): { image: string } | { error: string } {\n const known = registry.repositories.join(', ') || '(none configured)';\n const prefix = registry.registryPrefix ? `${registry.registryPrefix}/` : '';\n const rest = prefix && value.startsWith(prefix) ? value.slice(prefix.length) : value;\n\n if (rest.includes('/')) {\n return {\n error: `Runner image must be \"<repository>:<tag>\" or start with ${registry.registryPrefix}/. Available repositories: ${known}`,\n };\n }\n\n const colonIndex = rest.indexOf(':');\n if (colonIndex === -1) {\n return {\n error: `Runner image must include a tag, e.g. \"${registry.repositories[0] ?? 'runner-typescript'}:latest\"`,\n };\n }\n\n const repository = rest.slice(0, colonIndex);\n const tag = rest.slice(colonIndex + 1);\n if (!registry.repositories.includes(repository)) {\n return { error: `Unknown runner image repository \"${repository}\". Available repositories: ${known}` };\n }\n if (!tag) {\n return { error: `Runner image must include a tag, e.g. \"${repository}:latest\"` };\n }\n\n return { image: `${prefix}${repository}:${tag}` };\n}\n\n/**\n * Find a script in a source folder's file list by its exact name. Farseer file\n * names are case-sensitive \u2014 two files differing only in case can coexist in a\n * folder \u2014 so matching is exact, never case-folded, to avoid resolving an\n * entrypoint to the wrong file. Resolution is folder-scoped, never tenant-wide,\n * so a same-named file in another folder can't be picked by accident. Returns\n * undefined when the name isn't in the folder.\n */\nexport function findScriptInFolder(folderScripts: AppScriptFile[], name: string): AppScriptFile | undefined {\n return folderScripts.find((s) => s.name === name);\n}\n\n// The one client capability applySourceFolderChange needs. Kept minimal (not the\n// whole client) so it is trivial to unit-test with a fake resolver.\nexport interface SourceFolderResolver {\n resolveSourceFolder(relativePath: string): Promise<SourceFolderResolution | null>;\n}\n\n// Selects only how an error is presented \u2014 dimming, and `--flag` (CLI) vs param\n// (MCP) wording. It is a pure UX knob: the decision, the ids written to `changes`,\n// and the success/failure outcome are identical for both values. Never branch\n// functionality on it.\nexport type ConfigureCaller = 'cli' | 'mcp';\n\n/**\n * Resolve the source-folder / entrypoint settings for an `app configure` and\n * write the resulting ids into `changes`, applying the rule that an app's\n * scripts derive from its source folder and the entrypoint must be a file in\n * that folder. `sourceFolder` (a path under Files/) switches the folder;\n * otherwise the entrypoint is validated against the app's current folder. Moving\n * the folder must not orphan the entrypoint: if the current entrypoint isn't in\n * the new folder and the caller didn't supply one, the request is rejected \u2014 the\n * entrypoint is never silently cleared or relocated.\n *\n * Returns an error message for the caller to surface (and `changes` is left\n * untouched), or null once the ids have been written. The decision lives here so\n * the CLI and MCP paths can't drift.\n */\nexport async function applySourceFolderChange(\n client: SourceFolderResolver,\n app: Pick<RemoteApp, 'scriptFiles' | 'mainScriptFileId'>,\n changes: AppUpdateChanges,\n options: { sourceFolder?: string; entrypoint?: string },\n caller: ConfigureCaller,\n): Promise<string | null> {\n const cli = caller === 'cli';\n // Secondary guidance lines are dimmed in the terminal; plain for the MCP tool.\n const hint = (text: string) => (cli ? chalk.dim(text) : text);\n\n let folderScripts = app.scriptFiles ?? [];\n let sourceFolderId: number | undefined;\n\n if (options.sourceFolder) {\n // A failed request is deliberately not caught: \"no such folder\" is an\n // answer, and a 500 or a dropped connection is not one. Both callers\n // surface the throw with the status intact.\n const resolved = await client.resolveSourceFolder(options.sourceFolder);\n if (!resolved) {\n return [\n `Source folder not found under Files/: ${options.sourceFolder}`,\n hint('Use a path relative to Files/, e.g. \"Scripts/MyApp\".'),\n ].join('\\n');\n }\n sourceFolderId = resolved.id;\n folderScripts = resolved.scripts;\n\n // Moving the folder must not leave the entrypoint pointing outside it.\n if (!options.entrypoint && app.mainScriptFileId) {\n const stillThere = folderScripts.some((s) => s.id === app.mainScriptFileId);\n if (!stillThere) {\n const files = folderScripts.map((s) => s.name).join(', ') || '(none)';\n return [\n \"The app's current entrypoint is not in the new source folder.\",\n hint(\n cli\n ? 'Pass --entrypoint <script> (a file in the new folder) in the same command.'\n : 'Pass \"entrypoint\" (a file in the new folder) in the same call.',\n ),\n hint(`Files in this folder: ${files}`),\n ].join('\\n');\n }\n }\n }\n\n let mainScriptFileId: string | undefined;\n if (options.entrypoint) {\n const match = findScriptInFolder(folderScripts, options.entrypoint);\n if (!match) {\n const files = folderScripts.map((s) => s.name).join(', ') || '(none)';\n const lines = [\n `Entrypoint not found in the source folder: ${options.entrypoint}`,\n hint(`Files in this folder: ${files}`),\n ];\n if (!options.sourceFolder) {\n lines.push(\n hint(\n cli\n ? 'To use a file from another folder, set it first with --source-folder <path>.'\n : 'To use a file from another folder, pass sourceFolder first.',\n ),\n );\n }\n return lines.join('\\n');\n }\n mainScriptFileId = match.id;\n }\n\n // Apply only after every check passes, so a rejected request never partially\n // mutates `changes`.\n if (sourceFolderId !== undefined) {\n changes.sourceFolderId = sourceFolderId;\n }\n if (mainScriptFileId !== undefined) {\n changes.mainScriptFileId = mainScriptFileId;\n }\n return null;\n}\n\n// What a caller passes to clear a setting that can be unset. An empty string\n// does the same, so a shell variable that resolved to nothing reads as \"clear\"\n// rather than as a runner named ''.\nexport const CLEAR_SETTING = 'none';\n\nfunction isCleared(value: string): boolean {\n return value.trim() === '' || value.trim().toLowerCase() === CLEAR_SETTING;\n}\n\nexport interface RunSettings {\n schedule?: string;\n runner?: string;\n runnerImage?: string;\n compute?: string;\n}\n\n// The client capabilities applyRunSettings needs, kept minimal so tests can pass\n// a fake in place of a whole client.\nexport interface RunSettingsResolver {\n getRunnerImageRepositories(): Promise<RunnerImageRepositories>;\n getRunners(): Promise<ConnectedRunner[]>;\n}\n\n/**\n * Resolve the where-and-when settings for an `app configure` and write them into\n * `changes`. Returns an error string to report and abort on, or the warnings to\n * print alongside a successful update.\n *\n * Warnings rather than errors for anything that depends on a runner being\n * connected right now: these settings outlive any one connection, so a runner\n * that is merely restarting must not block configuring the job that needs it.\n */\nexport async function applyRunSettings(\n client: RunSettingsResolver,\n app: RemoteApp,\n changes: AppUpdateChanges,\n settings: RunSettings,\n): Promise<{ error: string } | { warnings: string[] }> {\n const warnings: string[] = [];\n const resolved: AppUpdateChanges = {};\n\n // Passed through as written. The CLI is one of three ways to set a schedule\n // and the only one that could check it here, so checking here would make the\n // same expression valid or invalid depending on where it was typed. The check\n // belongs in the backend, which every surface goes through.\n if (settings.schedule !== undefined) {\n resolved.schedule = isCleared(settings.schedule) ? null : settings.schedule.trim();\n }\n\n if (settings.compute !== undefined) {\n const compute = parseComputeChoice(settings.compute);\n if (!compute) {\n return {\n error: `Unknown compute selection \"${settings.compute}\". Valid values: ${APP_COMPUTE_CHOICES.join(', ')}.`,\n };\n }\n resolved.compute = compute;\n }\n\n if (settings.runner !== undefined) {\n resolved.runnerName = isCleared(settings.runner) ? null : settings.runner.trim();\n }\n\n if (settings.runnerImage !== undefined) {\n if (isCleared(settings.runnerImage)) {\n resolved.runnerImage = null;\n } else {\n const registry = await client.getRunnerImageRepositories();\n const outcome = resolveRunnerImage(settings.runnerImage.trim(), registry);\n if ('error' in outcome) {\n return outcome;\n }\n resolved.runnerImage = outcome.image;\n }\n }\n\n if ('runnerName' in resolved || 'compute' in resolved) {\n // Both sides fall back to what the job already holds, so the check sees\n // the configuration the job ends up with rather than only the half of it\n // this call happened to touch.\n const runnerName = ('runnerName' in resolved ? resolved.runnerName : app.runnerName) ?? null;\n const compute = 'compute' in resolved ? resolved.compute : app.compute;\n warnings.push(...(await runnerWarnings(client, runnerName, compute)));\n }\n\n Object.assign(changes, resolved);\n return { warnings };\n}\n\nasync function runnerWarnings(\n client: RunSettingsResolver,\n runnerName: string | null,\n compute: AppCompute | undefined,\n): Promise<string[]> {\n let runners: ConnectedRunner[];\n try {\n runners = await client.getRunners();\n } catch {\n // The settings are still valid; only the reassurance is missing.\n return [];\n }\n\n if (runnerName && !runners.some((runner) => runner.name === runnerName)) {\n const connected = runners.map((runner) => runner.name).join(', ') || '(none)';\n return [`No jobrunner named \"${runnerName}\" is connected. Currently connected: ${connected}`];\n }\n\n if (!compute) {\n return [];\n }\n\n const answering = runnerName ? runners.filter((runner) => runner.name === runnerName) : runners;\n if (answering.length === 0) {\n return [];\n }\n // A runner that reported no engines predates the field and runs in process only.\n const engine = compute.type;\n if (answering.some((runner) => (runner.engines ?? ['local']).includes(engine))) {\n return [];\n }\n\n const who = runnerName ? `Jobrunner \"${runnerName}\" does not offer` : 'No connected jobrunner offers';\n // \"shared runner\" and \"a machine per run\" are the labels the UI's compute\n // selector uses, so one job reads the same whichever surface configured it.\n const what = engine === 'batch' ? 'a machine per run' : 'runs on the shared runner';\n return [`${who} ${what}. The setting is saved; runs will fail until one does.`];\n}\n\n// `reference` (the Remote Job id) is deliberately the only id here \u2014 apps also\n// have a folder-item id, in an overlapping number space, and carrying both is\n// what let `app delete` destroy unrelated objects.\nexport interface AppListItem {\n name: string;\n type: string;\n reference: string;\n}\n\nexport const REMOTE_JOB_ITEM_TYPE = farseer.FolderItemType.RemoteJob;\n\n// A `folders.resolveItems` result: `id` is the folder-item id, `reference` the\n// id in the item's own domain (for REMOTE_JOB, the Remote Job id).\nexport interface ResolvedFolderItem {\n id: number;\n name: string;\n type: string;\n reference: string;\n}\n\nexport function remoteJobReverseReferences(remoteJobIds: readonly string[]): farseer.ReverseReference[] {\n return remoteJobIds.map((reference) => ({ reference, type: REMOTE_JOB_ITEM_TYPE }));\n}\n\n// A deliberate refusal from the delete guard, as distinct from a transport\n// failure. Callers surface it as a validation error, not a retryable one:\n// nothing was deleted and retrying cannot change that.\nexport class AppDeleteRefusedError extends Error {}\n\n/**\n * Pick the folder-item id to delete for an app, from the `resolveItems` response.\n *\n * Remote Job ids and folder-item ids overlap \u2014 the low folder ids are the roots\n * (13 = Files, 15 = Apps) \u2014 so posting a Remote Job id to `deleteItems` deletes\n * whichever unrelated node owns that number. `resolveItems` is type-scoped\n * server-side; these checks make sure a server change can't widen that.\n */\nexport function resolveAppItemNodeId(remoteJobId: string, items: readonly ResolvedFolderItem[]): number {\n const matches = items.filter((item) => item.reference === remoteJobId);\n\n if (matches.length === 0) {\n throw new AppDeleteRefusedError(`No app found for Remote Job id ${remoteJobId} \u2014 nothing was deleted.`);\n }\n if (matches.length > 1) {\n throw new AppDeleteRefusedError(\n `Remote Job id ${remoteJobId} resolved to ${matches.length} folder items \u2014 refusing to delete.`,\n );\n }\n\n const item = matches[0];\n if (item.type !== REMOTE_JOB_ITEM_TYPE) {\n throw new AppDeleteRefusedError(\n `Refusing to delete: Remote Job id ${remoteJobId} resolved to a ${item.type} ` +\n `(\"${item.name}\"), not an app.`,\n );\n }\n\n return item.id;\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AASA,mBAAkB;AAClB,cAAyB;AAuClB,MAAM,qBAAqB;AAGlC,SAAS,YAAY,MAAkC;AACnD,SAAO,IAAI,IAAI,KAAK,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC;AAClE;AAGO,SAAS,mBAAmB,SAAgC,MAA4C;AAC3G,QAAM,SAAS,YAAY,IAAI;AAC/B,SAAO,QAAQ,IAAI,CAAC,YAAY;AAAA,IAC5B,MAAM,OAAO;AAAA,IACb,cAAc,OAAO;AAAA,MACjB,OAAO,QAAQ,OAAO,gBAAgB,CAAC,CAAC,EAAE,IAAI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AI;AAAA,MACN,iBAAiB,WAAW,gBAAgB,QAAQ,MAAM;AAAA,IAC9D;AAAA,EACJ;AAEA,QAAM,OAAO,QAAQ,CAAC;AACtB,MAAI,KAAK,SAAS,sBAAsB;AACpC,UAAM,IAAI;AAAA,MACN,qCAAqC,WAAW,kBAAkB,KAAK,IAAI,MAClE,KAAK,IAAI;AAAA,IACtB;AAAA,EACJ;AAEA,SAAO,KAAK;AAChB;",
|
|
6
5
|
"names": ["actions", "chalk", "item"]
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/authErrors.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Telling an authentication failure from everything else.\n *\n * The 403 is the hard one: the backend answers it both for a credential it will\n * not accept and for a tenant the organisation does not have. The second is not\n * a credentials problem \u2014 every tenant-scoped request carries X-TENANT-ID, and\n * an organisation without that tenant refuses on that alone \u2014 so \"log in again\"\n * would send the user to fix the one thing that works. Only the body tells them\n * apart, which is why this is a shared decision and not a status check at each\n * call site.\n */\n\nimport { logger } from '../utils/logger';\n\n/** The wrong-organisation 403: `{\"code\":\"Forbidden\",\"message\":\"Tenant with id <t> does not exist\"}`. */\nexport function isTenantNotFoundError(error: unknown): boolean {\n return error instanceof Error && mentionsUnknownTenant(error.message);\n}\n\n/**\n * Apart from isTenantNotFoundError because that sentence reaches us two ways:\n * inside an Error the SDK threw, and as the `message` of a 403 body the\n * organisation probe reads straight off the response.\n */\nexport function mentionsUnknownTenant(text: string | undefined): boolean {\n if (!text) {\n return false;\n }\n const msg = text.toLowerCase();\n return msg.includes('does not exist') && msg.includes('tenant');\n}\n\nexport function isAuthError(error: unknown): boolean {\n if (isTenantNotFoundError(error)) {\n return false;\n }\n // Status first; the message is only a fallback, and messages now carry\n // folder paths and Remote Job ids \u2014 \"Failed to load app 1403\" is not a 403.\n const status = statusOf(error) ?? statusOf((error as { cause?: unknown } | null)?.cause);\n if (status !== undefined) {\n if (status === 401) {\n return true;\n }\n // The exclusion above reads a message and a raw Response carries none,\n // so for a bare 403 it never ran \u2014 claiming an auth failure here would\n // guess against the case this module exists to catch.\n return status === 403 && error instanceof Error;\n }\n if (error instanceof Error) {\n return mentionsAuthStatus(error.message);\n }\n return false;\n}\n\n/**\n * Only reached when nothing carried a status. The number must be presented as\n * one to count: a bare `includes('403')` read a folder named `403-reports` as\n * an auth failure.\n */\nfunction mentionsAuthStatus(message: string): boolean {\n const msg = message.toLowerCase();\n return (\n /(?:code|status|http)\\s*:?\\s*(?:401|403)\\b/.test(msg) ||\n msg.includes('unauthorized') ||\n msg.includes('forbidden')\n );\n}\n\n/** The HTTP status of an HttpError or a raw fetch Response, when there is one. */\nfunction statusOf(value: unknown): number | undefined {\n const status = (value as { status?: unknown } | null | undefined)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\nexport function showLoginPrompt(tenant?: string, organisation?: string): void {\n logger.error('Authentication required.');\n if (tenant) {\n logger.dim(`No valid credentials found for tenant \"${tenant}\".`);\n }\n // A login is per realm, so name the org: `login --org` picks its realm.\n logger.info(`Run \"farseer login${organisation ? ` --org ${organisation}` : ''}\" to authenticate via browser.`);\n logger.dim('Or use \"farseer config set <tenant> --api-key <key>\" for API key auth.');\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAYA,oBAAuB;AAGhB,SAAS,sBAAsB,OAAyB;AAC3D,SAAO,iBAAiB,SAAS,sBAAsB,MAAM,OAAO;AACxE;AAOO,SAAS,sBAAsB,MAAmC;AACrE,MAAI,CAAC,MAAM;AACP,WAAO;AAAA,EACX;AACA,QAAM,MAAM,KAAK,YAAY;AAC7B,SAAO,IAAI,SAAS,gBAAgB,KAAK,IAAI,SAAS,QAAQ;AAClE;AAEO,SAAS,YAAY,OAAyB;AACjD,MAAI,sBAAsB,KAAK,GAAG;AAC9B,WAAO;AAAA,EACX;AAGA,QAAM,SAAS,SAAS,KAAK,KAAK,SAAU,OAAsC,KAAK;AACvF,MAAI,WAAW,QAAW;AACtB,QAAI,WAAW,KAAK;AAChB,aAAO;AAAA,IACX;AAIA,WAAO,WAAW,OAAO,iBAAiB;AAAA,EAC9C;AACA,MAAI,iBAAiB,OAAO;AACxB,WAAO,mBAAmB,MAAM,OAAO;AAAA,EAC3C;AACA,SAAO;AACX;AAOA,SAAS,mBAAmB,SAA0B;AAClD,QAAM,MAAM,QAAQ,YAAY;AAChC,SACI,4CAA4C,KAAK,GAAG,KACpD,IAAI,SAAS,cAAc,KAC3B,IAAI,SAAS,WAAW;AAEhC;AAGA,SAAS,SAAS,OAAoC;AAClD,QAAM,SAAU,OAAmD;AACnE,SAAO,OAAO,WAAW,WAAW,SAAS;AACjD;AAEO,SAAS,gBAAgB,QAAiB,cAA6B;AAC1E,uBAAO,MAAM,0BAA0B;AACvC,MAAI,QAAQ;AACR,yBAAO,IAAI,0CAA0C,MAAM,IAAI;AAAA,EACnE;AAEA,uBAAO,KAAK,qBAAqB,eAAe,UAAU,YAAY,KAAK,EAAE,gCAAgC;AAC7G,uBAAO,IAAI,wEAAwE;AACvF;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -37,15 +37,21 @@ var import_stream = require("stream");
|
|
|
37
37
|
var farseer = __toESM(require("farseer-client"));
|
|
38
38
|
var import_httpError = require("../httpError");
|
|
39
39
|
const REQUEST_TIMEOUT_MS = 12e4;
|
|
40
|
-
const
|
|
40
|
+
const HEAD_TIMEOUT_MS = 3e5;
|
|
41
|
+
const APPLY_TIMEOUT_MS = 36e4;
|
|
41
42
|
const NEVER_SENT = /* @__PURE__ */ new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH"]);
|
|
42
43
|
const GATEWAY_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
|
|
44
|
+
const STALE_CONNECTION = /* @__PURE__ */ new Set(["ECONNRESET", "EPIPE", "UND_ERR_SOCKET"]);
|
|
43
45
|
function failureCodes(error, depth = 0) {
|
|
44
46
|
if (!(error instanceof Error) || depth > 4) return [];
|
|
45
47
|
const code = error.code;
|
|
46
48
|
const nested = [error.cause, ...error instanceof AggregateError ? error.errors : []];
|
|
47
49
|
return [...typeof code === "string" ? [code] : [], ...nested.flatMap((item) => failureCodes(item, depth + 1))];
|
|
48
50
|
}
|
|
51
|
+
function replayable(init, error) {
|
|
52
|
+
if ((init?.method ?? "GET") !== "GET" || init?.signal?.aborted) return false;
|
|
53
|
+
return failureCodes(error).some((code) => STALE_CONNECTION.has(code));
|
|
54
|
+
}
|
|
49
55
|
class TransportError extends Error {
|
|
50
56
|
constructor(cause) {
|
|
51
57
|
const codes = failureCodes(cause);
|
|
@@ -113,6 +119,13 @@ class CodeFirstApi {
|
|
|
113
119
|
headers: this.configuration.headers,
|
|
114
120
|
middleware: this.configuration.middleware,
|
|
115
121
|
fetchApi: async (input, init) => {
|
|
122
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
123
|
+
try {
|
|
124
|
+
return await send(input, init);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (!replayable(init, error)) throw new TransportError(error);
|
|
127
|
+
}
|
|
128
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
116
129
|
try {
|
|
117
130
|
return await send(input, init);
|
|
118
131
|
} catch (error) {
|
|
@@ -176,6 +189,7 @@ class CodeFirstApi {
|
|
|
176
189
|
}
|
|
177
190
|
head() {
|
|
178
191
|
return this.json("GET /codefirst/head", (init) => this.routes.headRaw(init), {
|
|
192
|
+
timeoutMs: HEAD_TIMEOUT_MS,
|
|
179
193
|
models: { 200: farseer.HeadFromJSON }
|
|
180
194
|
});
|
|
181
195
|
}
|
|
@@ -204,7 +218,13 @@ class CodeFirstApi {
|
|
|
204
218
|
deadline.settle();
|
|
205
219
|
}
|
|
206
220
|
}
|
|
207
|
-
/**
|
|
221
|
+
/**
|
|
222
|
+
* The answer must start within the timeout and then never fall silent for as long: every chunk
|
|
223
|
+
* restarts it, as an upload's does, so a large file streams to disk for as long as it takes. The
|
|
224
|
+
* session's undici `Agent` has no body timeout, so without this a stalled body would hold the
|
|
225
|
+
* download open forever. The deadline ends when the stream closes, whether it ended, failed or
|
|
226
|
+
* was destroyed by the caller.
|
|
227
|
+
*/
|
|
208
228
|
async downloadBlob(sha256) {
|
|
209
229
|
const deadline = requestDeadline(REQUEST_TIMEOUT_MS);
|
|
210
230
|
let response;
|
|
@@ -212,14 +232,26 @@ class CodeFirstApi {
|
|
|
212
232
|
response = await this.answer((init) => this.routes.downloadBlobRaw({ sha256 }, init), {
|
|
213
233
|
signal: deadline.signal
|
|
214
234
|
});
|
|
215
|
-
}
|
|
235
|
+
} catch (error) {
|
|
216
236
|
deadline.settle();
|
|
237
|
+
throw error;
|
|
217
238
|
}
|
|
218
239
|
if (response.status !== 200 || !response.body) {
|
|
240
|
+
deadline.settle();
|
|
219
241
|
await response.body?.cancel();
|
|
220
242
|
throw new Error(`Blob download failed (HTTP ${response.status})`);
|
|
221
243
|
}
|
|
222
|
-
|
|
244
|
+
const body = response.body.pipeThrough(
|
|
245
|
+
new TransformStream({
|
|
246
|
+
transform(chunk, output) {
|
|
247
|
+
deadline.progress();
|
|
248
|
+
output.enqueue(chunk);
|
|
249
|
+
}
|
|
250
|
+
})
|
|
251
|
+
);
|
|
252
|
+
const stream = import_stream.Readable.fromWeb(body);
|
|
253
|
+
stream.once("close", deadline.settle);
|
|
254
|
+
return stream;
|
|
223
255
|
}
|
|
224
256
|
/** A 400 is a plan with a top-level `code`, or a plain `{code, message}` error the commands tell apart. */
|
|
225
257
|
plan(documents, baseline) {
|
|
@@ -227,7 +259,8 @@ class CodeFirstApi {
|
|
|
227
259
|
return this.json(
|
|
228
260
|
"POST /codefirst/plans",
|
|
229
261
|
(init) => this.routes.planRaw({ planRequest }, init),
|
|
230
|
-
|
|
262
|
+
// The server reads the head for the plan, which takes a large tenant's first snapshot.
|
|
263
|
+
{ timeoutMs: HEAD_TIMEOUT_MS, models: PLAN_MODELS }
|
|
231
264
|
);
|
|
232
265
|
}
|
|
233
266
|
/** Only a 200 carries the stored plan; any other answer throws an `HttpError`. */
|