farseer-cli 1.17.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 +3 -3
- 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 +16 -7
- package/dist/commands/formula.js.map +1 -2
- 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 +120 -0
- package/dist/commands/tool.js.map +6 -0
- package/dist/commands/variables.js.map +0 -1
- package/dist/commands/whoami.js.map +0 -1
- package/dist/index.js +29 -12
- 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 +65 -23
- package/dist/mcp/tools/modelTools.js.map +2 -3
- package/dist/mcp/tools/pipelineContract.js.map +0 -1
- package/dist/mcp/tools/pipelineTools.js.map +0 -1
- package/dist/mcp/tools/runTools.js +6 -2
- package/dist/mcp/tools/runTools.js.map +1 -2
- 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 +1 -1
- package/dist/mcp/utils/launchPin.js.map +1 -2
- 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 +48 -0
- package/dist/utils/formulaFilters.js.map +6 -0
- 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 +14 -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/operations.ts"],
|
|
4
|
-
"sourcesContent": ["import type { PipelinePaths } from './connect';\nimport { createPipeline } from './create';\nimport { initPipelineProfile } from './init';\nimport type { PipelineClient, PipelineService } from './service';\n\n/**\n * The operations every surface (CLI command, MCP tool) exposes on a connected pipeline.\n * recover and unlock stay CLI-only: they resolve local state after a crash and are not\n * offered to a model.\n */\nexport const PIPELINE_OPERATIONS = [\n 'check',\n 'pull',\n 'push',\n 'run',\n 'runs',\n 'inspect',\n 'inspect-import',\n 'query',\n 'versions',\n 'restore',\n 'terminate',\n 'upgrade-runtime',\n] as const;\nexport type PipelineOperation = (typeof PIPELINE_OPERATIONS)[number];\n\nexport interface PipelineOperationArgs {\n /** Exact run UUID: for inspect (the local receipt's run when absent) and terminate (required). */\n uuid?: string;\n datasetId?: string;\n versionId?: string;\n /** The current version observed before restore; a stale value is refused by the backend. */\n expectedCurrent?: string;\n importId?: number;\n /** Log offset for inspect, from a previous page's nextOffset. */\n offset?: number;\n /** Ordered job arguments for run. */\n args?: string[];\n /** Version bindings {name, datasetId, versionId} or file bindings {name, file} for query. */\n bindings?: unknown[];\n sql?: string;\n /** Runs to list, newest first. */\n limit?: number;\n}\n\nexport interface PipelineInitSelection {\n organisation: string;\n tenant: string;\n /** Attach to a job somebody prepared; reads only. */\n jobId?: number;\n /** Create folder, job and profile for a new pipeline named after its folder. */\n name?: string;\n workspace?: string;\n force?: boolean;\n}\n\nfunction required<T>(name: keyof PipelineOperationArgs, value: T | undefined): T {\n if (value === undefined) throw new Error(`${name} is required`);\n return value;\n}\n\n/** One dispatcher for every surface, so an operation means the same call everywhere. */\nexport async function runPipelineOperation(\n service: PipelineService,\n operation: PipelineOperation,\n args: PipelineOperationArgs,\n signal?: AbortSignal,\n): Promise<unknown> {\n switch (operation) {\n case 'check':\n return service.check(signal);\n case 'pull':\n case 'push':\n return service.syncSources(operation);\n case 'run':\n return service.submit(args.args ?? []);\n case 'runs':\n return service.runs(args.limit);\n case 'inspect':\n return service.inspect(args.uuid, args.offset ?? 0);\n case 'inspect-import':\n return service.inspectImport(required('importId', args.importId));\n case 'versions':\n return service.versions(required('datasetId', args.datasetId));\n case 'restore':\n return service.restore(\n required('datasetId', args.datasetId),\n required('versionId', args.versionId),\n required('expectedCurrent', args.expectedCurrent),\n );\n case 'terminate':\n return service.terminate(required('uuid', args.uuid));\n case 'upgrade-runtime':\n return service.upgradeRuntime();\n case 'query': {\n const bindings = required('bindings', args.bindings);\n const sql = required('sql', args.sql);\n // A binding naming a dataset version reads immutable history; a file binding\n // reads the current mutable Farseer File. The first binding decides the mode.\n const versioned = (bindings[0] as { datasetId?: unknown } | undefined)?.datasetId !== undefined;\n return versioned\n ? service.queryVersions(bindings as Parameters<PipelineService['queryVersions']>[0], sql, signal)\n : service.query(bindings as Parameters<PipelineService['query']>[0], sql, signal);\n }\n default:\n throw new Error(\n `Unknown operation \"${String(operation)}\". Supported operations: ${PIPELINE_OPERATIONS.join(', ')}`,\n );\n }\n}\n\n/**\n * Attach to a prepared job or create a pipeline from nothing; exactly one of the two.\n * The selection is validated before the client is opened, so a bad call never touches the tenant.\n */\nexport async function runPipelineInit(\n selection: PipelineInitSelection,\n openClient: () => Promise<PipelineClient>,\n paths: PipelinePaths,\n) {\n const { organisation, tenant, jobId, name, workspace, force } = selection;\n if ((jobId === undefined) === (name === undefined))\n throw new Error('Pass either a prepared jobId or a new name, not both and not neither');\n if (name !== undefined) {\n if (workspace !== undefined || force !== undefined)\n throw new Error('workspace and force only apply when attaching to a prepared jobId');\n return createPipeline({ organisation, tenant, name }, await openClient(), paths);\n }\n return initPipelineProfile(\n { organisation, tenant, jobId: jobId as number, workspace, force },\n await openClient(),\n paths,\n );\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAA+B;AAC/B,kBAAoC;AAQ7B,MAAM,sBAAsB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ;AAiCA,SAAS,SAAY,MAAmC,OAAyB;AAC7E,MAAI,UAA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AAMA,eAAsB,gBAClB,WACA,YACA,OACF;AACE,QAAM,EAAE,cAAc,QAAQ,OAAO,MAAM,WAAW,MAAM,IAAI;AAChE,MAAK,UAAU,YAAgB,SAAS;AACpC,UAAM,IAAI,MAAM,sEAAsE;AAC1F,MAAI,SAAS,QAAW;AACpB,QAAI,cAAc,UAAa,UAAU;AACrC,YAAM,IAAI,MAAM,mEAAmE;AACvF,eAAO,8BAAe,EAAE,cAAc,QAAQ,KAAK,GAAG,MAAM,WAAW,GAAG,KAAK;AAAA,EACnF;AACA,aAAO;AAAA,IACH,EAAE,cAAc,QAAQ,OAAwB,WAAW,MAAM;AAAA,IACjE,MAAM,WAAW;AAAA,IACjB;AAAA,EACJ;AACJ;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/pipeline/query.ts"],
|
|
4
|
-
"sourcesContent": ["import { fork } from 'child_process';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { downloadQueryFiles } from './queryDownloads';\n\nexport interface QueryLimits {\n memoryMb: number;\n spillMb: number;\n threads: number;\n timeMs: number;\n inputBytes: number;\n rows: number;\n resultBytes: number;\n}\nexport const DEFAULT_LIMITS: Readonly<QueryLimits> = Object.freeze({\n memoryMb: 256,\n spillMb: 256,\n threads: 2,\n timeMs: 30_000,\n inputBytes: 256 * 1024 * 1024,\n rows: 1000,\n resultBytes: 256 * 1024,\n});\nexport interface QueryRequest {\n bindings: { name: string; url?: string; urls?: string[] }[];\n sql: string;\n limits: QueryLimits;\n /** Local test harness only; not an MCP/CLI argument. */\n loopbackTest?: boolean;\n}\nexport interface QueryResult {\n columns: string[];\n rows: unknown[][];\n truncated: boolean;\n complete: boolean;\n downloadedBytes: number;\n resultBytes: number;\n}\n\nexport async function queryFiles(\n request: QueryRequest,\n signal?: AbortSignal,\n download?: (binding: number, file: number, signal: AbortSignal) => Promise<Response>,\n): Promise<QueryResult> {\n if (signal?.aborted) throw new Error('Query cancelled');\n for (const value of Object.values(request.limits))\n if (!Number.isSafeInteger(value) || value <= 0) throw new Error('Invalid query limits');\n if (!request.bindings.length || request.bindings.length > 16 || request.sql.length > 100_000)\n throw new Error('Invalid query size or bindings');\n const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'farseer-pipeline-query-'));\n fs.chmodSync(directory, 0o700);\n const timeout = new AbortController();\n const querySignal = signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal;\n const cancelled = () => new Error(timeout.signal.aborted ? 'Query time limit exceeded' : 'Query cancelled');\n const timer = setTimeout(() => timeout.abort(), request.limits.timeMs);\n try {\n // The sandbox parent downloads through its authenticated backend connection. Only local\n // files reach the disposable SQL worker; it receives no credential or authenticated URL.\n const prepared = download\n ? await downloadQueryFiles(request, directory, (_address, binding, file) =>\n download(binding, file, querySignal),\n )\n : undefined;\n if (querySignal.aborted) throw cancelled();\n const worker = path.join(__dirname, 'queryWorker.js');\n const child = fork(worker, [], {\n stdio: ['ignore', 'ignore', 'ignore', 'ipc'],\n execArgv: [],\n // A laptop behind a TLS-inspecting proxy needs its extra CA for signed storage reads.\n env: {\n HOME: directory,\n TMPDIR: directory,\n LANG: 'en_US.UTF-8',\n ...(process.env.NODE_EXTRA_CA_CERTS ? { NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS } : {}),\n },\n });\n return await new Promise((resolve, reject) => {\n let outcome: { value?: QueryResult; error?: Error } | undefined;\n const finish = (next: typeof outcome) => {\n if (!outcome) {\n outcome = next;\n child.kill('SIGKILL');\n }\n };\n const cancel = () => finish({ error: cancelled() });\n querySignal.addEventListener('abort', cancel, { once: true });\n child.once('message', (message: any) =>\n finish(message.ok ? { value: message.result } : { error: new Error(message.error) }),\n );\n child.once('error', (error) => finish({ error }));\n child.once('exit', () => {\n querySignal.removeEventListener('abort', cancel);\n if (outcome?.value) resolve(outcome.value);\n else reject(outcome?.error ?? new Error('Query worker exited without a result'));\n });\n child.send({\n ...request,\n ...(prepared ? { bindings: request.bindings.map(({ name }) => ({ name })) } : {}),\n directory,\n prepared,\n });\n if (querySignal.aborted) cancel();\n });\n } catch (error) {\n if (querySignal.aborted) throw cancelled();\n throw error;\n } finally {\n clearTimeout(timer);\n fs.rmSync(directory, { recursive: true, force: true });\n }\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAAqB;AACrB,SAAoB;AACpB,SAAoB;AACpB,WAAsB;AACtB,4BAAmC;AAW5B,MAAM,iBAAwC,OAAO,OAAO;AAAA,EAC/D,UAAU;AAAA,EACV,SAAS;AAAA,EACT,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,YAAY,MAAM,OAAO;AAAA,EACzB,MAAM;AAAA,EACN,aAAa,MAAM;AACvB,CAAC;AAiBD,eAAsB,WAClB,SACA,QACA,UACoB;AACpB,MAAI,QAAQ,QAAS,OAAM,IAAI,MAAM,iBAAiB;AACtD,aAAW,SAAS,OAAO,OAAO,QAAQ,MAAM;AAC5C,QAAI,CAAC,OAAO,cAAc,KAAK,KAAK,SAAS,EAAG,OAAM,IAAI,MAAM,sBAAsB;AAC1F,MAAI,CAAC,QAAQ,SAAS,UAAU,QAAQ,SAAS,SAAS,MAAM,QAAQ,IAAI,SAAS;AACjF,UAAM,IAAI,MAAM,gCAAgC;AACpD,QAAM,YAAY,GAAG,YAAY,KAAK,KAAK,GAAG,OAAO,GAAG,yBAAyB,CAAC;AAClF,KAAG,UAAU,WAAW,GAAK;AAC7B,QAAM,UAAU,IAAI,gBAAgB;AACpC,QAAM,cAAc,SAAS,YAAY,IAAI,CAAC,QAAQ,QAAQ,MAAM,CAAC,IAAI,QAAQ;AACjF,QAAM,YAAY,MAAM,IAAI,MAAM,QAAQ,OAAO,UAAU,8BAA8B,iBAAiB;AAC1G,QAAM,QAAQ,WAAW,MAAM,QAA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,IAAI,MAAM,sCAAsC,CAAC;AAAA,MACnF,CAAC;AACD,YAAM,KAAK;AAAA,QACP,GAAG;AAAA,QACH,GAAI,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC,EAAE,KAAK,OAAO,EAAE,KAAK,EAAE,EAAE,IAAI,CAAC;AAAA,QAC/E;AAAA,QACA;AAAA,MACJ,CAAC;AACD,UAAI,YAAY,QAAS,QAAO;AAAA,IACpC,CAAC;AAAA,EACL,SAAS,OAAO;AACZ,QAAI,YAAY,QAAS,OAAM,UAAU;AACzC,UAAM;AAAA,EACV,UAAE;AACE,iBAAa,KAAK;AAClB,OAAG,OAAO,WAAW,EAAE,WAAW,MAAM,OAAO,KAAK,CAAC;AAAA,EACzD;AACJ;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/pipeline/queryDownloads.ts"],
|
|
4
|
-
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport type { QueryRequest } from './query';\n\nexport interface QueryFiles {\n groups: string[][];\n downloadedBytes: number;\n}\n\n/** Shared byte limits for direct signed downloads and authenticated backend downloads. */\nexport async function downloadQueryFiles(\n request: QueryRequest,\n directory: string,\n download: (address: string, binding: number, file: number) => Promise<Response>,\n): Promise<QueryFiles> {\n let downloadedBytes = 0;\n let fileCount = 0;\n const groups: string[][] = [];\n for (const [index, binding] of request.bindings.entries()) {\n const group: string[] = [];\n groups.push(group);\n const urls = binding.urls ?? (binding.url ? [binding.url] : []);\n if (!urls.length || urls.length > 512) throw new Error('Unsupported version file count');\n for (const [fileIndex, address] of urls.entries()) {\n const response = await download(address, index, fileIndex);\n if (!response.ok || !response.body) {\n await response.body?.cancel();\n throw new Error(`Dataset read failed (${response.status}); retry as a new query`);\n }\n const file = path.join(directory, `${fileCount++}.parquet`);\n const handle = await fs.promises.open(file, 'wx', 0o600);\n try {\n for await (const chunk of response.body as any) {\n downloadedBytes += chunk.byteLength;\n if (downloadedBytes > request.limits.inputBytes)\n throw new Error('Input download byte limit exceeded');\n await handle.write(chunk);\n }\n } finally {\n await handle.close();\n }\n group.push(file);\n }\n }\n return { groups, downloadedBytes };\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AAStB,eAAsB,mBAClB,SACA,WACA,UACmB;AACnB,MAAI,kBAAkB;AACtB,MAAI,YAAY;AAChB,QAAM,SAAqB,CAAC;AAC5B,aAAW,CAAC,OAAO,OAAO,KAAK,QAAQ,SAAS,QAAQ,GAAG;AACvD,UAAM,QAAkB,CAAC;AACzB,WAAO,KAAK,KAAK;AACjB,UAAM,OAAO,QAAQ,SAAS,QAAQ,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC;AAC7D,QAAI,CAAC,KAAK,UAAU,KAAK,SAAS,IAAK,OAAM,IAAI,MAAM,gCAAgC;AACvF,eAAW,CAAC,WAAW,OAAO,KAAK,KAAK,QAAQ,GAAG;AAC/C,YAAM,WAAW,MAAM,SAAS,SAAS,OAAO,SAAS;AACzD,UAAI,CAAC,SAAS,MAAM,CAAC,SAAS,MAAM;AAChC,cAAM,SAAS,MAAM,OAAO;AAC5B,cAAM,IAAI,MAAM,wBAAwB,SAAS,MAAM,yBAAyB;AAAA,MACpF;AACA,YAAM,OAAO,KAAK,KAAK,WAAW,GAAG,WAAW,UAAU;AAC1D,YAAM,SAAS,MAAM,GAAG,SAAS,KAAK,MAAM,MAAM,GAAK;AACvD,UAAI;AACA,yBAAiB,SAAS,SAAS,MAAa;AAC5C,6BAAmB,MAAM;AACzB,cAAI,kBAAkB,QAAQ,OAAO;AACjC,kBAAM,IAAI,MAAM,oCAAoC;AACxD,gBAAM,OAAO,MAAM,KAAK;AAAA,QAC5B;AAAA,MACJ,UAAE;AACE,cAAM,OAAO,MAAM;AAAA,MACvB;AACA,YAAM,KAAK,IAAI;AAAA,IACnB;AAAA,EACJ;AACA,SAAO,EAAE,QAAQ,gBAAgB;AACrC;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/pipeline/queryWorker.ts"],
|
|
4
|
-
"sourcesContent": ["// Runs in a disposable child process. No tenant token or user environment is inherited.\nimport { DuckDBInstance, StatementType } from '@duckdb/node-api';\nimport * as path from 'path';\nimport type { QueryRequest } from './query';\nimport { downloadQueryFiles, type QueryFiles } from './queryDownloads';\n\nconst literal = (s: string) => `'${s.replace(/'/g, \"''\")}'`;\nprocess.once('message', async (request: QueryRequest & { directory: string; prepared?: QueryFiles }) => {\n const { directory, limits } = request;\n try {\n const { groups, downloadedBytes } =\n request.prepared ??\n (await downloadQueryFiles(request, directory, async (address) => {\n const url = new URL(address);\n if (\n url.protocol !== 'https:' &&\n !(request.loopbackTest && url.protocol === 'http:' && url.hostname === '127.0.0.1')\n ) {\n throw new Error('Signed access must use HTTPS');\n }\n // One fixed grant, no credential forwarding, redirects or automatic rebinding.\n return fetch(url, { redirect: 'error' });\n }));\n const files = groups.flat();\n const db = await DuckDBInstance.create(':memory:', {\n memory_limit: `${limits.memoryMb}MB`,\n threads: String(limits.threads),\n temp_directory: path.join(directory, 'spill'),\n max_temp_directory_size: `${limits.spillMb}MB`,\n autoinstall_known_extensions: 'false',\n autoload_known_extensions: 'false',\n allow_unsigned_extensions: 'false',\n });\n const connection = await db.connect();\n await connection.run(`SET allowed_paths = [${files.map(literal).join(',')}]`);\n await connection.run('SET enable_external_access = false');\n for (const [i, binding] of request.bindings.entries()) {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/.test(binding.name)) throw new Error('Invalid SQL binding name');\n await connection.run(\n `CREATE VIEW \"${binding.name}\" AS SELECT * FROM read_parquet([${groups[i].map(literal).join(',')}])`,\n );\n }\n await connection.run('SET lock_configuration = true');\n const statements = await connection.extractStatements(request.sql);\n if (statements.count !== 1) throw new Error('Exactly one SELECT query is supported');\n const prepared = await statements.prepare(0);\n if (prepared.statementType !== StatementType.SELECT) throw new Error('Only SELECT queries are supported');\n prepared.destroySync();\n // Streaming avoids materializing an unbounded result in JS. Timeout includes downloads.\n const result = await connection.stream(request.sql);\n const rows: unknown[][] = [];\n let bytes = 0;\n let truncated = false;\n outer: for await (const chunk of result.yieldRowsJson()) {\n for (const row of chunk) {\n const size = Buffer.byteLength(JSON.stringify(row));\n if (rows.length >= limits.rows || bytes + size > limits.resultBytes) {\n truncated = true;\n break outer;\n }\n rows.push(row);\n bytes += size;\n }\n }\n process.send?.({\n ok: true,\n result: {\n columns: result.columnNames(),\n rows,\n truncated,\n complete: !truncated,\n downloadedBytes,\n resultBytes: bytes,\n },\n });\n } catch (error) {\n const message = String(error instanceof Error ? error.message : error)\n .replace(/https?:\\/\\/[^\\s'\"<>]+/g, '[signed URL redacted]')\n .split(directory)\n .join('[query temp]');\n process.send?.({ ok: false, error: message.slice(0, 2000) });\n } finally {\n process.disconnect();\n }\n});\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;AACA,sBAA8C;AAC9C,WAAsB;AAEtB,4BAAoD;AAEpD,MAAM,UAAU,CAAC,MAAc,IAAI,EAAE,QAAQ,MAAM,IAAI,CAAC;AACxD,QAAQ,KAAK,WAAW,OAAO,YAAyE;AACpG,QAAM,EAAE,WAAW,OAAO,IAAI;AAC9B,MAAI;AACA,UAAM,EAAE,QAAQ,gBAAgB,IAC5B,QAAQ,YACP,UAAM,0CAAmB,SAAS,WAAW,OAAO,YAAY;AAC7D,YAAM,MAAM,IAAI,IAAI,OAAO;AAC3B,UACI,IAAI,aAAa,YACjB,EAAE,QAAQ,gBAAgB,IAAI,aAAa,WAAW,IAAI,aAAa,cACzE;AACE,cAAM,IAAI,MAAM,8BAA8B;AAAA,MAClD;AAEA,aAAO,MAAM,KAAK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,OAAO,OAAO;AACrB,cAAM,OAAO,OAAO,WAAW,KAAK,UAAU,GAAG,CAAC;AAClD,YAAI,KAAK,UAAU,OAAO,QAAQ,QAAQ,OAAO,OAAO,aAAa;AACjE,sBAAY;AACZ,gBAAM;AAAA,QACV;AACA,aAAK,KAAK,GAAG;AACb,iBAAS;AAAA,MACb;AAAA,IACJ;AACA,YAAQ,OAAO;AAAA,MACX,IAAI;AAAA,MACJ,QAAQ;AAAA,QACJ,SAAS,OAAO,YAAY;AAAA,QAC5B;AAAA,QACA;AAAA,QACA,UAAU,CAAC;AAAA,QACX;AAAA,QACA,aAAa;AAAA,MACjB;AAAA,IACJ,CAAC;AAAA,EACL,SAAS,OAAO;AACZ,UAAM,UAAU,OAAO,iBAAiB,QAAQ,MAAM,UAAU,KAAK,EAChE,QAAQ,0BAA0B,uBAAuB,EACzD,MAAM,SAAS,EACf,KAAK,cAAc;AACxB,YAAQ,OAAO,EAAE,IAAI,OAAO,OAAO,QAAQ,MAAM,GAAG,GAAI,EAAE,CAAC;AAAA,EAC/D,UAAE;AACE,YAAQ,WAAW;AAAA,EACvB;AACJ,CAAC;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/pipeline/readiness.ts"],
|
|
4
|
-
"sourcesContent": ["import { boundedPipelineCall, pipelineRequestSignal } from './requests';\n\n/** Probe one fixed grant without tenant credentials, redirects, or a full download. */\nexport async function probeParquetAccess(address: string): Promise<void> {\n if (new URL(address).protocol !== 'https:') throw new Error('Signed read access must use HTTPS');\n await probeParquetPrefix((signal) =>\n fetch(address, {\n headers: { Range: 'bytes=0-3' },\n redirect: 'error',\n signal,\n }),\n );\n}\n\n/** Read a file's first four bytes, confirm the Parquet magic number, and stop the download there. */\nexport async function probeParquetPrefix(open: (signal: AbortSignal) => Promise<Response>): Promise<void> {\n await boundedPipelineCall(async () => {\n // boundedPipelineCall always sets the request signal.\n const response = await open(pipelineRequestSignal()!);\n if (!response.ok || !response.body) {\n await response.body?.cancel();\n throw new Error(`Read probe failed (${response.status})`);\n }\n const reader = response.body.getReader();\n const prefix: number[] = [];\n try {\n while (prefix.length < 4) {\n const next = await reader.read();\n if (next.done) break;\n prefix.push(...next.value.subarray(0, 4 - prefix.length));\n }\n if (Buffer.from(prefix).toString('ascii') !== 'PAR1') throw new Error('Probed file is not Parquet');\n } finally {\n await reader.cancel(); // Also stops servers that ignore Range, as the API's file route does.\n }\n });\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAA2D;AAG3D,eAAsB,mBAAmB,SAAgC;AACrE,MAAI,IAAI,IAAI,OAAO,EAAE,aAAa,SAAU,OAAM,IAAI,MAAM,mCAAmC;AAC/F,QAAM;AAAA,IAAmB,CAAC,WACtB,MAAM,SAAS;AAAA,MACX,SAAS,EAAE,OAAO,YAAY;AAAA,MAC9B,UAAU;AAAA,MACV;AAAA,IACJ,CAAC;AAAA,EACL;AACJ;AAGA,eAAsB,mBAAmB,MAAiE;AACtG,YAAM,qCAAoB,YAAY;AAElC,UAAM,WAAW,MAAM,SAAK,uCAAsB,CAAE;AACpD,QAAI,CAAC,SAAS,MAAM,CAAC,SAAS,MAAM;AAChC,YAAM,SAAS,MAAM,OAAO;AAC5B,YAAM,IAAI,MAAM,sBAAsB,SAAS,MAAM,GAAG;AAAA,IAC5D;AACA,UAAM,SAAS,SAAS,KAAK,UAAU;AACvC,UAAM,SAAmB,CAAC;AAC1B,QAAI;AACA,aAAO,OAAO,SAAS,GAAG;AACtB,cAAM,OAAO,MAAM,OAAO,KAAK;AAC/B,YAAI,KAAK,KAAM;AACf,eAAO,KAAK,GAAG,KAAK,MAAM,SAAS,GAAG,IAAI,OAAO,MAAM,CAAC;AAAA,MAC5D;AACA,UAAI,OAAO,KAAK,MAAM,EAAE,SAAS,OAAO,MAAM,OAAQ,OAAM,IAAI,MAAM,4BAA4B;AAAA,IACtG,UAAE;AACE,YAAM,OAAO,OAAO;AAAA,IACxB;AAAA,EACJ,CAAC;AACL;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/pipeline/reference.ts"],
|
|
4
|
-
"sourcesContent": ["import reference from './generated-reference.json';\nimport { PIPELINE_GUIDE, PIPELINE_PRACTICES } from './guide';\nimport { CLI_VERSION } from '../utils/constants';\nimport { inAgentSandbox } from '../utils/agentSandbox';\n\n/** The engine line (major.minor) this CLI's grammar describes. Patch releases keep the grammar. */\nexport const PIPELINE_ENGINE_PROFILE = reference.engineProfile;\n\nexport interface EngineReport {\n /** Engine version the run reported at startup, or null when no start marker was inspected. */\n ran: string | null;\n /** Engine line (major.minor) this CLI's bundled grammar describes. */\n expected: string;\n status: 'match' | 'mismatch' | 'unobserved';\n}\n\n/** Compare the engine line a run actually started on against the one this CLI's grammar describes. */\nexport function engineReport(observations: Record<string, unknown>[]): EngineReport {\n const expected = PIPELINE_ENGINE_PROFILE;\n const started = observations.find((o) => o.event === 'pipeline_started');\n const ran = typeof started?.version === 'string' ? started.version : null;\n if (ran === null) return { ran, expected, status: 'unobserved' };\n const line = ran.split('.').slice(0, 2).join('.');\n return { ran, expected, status: line === expected ? 'match' : 'mismatch' };\n}\n// An agent sandbox's CLI is part of its image and the sandbox cannot reach npm; a conversation keeps\n// its image, so only a new chat (on the deployment's current image) can bring a newer CLI.\nexport const CLI_UPDATE_INSTRUCTION = inAgentSandbox()\n ? \"This chat's CLI comes with its sandbox and cannot be updated here; do not try to install one. Tell the user that a new chat starts with the newest CLI this deployment provides, and that if it is still too old, a Labs admin must update the sandbox image.\"\n : 'Update to the latest compatible CLI: npm install -g farseer-cli@latest. Restart the MCP connection in your AI client after updating. Until the matching CLI is published, install the build supplied by the setup owner.';\n\nexport function pipelineGuide(topic = 'method'): string {\n const header =\n `Pipeline authoring reference: engine ${reference.engineVersion}; CLI ${CLI_VERSION}.\\n` +\n 'This is the bundled reference for the prepared pipeline runtime; the engine was not detected from a job.\\n\\n';\n if (topic === 'method')\n return (\n header +\n PIPELINE_GUIDE +\n '\\nRead topic=\"grammar\" for the generated YAML reference, then request the model names it links to.\\n' +\n CLI_UPDATE_INSTRUCTION\n );\n if (topic === 'practices') return header + PIPELINE_PRACTICES;\n const topics: Record<string, string> = reference.topics;\n if (topic === 'grammar')\n return (\n header +\n reference.notice +\n '\\n\\n' +\n topics.DatasetDefinition +\n '\\nAvailable topics (use their exact names as topic):\\n' +\n Object.keys(topics).join(', ')\n );\n if (!Object.prototype.hasOwnProperty.call(topics, topic))\n throw new Error(`Unknown guide topic \"${topic}\". Read topic=\"grammar\" to list supported model names.`);\n return header + reference.notice + '\\n\\n' + topics[topic];\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iCAAsB;AACtB,mBAAmD;AACnD,uBAA4B;AAC5B,0BAA+B;AAGxB,MAAM,0BAA0B,2BAAAA,QAAU;AAW1C,SAAS,aAAa,cAAuD;AAChF,QAAM,WAAW;AACjB,QAAM,UAAU,aAAa,KAAK,CAAC,MAAM,EAAE,UAAU,kBAAkB;AACvE,QAAM,MAAM,OAAO,SAAS,YAAY,WAAW,QAAQ,UAAU;AACrE,MAAI,QAAQ,KAAM,QAAO,EAAE,KAAK,UAAU,QAAQ,aAAa;AAC/D,QAAM,OAAO,IAAI,MAAM,GAAG,EAAE,MAAM,GAAG,CAAC,EAAE,KAAK,GAAG;AAChD,SAAO,EAAE,KAAK,UAAU,QAAQ,SAAS,WAAW,UAAU,WAAW;AAC7E;AAGO,MAAM,6BAAyB,oCAAe,IAC/C,kQACA;AAEC,SAAS,cAAc,QAAQ,UAAkB;AACpD,QAAM,SACF,wCAAwC,2BAAAA,QAAU,aAAa,SAAS,4BAAW;AAAA;AAAA;AAAA;AAEvF,MAAI,UAAU;AACV,WACI,SACA,8BACA,yGACA;AAER,MAAI,UAAU,YAAa,QAAO,SAAS;AAC3C,QAAM,SAAiC,2BAAAA,QAAU;AACjD,MAAI,UAAU;AACV,WACI,SACA,2BAAAA,QAAU,SACV,SACA,OAAO,oBACP,2DACA,OAAO,KAAK,MAAM,EAAE,KAAK,IAAI;AAErC,MAAI,CAAC,OAAO,UAAU,eAAe,KAAK,QAAQ,KAAK;AACnD,UAAM,IAAI,MAAM,wBAAwB,KAAK,wDAAwD;AACzG,SAAO,SAAS,2BAAAA,QAAU,SAAS,SAAS,OAAO,KAAK;AAC5D;",
|
|
6
5
|
"names": ["reference"]
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/pipeline/requests.ts"],
|
|
4
|
-
"sourcesContent": ["import { AsyncLocalStorage } from 'async_hooks';\n\nexport const PIPELINE_REQUEST_TIMEOUT_MS = 30_000;\ntype RequestContext = { signal?: AbortSignal; timeoutMs: number; parent?: RequestContext; pause?: () => () => void };\nconst context = new AsyncLocalStorage<RequestContext>();\n\n// Only pipeline operations opt in. SDK helpers and authentication share their caller's\n// cancellation without changing the rest of the CLI's networking policy.\nexport function withPipelineRequests<T>(\n fn: () => Promise<T>,\n signal?: AbortSignal,\n timeoutMs = PIPELINE_REQUEST_TIMEOUT_MS,\n) {\n signal?.throwIfAborted();\n return context.run({ signal, timeoutMs }, fn);\n}\n\nexport function pipelineRequestSignal(existing?: AbortSignal | null): AbortSignal | undefined {\n const signal = context.getStore()?.signal;\n signal?.throwIfAborted();\n return signal && existing ? AbortSignal.any([signal, existing]) : (signal ?? existing ?? undefined);\n}\n\nexport function pipelineFetch(fetcher: typeof fetch = (...args) => fetch(...args)): typeof fetch {\n return (input, init) => fetcher(input, { ...init, signal: pipelineRequestSignal(init?.signal) });\n}\n\n/** Human approval is not network time. Cancellation and the turn's own deadline still apply. */\nexport function pausePipelineDeadlines(): () => void {\n const resume: (() => void)[] = [];\n for (let current = context.getStore(); current; current = current.parent)\n if (current.pause) resume.push(current.pause());\n return () => resume.forEach((fn) => fn());\n}\n\nexport async function boundedPipelineCall<T>(fn: () => Promise<T>): Promise<T> {\n const parent = context.getStore();\n const controller = new AbortController();\n const signal = parent?.signal ? AbortSignal.any([parent.signal, controller.signal]) : controller.signal;\n signal.throwIfAborted();\n const timeoutMs = parent?.timeoutMs ?? PIPELINE_REQUEST_TIMEOUT_MS;\n let remaining = timeoutMs;\n let started = Date.now();\n let pauses = 0;\n let finished = false;\n const startTimer = () =>\n setTimeout(\n () =>\n controller.abort(\n new Error(\n 'Pipeline request timed out. A write may have been accepted; inspect its outcome before retrying.',\n ),\n ),\n remaining,\n );\n let timer = startTimer();\n const pause = () => {\n if (pauses++ === 0) {\n clearTimeout(timer);\n remaining = Math.max(0, remaining - (Date.now() - started));\n }\n let resumed = false;\n return () => {\n if (resumed) return;\n resumed = true;\n if (--pauses === 0 && !finished) {\n started = Date.now();\n timer = startTimer();\n }\n };\n };\n let cancel: () => void = () => undefined;\n try {\n // The signal aborts real HTTP I/O. The race also bounds legacy helpers\n // which swallow errors or wait for a shared authentication refresh.\n return await Promise.race([\n context.run({ signal, timeoutMs, parent, pause }, fn),\n new Promise<never>((_, reject) => {\n cancel = () => reject(signal.reason);\n signal.addEventListener('abort', cancel, { once: true });\n if (signal.aborted) cancel();\n }),\n ]);\n } finally {\n finished = true;\n clearTimeout(timer);\n signal.removeEventListener('abort', cancel);\n }\n}\n\nexport function boundedPipelineClient<T extends object>(client: T): T {\n const synchronous = new Set(['updateAccessToken', 'isTextFile', 'isBinaryFile']);\n return new Proxy(client, {\n get(target, key) {\n const value = Reflect.get(target, key);\n if (typeof value !== 'function') return value;\n const call = (...args: unknown[]) => value.apply(target, args);\n return synchronous.has(String(key))\n ? call\n : (...args: unknown[]) => boundedPipelineCall(() => call(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ACA,IAAI,SAAoB,oBAAoB,MAAM,KAAK,GAAG,IAAI,CAAC;AAAA,IACzE;AAAA,EACJ,CAAC;AACL;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/pipeline/runArguments.ts"],
|
|
4
|
-
"sourcesContent": ["import type { AppArgument } from '../services/apps';\nimport { PipelineError } from './errors';\n\n/**\n * Run arguments by name. The backend takes a run's arguments by position, in the order the job\n * declares them, and an empty slot keeps that argument's default. A positional value an author\n * meant for a later argument therefore lands silently in the first one, which may be a secret.\n * So the CLI and the MCP tool take `NAME=value` entries only, and this builds the positional list.\n */\nexport function resolveRunArguments(\n declared: readonly AppArgument[],\n entries: readonly string[],\n): { positional: string[]; given: Record<string, string> } {\n const byName = new Map(declared.map((a) => [a.name, a]));\n const values = new Map<string, string>();\n for (const entry of entries) {\n const at = entry.indexOf('=');\n if (at <= 0)\n throw refused(\n declared,\n `Run argument \"${entry}\" must be NAME=value, naming one of this job's arguments (${names(declared)}).`,\n );\n const name = entry.slice(0, at);\n const argument = byName.get(name);\n if (!argument)\n throw refused(declared, `${name} is not an argument of this job. Its arguments are: ${names(declared)}.`);\n if (argument.fixed) throw refused(declared, `${name} is fixed on this job, so a run cannot change it.`);\n if (values.has(name)) throw refused(declared, `${name} is given twice.`);\n const value = entry.slice(at + 1);\n if (value === '')\n throw refused(\n declared,\n `${name} cannot be empty: the backend runs an empty value with the argument's default. Leave ${name} out to keep its default, or give it a value.`,\n );\n values.set(name, value);\n }\n const given: Record<string, string> = {};\n for (const [name, value] of values) given[name] = byName.get(name)?.secret ? '****' : value;\n return { positional: declared.map((a) => values.get(a.name) ?? ''), given };\n}\n\nfunction refused(declared: readonly AppArgument[], message: string): PipelineError {\n return new PipelineError(\n 'refused',\n 'INVALID_ARGUMENTS',\n message,\n `Pass job arguments as NAME=value, naming only this job's arguments (${names(declared)}); nothing was submitted.`,\n );\n}\n\nfunction names(declared: readonly AppArgument[]): string {\n return declared.length ? declared.map((a) => a.name).join(', ') : 'none';\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,oBAA8B;AAQvB,SAAS,oBACZ,UACA,SACuD;AACvD,QAAM,SAAS,IAAI,IAAI,SAAS,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;AACvD,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,SAAS,SAAS;AACzB,UAAM,KAAK,MAAM,QAAQ,GAAG;AAC5B,QAAI,MAAM;AACN,YAAM;AAAA,QACF;AAAA,QACA,iBAAiB,KAAK,6DAA6D,MAAM,QAAQ,CAAC;AAAA,MACtG;AACJ,UAAM,OAAO,MAAM,MAAM,GAAG,EAAE;AAC9B,UAAM,WAAW,OAAO,IAAI,IAAI;AAChC,QAAI,CAAC;AACD,YAAM,QAAQ,UAAU,GAAG,IAAI,uDAAuD,MAAM,QAAQ,CAAC,GAAG;AAC5G,QAAI,SAAS,MAAO,OAAM,QAAQ,UAAU,GAAG,IAAI,mDAAmD;AACtG,QAAI,OAAO,IAAI,IAAI,EAAG,OAAM,QAAQ,UAAU,GAAG,IAAI,kBAAkB;AACvE,UAAM,QAAQ,MAAM,MAAM,KAAK,CAAC;AAChC,QAAI,UAAU;AACV,YAAM;AAAA,QACF;AAAA,QACA,GAAG,IAAI,wFAAwF,IAAI;AAAA,MACvG;AACJ,WAAO,IAAI,MAAM,KAAK;AAAA,EAC1B;AACA,QAAM,QAAgC,CAAC;AACvC,aAAW,CAAC,MAAM,KAAK,KAAK,OAAQ,OAAM,IAAI,IAAI,OAAO,IAAI,IAAI,GAAG,SAAS,SAAS;AACtF,SAAO,EAAE,YAAY,SAAS,IAAI,CAAC,MAAM,OAAO,IAAI,EAAE,IAAI,KAAK,EAAE,GAAG,MAAM;AAC9E;AAEA,SAAS,QAAQ,UAAkC,SAAgC;AAC/E,SAAO,IAAI;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA,uEAAuE,MAAM,QAAQ,CAAC;AAAA,EAC1F;AACJ;AAEA,SAAS,MAAM,UAA0C;AACrD,SAAO,SAAS,SAAS,SAAS,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,IAAI,IAAI;AACtE;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/pipeline/runtime.ts"],
|
|
4
|
-
"sourcesContent": ["import reference from './generated-reference.json';\nimport { CLI_UPDATE_INSTRUCTION } from './reference';\nimport { PipelineError } from './errors';\nimport { inAgentSandbox } from '../utils/agentSandbox';\n\n/** The runner image tag this CLI was released in tandem with, as `<repository>:<version>`. */\nexport const PIPELINE_RUNNER_IMAGE: string = reference.runnerImage;\n\nexport interface RuntimeComparison {\n status: 'match' | 'behind' | 'ahead' | 'unversioned' | 'incompatible';\n /** Version parsed from the job's image tag, or null when the tag is not a release version. */\n jobVersion: string | null;\n /** Version this CLI authors for. */\n expected: string;\n nextAction: string;\n}\n\nconst RELEASE_VERSION = /^\\d+\\.\\d+\\.\\d+$/;\n\nfunction split(image: string): { repository: string; tag: string | null } {\n const name = image.slice(image.lastIndexOf('/') + 1);\n if (name.includes('@')) return { repository: name.slice(0, name.indexOf('@')).split(':')[0], tag: null };\n const colon = name.indexOf(':');\n return colon < 0\n ? { repository: name, tag: null }\n : { repository: name.slice(0, colon), tag: name.slice(colon + 1) };\n}\n\n/** Numeric three-part comparison; negative when `a` is older than `b`. */\nexport function compareVersions(a: string, b: string): number {\n const [pa, pb] = [a, b].map((v) => v.split('.').map(Number));\n for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pa[i] < pb[i] ? -1 : 1;\n return 0;\n}\n\n/**\n * The CLI authors for exactly one engine: the one inside the runner image it was\n * released with. It never changes a job's image on its own: a job behind it is moved\n * up only by upgrade-runtime, a CLI behind a job is updated, and nothing moves down.\n */\nexport function compareRuntime(jobImage: string): RuntimeComparison {\n const bundled = split(PIPELINE_RUNNER_IMAGE);\n const expected = bundled.tag ?? '';\n const job = split(jobImage);\n if (job.repository !== bundled.repository)\n return {\n status: 'incompatible',\n jobVersion: null,\n expected,\n nextAction:\n 'Use the existing app tools to inspect, run or maintain this app in its current implementation. Do not change its runner or entrypoint to satisfy pipeline setup. Migration to Simple Pipelines requires an explicit migration request.',\n };\n if (!job.tag || !RELEASE_VERSION.test(job.tag))\n return {\n status: 'unversioned',\n jobVersion: null,\n expected,\n nextAction: `The job's image \"${jobImage}\" is a moving tag or digest, not a released ${bundled.repository} version, so this CLI leaves the image as it is. Each run reports the engine it started on: read engine in inspect.`,\n };\n const order = compareVersions(job.tag, expected);\n if (order === 0) return { status: 'match', jobVersion: job.tag, expected, nextAction: '' };\n if (order < 0)\n return {\n status: 'behind',\n jobVersion: job.tag,\n expected,\n nextAction: `The job runs ${bundled.repository}:${job.tag}; this CLI authors for ${expected}. Run, pull and reads work on the job's image, but push is refused until the job is upgraded: ask the user, then run upgrade-runtime, which moves the job to ${PIPELINE_RUNNER_IMAGE} for everyone on the tenant and for its next scheduled run.${inAgentSandbox() ? '' : ' Or keep the job on its image and author with the CLI release that targets it.'}`,\n };\n return {\n status: 'ahead',\n jobVersion: job.tag,\n expected,\n nextAction: `The job runs ${bundled.repository}:${job.tag}; this CLI authors for ${expected}. Run and push work on the job's image, but this CLI does not describe what the newer engine added. ${CLI_UPDATE_INSTRUCTION}`,\n };\n}\n\n/** Version pinning may upgrade Simple Pipelines, but must never convert another kind of app. */\nexport function assertPipelineRuntime(jobImage: string): RuntimeComparison {\n const runtime = compareRuntime(jobImage);\n if (runtime.status === 'incompatible')\n throw new PipelineError(\n 'refused',\n 'PIPELINE_RUNTIME_UNSUPPORTED',\n `Runner image \"${jobImage || '(tenant default or unknown)'}\" is not a Simple Pipelines runner. The existing app must be preserved.`,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AC,IAAI,OAAO,CAAC,gBAAgB,KAAK,IAAI,GAAG;AACzC,WAAO;AAAA,MACH,QAAQ;AAAA,MACR,YAAY;AAAA,MACZ;AAAA,MACA,YAAY,oBAAoB,QAAQ,+CAA+C,QAAQ,UAAU;AAAA,IAC7G;AACJ,QAAM,QAAQ,gBAAgB,IAAI,KAAK,QAAQ;AAC/C,MAAI,UAAU,EAAG,QAAO,EAAE,QAAQ,SAAS,YAAY,IAAI,KAAK,UAAU,YAAY,GAAG;AACzF,MAAI,QAAQ;AACR,WAAO;AAAA,MACH,QAAQ;AAAA,MACR,YAAY,IAAI;AAAA,MAChB;AAAA,MACA,YAAY,gBAAgB,QAAQ,UAAU,IAAI,IAAI,GAAG,0BAA0B,QAAQ,gKAAgK,qBAAqB,kEAA8D,oCAAe,IAAI,KAAK,gFAAgF;AAAA,IAC1b;AACJ,SAAO;AAAA,IACH,QAAQ;AAAA,IACR,YAAY,IAAI;AAAA,IAChB;AAAA,IACA,YAAY,gBAAgB,QAAQ,UAAU,IAAI,IAAI,GAAG,0BAA0B,QAAQ,uGAAuG,uCAAsB;AAAA,EAC5N;AACJ;AAGO,SAAS,sBAAsB,UAAqC;AACvE,QAAM,UAAU,eAAe,QAAQ;AACvC,MAAI,QAAQ,WAAW;AACnB,UAAM,IAAI;AAAA,MACN;AAAA,MACA;AAAA,MACA,iBAAiB,YAAY,6BAA6B;AAAA,MAC1D,QAAQ;AAAA,IACZ;AACJ,SAAO;AACX;",
|
|
6
5
|
"names": ["reference"]
|
|
7
6
|
}
|
|
@@ -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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W;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,EACJ;AACI,eAAW,SAAS,OAAO,SAAS,OAAO,EAAG,OAAM,IAAI,MAAM,CAAC,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,S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
|
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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