farseer-cli 1.13.0 → 1.14.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +23 -8
  2. package/dist/commands/config.js +4 -3
  3. package/dist/commands/config.js.map +2 -2
  4. package/dist/commands/install.js +5 -0
  5. package/dist/commands/install.js.map +2 -2
  6. package/dist/commands/login.js +2 -2
  7. package/dist/commands/login.js.map +2 -2
  8. package/dist/commands/pipeline.js +158 -0
  9. package/dist/commands/pipeline.js.map +7 -0
  10. package/dist/commands/pull.js +2 -1
  11. package/dist/commands/pull.js.map +2 -2
  12. package/dist/commands/run.js +9 -0
  13. package/dist/commands/run.js.map +2 -2
  14. package/dist/commands/variables.js +17 -8
  15. package/dist/commands/variables.js.map +2 -2
  16. package/dist/index.js +45 -46
  17. package/dist/index.js.map +2 -2
  18. package/dist/mcp/prompts/workflows.js +13 -68
  19. package/dist/mcp/prompts/workflows.js.map +2 -2
  20. package/dist/mcp/resources/documentation.js +14 -0
  21. package/dist/mcp/resources/documentation.js.map +2 -2
  22. package/dist/mcp/server.js +14 -2
  23. package/dist/mcp/server.js.map +2 -2
  24. package/dist/mcp/skills.js +59 -0
  25. package/dist/mcp/skills.js.map +7 -0
  26. package/dist/mcp/tools/appTools.js +4 -0
  27. package/dist/mcp/tools/appTools.js.map +2 -2
  28. package/dist/mcp/tools/authTools.js +5 -3
  29. package/dist/mcp/tools/authTools.js.map +2 -2
  30. package/dist/mcp/tools/cellTools.js +3 -2
  31. package/dist/mcp/tools/cellTools.js.map +2 -2
  32. package/dist/mcp/tools/dashboardTools.js +23 -18
  33. package/dist/mcp/tools/dashboardTools.js.map +2 -2
  34. package/dist/mcp/tools/dataTools.js +16 -12
  35. package/dist/mcp/tools/dataTools.js.map +2 -2
  36. package/dist/mcp/tools/folderTools.js +5 -4
  37. package/dist/mcp/tools/folderTools.js.map +2 -2
  38. package/dist/mcp/tools/modelTools.js +33 -58
  39. package/dist/mcp/tools/modelTools.js.map +2 -2
  40. package/dist/mcp/tools/pipelineContract.js +320 -0
  41. package/dist/mcp/tools/pipelineContract.js.map +7 -0
  42. package/dist/mcp/tools/pipelineTools.js +111 -0
  43. package/dist/mcp/tools/pipelineTools.js.map +7 -0
  44. package/dist/mcp/tools/runTools.js +10 -3
  45. package/dist/mcp/tools/runTools.js.map +2 -2
  46. package/dist/mcp/tools/sheetTools.js +21 -17
  47. package/dist/mcp/tools/sheetTools.js.map +2 -2
  48. package/dist/mcp/tools/syncTools.js +15 -5
  49. package/dist/mcp/tools/syncTools.js.map +2 -2
  50. package/dist/mcp/utils/registerTool.js +32 -0
  51. package/dist/mcp/utils/registerTool.js.map +7 -0
  52. package/dist/pipeline/compatibility.js +53 -0
  53. package/dist/pipeline/compatibility.js.map +7 -0
  54. package/dist/pipeline/connect.js +139 -0
  55. package/dist/pipeline/connect.js.map +7 -0
  56. package/dist/pipeline/create.js +158 -0
  57. package/dist/pipeline/create.js.map +7 -0
  58. package/dist/pipeline/errors.js +45 -0
  59. package/dist/pipeline/errors.js.map +7 -0
  60. package/dist/pipeline/generated-reference.json +115 -0
  61. package/dist/pipeline/guide.js +33 -0
  62. package/dist/pipeline/guide.js.map +7 -0
  63. package/dist/pipeline/init.js +204 -0
  64. package/dist/pipeline/init.js.map +7 -0
  65. package/dist/pipeline/operations.js +106 -0
  66. package/dist/pipeline/operations.js.map +7 -0
  67. package/dist/pipeline/query.js +121 -0
  68. package/dist/pipeline/query.js.map +7 -0
  69. package/dist/pipeline/queryDownloads.js +72 -0
  70. package/dist/pipeline/queryDownloads.js.map +7 -0
  71. package/dist/pipeline/queryWorker.js +96 -0
  72. package/dist/pipeline/queryWorker.js.map +7 -0
  73. package/dist/pipeline/readiness.js +62 -0
  74. package/dist/pipeline/readiness.js.map +7 -0
  75. package/dist/pipeline/reference.js +73 -0
  76. package/dist/pipeline/reference.js.map +7 -0
  77. package/dist/pipeline/requests.js +122 -0
  78. package/dist/pipeline/requests.js.map +7 -0
  79. package/dist/pipeline/runArguments.js +68 -0
  80. package/dist/pipeline/runArguments.js.map +7 -0
  81. package/dist/pipeline/runtime.js +106 -0
  82. package/dist/pipeline/runtime.js.map +7 -0
  83. package/dist/pipeline/service.js +1027 -0
  84. package/dist/pipeline/service.js.map +7 -0
  85. package/dist/services/agentApprovalFetch.js +86 -0
  86. package/dist/services/agentApprovalFetch.js.map +7 -0
  87. package/dist/services/appSyncService.js.map +1 -1
  88. package/dist/services/configService.js +40 -4
  89. package/dist/services/configService.js.map +2 -2
  90. package/dist/services/credentials.js +2 -0
  91. package/dist/services/credentials.js.map +2 -2
  92. package/dist/services/farseerService.js +33 -3
  93. package/dist/services/farseerService.js.map +2 -2
  94. package/dist/services/modelExport.js.map +1 -1
  95. package/dist/services/preflight.js +4 -0
  96. package/dist/services/preflight.js.map +2 -2
  97. package/dist/services/syncService.js +6 -0
  98. package/dist/services/syncService.js.map +2 -2
  99. package/dist/skills/pipeline.js +71 -0
  100. package/dist/skills/pipeline.js.map +7 -0
  101. package/dist/utils/agentSandbox.js +35 -0
  102. package/dist/utils/agentSandbox.js.map +7 -0
  103. package/dist/utils/helpers.js +2 -1
  104. package/dist/utils/helpers.js.map +2 -2
  105. package/dist/utils/variableValues.js +78 -0
  106. package/dist/utils/variableValues.js.map +7 -0
  107. package/docs/pipeline-client-guide.md +67 -0
  108. package/docs/pipeline-reference.md +2064 -0
  109. package/package.json +5 -1
  110. package/skills/pipeline-authoring/SKILL.md +95 -0
  111. package/skills/pipeline-authoring/practices.md +325 -0
@@ -0,0 +1,1027 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var service_exports = {};
30
+ __export(service_exports, {
31
+ BLANK_SETUP: () => BLANK_SETUP,
32
+ PipelineService: () => PipelineService,
33
+ SCHEDULE_NOTE: () => SCHEDULE_NOTE,
34
+ loadOutcomes: () => loadOutcomes,
35
+ localSourceFiles: () => localSourceFiles,
36
+ pipelineArgumentNames: () => pipelineArgumentNames,
37
+ profileSchema: () => profileSchema,
38
+ readPipelineProfileFile: () => readPipelineProfileFile,
39
+ redact: () => redact,
40
+ scheduleCheck: () => scheduleCheck,
41
+ skippedOutputs: () => skippedOutputs,
42
+ sourcePath: () => sourcePath
43
+ });
44
+ module.exports = __toCommonJS(service_exports);
45
+ var import_runArguments = require("./runArguments");
46
+ var fs = __toESM(require("fs"));
47
+ var path = __toESM(require("path"));
48
+ var import_crypto = require("crypto");
49
+ var import_zod = require("zod");
50
+ var import_syncService = require("../services/syncService");
51
+ var import_query = require("./query");
52
+ var import_reference = require("./reference");
53
+ var import_runtime = require("./runtime");
54
+ var import_constants = require("../utils/constants");
55
+ var import_apps = require("../services/apps");
56
+ var import_requests = require("./requests");
57
+ var import_readiness = require("./readiness");
58
+ var import_errors = require("./errors");
59
+ var import_agentSandbox = require("../utils/agentSandbox");
60
+ const relative = import_zod.z.string().min(1).refine(
61
+ (s) => !s.includes("\\") && !s.startsWith("/") && s.split("/").every((p) => p && p !== "." && p !== ".." && !p.startsWith(".")),
62
+ "Expected a non-hidden relative path"
63
+ );
64
+ const recordedSetupSchema = import_zod.z.object({
65
+ owner: import_zod.z.string().min(1),
66
+ checkedAt: import_zod.z.string().datetime({ offset: true }),
67
+ evidence: import_zod.z.string().min(1),
68
+ retentionDays: import_zod.z.number().int().positive(),
69
+ otherWritersExcluded: import_zod.z.literal(true),
70
+ runtimeVerified: import_zod.z.literal(true)
71
+ }).strict();
72
+ const profileSchema = import_zod.z.object({
73
+ organisation: import_zod.z.string().min(1),
74
+ tenant: import_zod.z.string().min(1),
75
+ author: import_zod.z.string().min(1).default("shared"),
76
+ datasetIds: import_zod.z.array(import_zod.z.string().uuid()).max(100).default([]),
77
+ jobId: import_zod.z.number().int().positive(),
78
+ sourceFolderId: import_zod.z.number().int().positive(),
79
+ workspace: relative,
80
+ entrypoint: relative,
81
+ /** Recorded by older profiles; the job's live image is what counts. */
82
+ runnerImage: import_zod.z.string().min(1).optional(),
83
+ /** The job's schedule when init ran; null for none, absent in profiles from before this was recorded. */
84
+ schedule: import_zod.z.string().min(1).nullable().optional(),
85
+ engine: import_zod.z.string().min(1),
86
+ configFiles: import_zod.z.array(relative).default([]),
87
+ setup: import_zod.z.record(import_zod.z.unknown()).optional()
88
+ }).strict();
89
+ function readPipelineProfileFile(file) {
90
+ return profileSchema.parse(JSON.parse(fs.readFileSync(file, "utf8")));
91
+ }
92
+ const BLANK_SETUP = {
93
+ owner: "",
94
+ checkedAt: "",
95
+ evidence: "",
96
+ retentionDays: 0,
97
+ otherWritersExcluded: false,
98
+ runtimeVerified: false
99
+ };
100
+ function readSetup(setup) {
101
+ const parsed = recordedSetupSchema.safeParse(setup ?? {});
102
+ if (parsed.success) return { recorded: parsed.data };
103
+ const fields = parsed.error.issues.flatMap(
104
+ (issue) => issue.code === "unrecognized_keys" ? issue.keys.map((key) => `${key} (not a setup field)`) : [String(issue.path[0])]
105
+ );
106
+ return { missing: [...new Set(fields)].join(", ") };
107
+ }
108
+ const CLOCK_SKEW_MARGIN_MS = 10 * 60 * 1e3;
109
+ const RECOVER_HINT = "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.";
110
+ const terminal = (status) => ["FINISHED", "ERROR"].includes(status);
111
+ const digest = (data) => (0, import_crypto.createHash)("sha256").update(data).digest("hex");
112
+ class WorkspaceSync extends import_syncService.SyncService {
113
+ constructor(tenant, client, stateFile) {
114
+ super(tenant, client);
115
+ this.stateFile = stateFile;
116
+ }
117
+ loadSyncState() {
118
+ return fs.existsSync(this.stateFile) ? JSON.parse(fs.readFileSync(this.stateFile, "utf8")) : { lastSync: "", files: {} };
119
+ }
120
+ saveSyncState(state) {
121
+ const tmp = `${this.stateFile}.${(0, import_crypto.randomUUID)()}`;
122
+ fs.writeFileSync(tmp, JSON.stringify(state), { mode: 384 });
123
+ fs.renameSync(tmp, this.stateFile);
124
+ }
125
+ }
126
+ function pipelineArgumentNames(files) {
127
+ const names = [];
128
+ for (const file of files) {
129
+ if (!fs.existsSync(file)) continue;
130
+ for (const match of fs.readFileSync(file, "utf8").matchAll(/pipeline_args\.([A-Za-z_][A-Za-z0-9_]*)/g))
131
+ if (!names.includes(match[1])) names.push(match[1]);
132
+ }
133
+ return names;
134
+ }
135
+ const SCHEDULE_NOTE = "Source you push runs at the next scheduled start. Verify it with run first, or pause the schedule for multi-step edits.";
136
+ function scheduleCheck(recorded, live, jobId) {
137
+ const restore = (cron) => `Restore it with farseer_configure_app schedule="${cron}" when done, or rerun init jobId=${jobId} force=true if the change was intended.`;
138
+ if (recorded && !live)
139
+ return {
140
+ status: "fail",
141
+ detail: `The job's schedule "${recorded}" was removed since init. ${restore(recorded)}`
142
+ };
143
+ if (recorded && live && recorded !== live)
144
+ return {
145
+ status: "fail",
146
+ detail: `The job's schedule changed from "${recorded}" to "${live}" since init. ${restore(recorded)}`
147
+ };
148
+ if (live) return { status: "pass", detail: `Job runs on schedule "${live}". ${SCHEDULE_NOTE}` };
149
+ return { status: "pass", detail: "Job has no schedule" };
150
+ }
151
+ function parseMarkers(lines) {
152
+ return lines.flatMap((line) => {
153
+ const pos = line.indexOf("PIPELINE_VISUALIZATION_MARKER");
154
+ if (pos < 0) return [];
155
+ try {
156
+ return [JSON.parse(line.slice(line.indexOf("{", pos)))];
157
+ } catch {
158
+ return [{ event: "unreadable_marker" }];
159
+ }
160
+ });
161
+ }
162
+ function loadOutcomes(markers) {
163
+ const loads = [];
164
+ for (const m of markers) {
165
+ if (m.event !== "import_observation") continue;
166
+ const name = String(m.name);
167
+ const importId = typeof m.import_id === "number" ? m.import_id : null;
168
+ const known = importId === null ? void 0 : loads.find((l) => l.name === name && l.importId === importId);
169
+ if (known) known.outcome = String(m.outcome);
170
+ else loads.push({ name, importId, outcome: String(m.outcome) });
171
+ }
172
+ return loads;
173
+ }
174
+ function skippedOutputs(markers) {
175
+ const types = /* @__PURE__ */ new Map();
176
+ for (const m of markers) if (m.event === "dataset_registered") types.set(String(m.name), m.type);
177
+ return markers.flatMap((m) => {
178
+ const type = types.get(String(m.name));
179
+ return m.event === "step_skipped" && (type === "load" || type === "export") ? [{ name: String(m.name), type, reason: String(m.reason ?? "") }] : [];
180
+ });
181
+ }
182
+ function skippedAttention(status, skipped) {
183
+ const count = (type) => skipped.filter((s) => s.type === type).length;
184
+ const phrase = (n, word) => n ? `${n} ${word}${n > 1 ? "s" : ""}` : "";
185
+ const parts = [phrase(count("load"), "load"), phrase(count("export"), "export")].filter(Boolean);
186
+ const verb = skipped.length > 1 ? "were" : "was";
187
+ const ended = status === "FINISHED" ? "Finished" : `Ended ${status}`;
188
+ return `${ended}, but ${parts.join(" and ")} ${verb} skipped: ${skipped.map((s) => `${s.name} (${s.reason})`).join(
189
+ ", "
190
+ )}. Nothing reached the model or Files through them. While building a pipeline, treat this as a defect to fix.`;
191
+ }
192
+ function sourcePath(profile, file) {
193
+ if (!relative.safeParse(file).success || !file.startsWith(profile.workspace + "/")) return false;
194
+ const inner = file.slice(profile.workspace.length + 1);
195
+ if (inner.split("/").some((p) => ["Data", "node_modules", "__pycache__"].includes(p))) return false;
196
+ return inner === profile.entrypoint || profile.configFiles.includes(inner) || /^(Models|Code)\//.test(inner) && /\.(py|ya?ml|json|md)$/.test(inner);
197
+ }
198
+ function localSourceFiles(profile, filesDir) {
199
+ const found = [];
200
+ const walk = (dir2, rel) => {
201
+ if (!fs.existsSync(dir2)) return;
202
+ if (fs.lstatSync(dir2).isSymbolicLink()) throw new Error(`Workspace symlinks are not supported: ${rel}`);
203
+ for (const entry of fs.readdirSync(dir2, { withFileTypes: true })) {
204
+ if (entry.name.startsWith(".") || ["Data", "node_modules", "__pycache__"].includes(entry.name)) continue;
205
+ const next = `${rel}/${entry.name}`;
206
+ if (entry.isSymbolicLink()) throw new Error(`Workspace symlinks are not supported: ${next}`);
207
+ if (entry.isDirectory()) walk(path.join(dir2, entry.name), next);
208
+ else if (sourcePath(profile, next)) found.push(next);
209
+ }
210
+ };
211
+ let dir = filesDir;
212
+ for (const part of profile.workspace.split("/")) {
213
+ dir = path.join(dir, part);
214
+ if (fs.existsSync(dir) && fs.lstatSync(dir).isSymbolicLink())
215
+ throw new Error("Workspace symlinks are not supported");
216
+ }
217
+ walk(dir, profile.workspace);
218
+ return found;
219
+ }
220
+ class PipelineService {
221
+ constructor(profile, client, filesDir, stateRoot, sync) {
222
+ this.client = client;
223
+ this.filesDir = filesDir;
224
+ this.client = (0, import_requests.boundedPipelineClient)(client);
225
+ this.profile = profileSchema.parse(profile);
226
+ const grammar = /^(\d+)\.(\d+)(?:\.\d+)?$/.exec(this.profile.engine)?.slice(1).map(Number);
227
+ const [major, minor] = import_reference.PIPELINE_ENGINE_PROFILE.split(".").map(Number);
228
+ if (grammar && (grammar[0] > major || grammar[0] === major && grammar[1] > minor))
229
+ throw new Error(
230
+ `This CLI's bundled grammar is ${import_reference.PIPELINE_ENGINE_PROFILE}; the profile was set up for ${this.profile.engine}. ${import_reference.CLI_UPDATE_INSTRUCTION}`
231
+ );
232
+ if (!grammar || grammar[0] < major)
233
+ throw new Error(
234
+ `The profile was set up for grammar ${this.profile.engine}, which this CLI (${import_reference.PIPELINE_ENGINE_PROFILE}) does not continue. Set the profile up again with init jobId=${this.profile.jobId} force=true${(0, import_agentSandbox.inAgentSandbox)() ? "" : `, or keep using the CLI release that targets ${this.profile.engine}`}.`
235
+ );
236
+ if (!profile.entrypoint.endsWith(".py"))
237
+ throw new import_errors.PipelineError(
238
+ "refused",
239
+ "PIPELINE_ENTRYPOINT_UNSUPPORTED",
240
+ "Pipeline entrypoint must be Python. The existing app must be preserved.",
241
+ "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."
242
+ );
243
+ this.stateDir = path.join(stateRoot, digest(`${profile.organisation}/${profile.tenant}/${profile.jobId}`));
244
+ this.operationDir = this.stateDir;
245
+ fs.mkdirSync(this.stateDir, { recursive: true, mode: 448 });
246
+ this.sync = sync ?? new WorkspaceSync(profile.tenant, this.client, path.join(this.stateDir, "sync.json"));
247
+ }
248
+ async versions(datasetId) {
249
+ import_zod.z.string().uuid().parse(datasetId);
250
+ const [dataset, versions] = await Promise.all([
251
+ this.client.pipelineRequest("GET", `/labs/datasets/${datasetId}`),
252
+ this.client.pipelineRequest("GET", `/labs/datasets/${datasetId}/versions`)
253
+ ]);
254
+ return { dataset, versions };
255
+ }
256
+ async check(signal) {
257
+ const checks = [];
258
+ const attempt = async (name, fn) => {
259
+ signal?.throwIfAborted();
260
+ try {
261
+ checks.push({ name, status: "pass", detail: await fn() });
262
+ } catch (error) {
263
+ signal?.throwIfAborted();
264
+ checks.push({ name, status: "fail", detail: redact(String(error)) });
265
+ }
266
+ };
267
+ await attempt("prepared-job", async () => {
268
+ await this.verifyJob();
269
+ return "Job, entrypoint and source folder match";
270
+ });
271
+ let job = null;
272
+ try {
273
+ signal?.throwIfAborted();
274
+ job = await this.client.getApp(String(this.profile.jobId));
275
+ if (job)
276
+ checks.push({
277
+ name: "schedule",
278
+ ...scheduleCheck(this.profile.schedule, job.schedule, this.profile.jobId)
279
+ });
280
+ const runtime = (0, import_runtime.compareRuntime)(job?.runnerImage ?? "");
281
+ checks.push({
282
+ name: "runner-image",
283
+ status: runtime.status === "match" ? "pass" : runtime.status === "behind" || runtime.status === "incompatible" ? "fail" : "pending",
284
+ detail: runtime.status === "match" ? `Job runs ${import_runtime.PIPELINE_RUNNER_IMAGE}, the image this CLI authors for` : runtime.nextAction
285
+ });
286
+ } catch (error) {
287
+ signal?.throwIfAborted();
288
+ checks.push({ name: "runner-image", status: "fail", detail: redact(String(error)) });
289
+ }
290
+ if (job) {
291
+ const used = pipelineArgumentNames(this.localSources().map((f) => path.join(this.filesDir, f)));
292
+ const defined = new Set((job.expectedArguments ?? []).map((a) => a.name));
293
+ const unset = used.filter((name) => !defined.has(name));
294
+ const entry = path.join(this.filesDir, this.profile.workspace, this.profile.entrypoint);
295
+ const setByMain = setArgumentNames(fs.existsSync(entry) ? fs.readFileSync(entry, "utf8") : "");
296
+ const missing = unset.filter((name) => !setByMain.has(name));
297
+ const derived = unset.filter((name) => setByMain.has(name));
298
+ checks.push(
299
+ missing.length ? {
300
+ name: "job-arguments",
301
+ status: "fail",
302
+ 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.`
303
+ } : derived.length ? {
304
+ name: "job-arguments",
305
+ status: "pending",
306
+ 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.`
307
+ } : {
308
+ name: "job-arguments",
309
+ status: "pass",
310
+ detail: used.length ? `Job defines every argument the source uses (${used.join(", ")})` : "Source uses no job arguments"
311
+ }
312
+ );
313
+ }
314
+ const models = this.localSources().filter((f) => /\/Models\/.+\.ya?ml$/.test(f));
315
+ if (!this.profile.datasetIds.length)
316
+ checks.push({
317
+ name: "declared-outputs",
318
+ status: "pending",
319
+ detail: models.length ? `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.` : "No dataset YAML under Models/ yet. Write the first one there: the guide topics FarseerFilesExtractConfig, TransformConfig and LoadCellsConfig each end with a complete example."
320
+ });
321
+ else
322
+ await attempt("declared-outputs", async () => {
323
+ return `${this.profile.datasetIds.length} prepared output(s); this is configuration, not an ownership lock`;
324
+ });
325
+ let latestCli;
326
+ try {
327
+ signal?.throwIfAborted();
328
+ ({ latestCliVersion: latestCli } = await this.client.pipelineRequest(
329
+ "GET",
330
+ "/pipelineAuthoring"
331
+ ));
332
+ } catch (error) {
333
+ signal?.throwIfAborted();
334
+ checks.push({ name: "cli-version", status: "fail", detail: redact(String(error)) });
335
+ }
336
+ if (latestCli !== void 0)
337
+ checks.push(
338
+ (0, import_runtime.compareVersions)(import_constants.CLI_VERSION, latestCli) < 0 ? {
339
+ name: "cli-version",
340
+ status: "pending",
341
+ detail: `CLI ${import_constants.CLI_VERSION} is installed; ${latestCli} is the CLI released with this tenant's current runner image. ${import_reference.CLI_UPDATE_INSTRUCTION}`
342
+ } : { name: "cli-version", status: "pass", detail: `CLI ${import_constants.CLI_VERSION} is current` }
343
+ );
344
+ for (const datasetId of this.profile.datasetIds) {
345
+ await attempt(`dataset:${datasetId}`, async () => {
346
+ const dataset = await this.client.pipelineRequest(
347
+ "GET",
348
+ `/labs/datasets/${datasetId}`
349
+ );
350
+ if (dataset.id !== datasetId) throw new Error("Dataset identity did not match");
351
+ if (!dataset.currentVersionId) {
352
+ checks.push({
353
+ name: `signed-read:${datasetId}`,
354
+ status: "pending",
355
+ detail: "No published version yet. Complete the prepared first run, then check again."
356
+ });
357
+ return "Prepared dataset exists; it has no current version";
358
+ }
359
+ const manifest = await this.client.pipelineRequest("GET", `/labs/datasets/${datasetId}/versions/${dataset.currentVersionId}/downloadUrls`);
360
+ if (!manifest.files?.length || manifest.files.length > 512 || manifest.files.some(
361
+ (f) => !f.filename.endsWith(".parquet") || !Number.isSafeInteger(f.size) || f.size < 0
362
+ ))
363
+ throw new Error("A complete supported Parquet manifest is required");
364
+ const bytes = manifest.files.reduce((sum, f) => sum + f.size, 0);
365
+ if (bytes > import_query.DEFAULT_LIMITS.inputBytes)
366
+ throw new Error(
367
+ "This version exceeds the 256 MiB query download limit; prepare a smaller pipeline output"
368
+ );
369
+ const versionId = dataset.currentVersionId;
370
+ const first = manifest.files[0];
371
+ if (this.client.agentSession)
372
+ await (0, import_readiness.probeParquetPrefix)(
373
+ (probeSignal) => this.client.downloadDatasetVersionFile(datasetId, versionId, first.filename, probeSignal)
374
+ );
375
+ else await (0, import_readiness.probeParquetAccess)(first.signedUrl);
376
+ const access = this.client.agentSession ? "Read through the API" : "Signed GET";
377
+ 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.`;
378
+ });
379
+ }
380
+ const automatedReady = checks.every((c) => c.status === "pass");
381
+ const setup = readSetup(this.profile.setup);
382
+ checks.push(
383
+ "recorded" in setup ? {
384
+ name: "setup-evidence",
385
+ status: "pass",
386
+ 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.`
387
+ } : {
388
+ name: "setup-evidence",
389
+ status: "pending",
390
+ 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.`
391
+ }
392
+ );
393
+ return {
394
+ tenant: this.profile.tenant,
395
+ jobId: this.profile.jobId,
396
+ automatedReady,
397
+ readyForAcceptance: checks.every((c) => c.status === "pass"),
398
+ checks,
399
+ limits: import_query.DEFAULT_LIMITS,
400
+ remainingAcceptance: "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."
401
+ };
402
+ }
403
+ async queryVersions(bindings, sql, signal) {
404
+ import_zod.z.array(
405
+ import_zod.z.object({
406
+ name: import_zod.z.string().regex(/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/),
407
+ datasetId: import_zod.z.string().uuid(),
408
+ versionId: import_zod.z.string().uuid()
409
+ }).strict()
410
+ ).min(1).max(16).parse(bindings);
411
+ if (new Set(bindings.map((b) => b.name.toLowerCase())).size !== bindings.length)
412
+ throw new Error("SQL binding names must be distinct");
413
+ const inputs = [];
414
+ for (const b of bindings) {
415
+ const result2 = await this.client.pipelineRequest("GET", `/labs/datasets/${b.datasetId}/versions/${b.versionId}/downloadUrls`);
416
+ if (!result2.files?.length || result2.files.some((f) => !f.filename.endsWith(".parquet")))
417
+ throw new Error("This version has no supported Parquet contents");
418
+ inputs.push({ ...b, files: result2.files });
419
+ }
420
+ const total = inputs.reduce((sum, b) => sum + b.files.reduce((n, f) => n + f.size, 0), 0);
421
+ if (total > import_query.DEFAULT_LIMITS.inputBytes) throw new Error("Input download byte limit exceeded");
422
+ const result = await (0, import_query.queryFiles)(
423
+ {
424
+ bindings: inputs.map((b) => ({ name: b.name, urls: b.files.map((f) => f.signedUrl) })),
425
+ sql,
426
+ limits: import_query.DEFAULT_LIMITS
427
+ },
428
+ signal,
429
+ this.client.agentSession ? (binding, file, downloadSignal) => {
430
+ const input = inputs[binding];
431
+ return this.client.downloadDatasetVersionFile(
432
+ input.datasetId,
433
+ input.versionId,
434
+ input.files[file].filename,
435
+ downloadSignal
436
+ );
437
+ } : void 0
438
+ );
439
+ return {
440
+ ...result,
441
+ tenant: this.profile.tenant,
442
+ semantics: "explicit immutable dataset versions",
443
+ inputs: inputs.map(({ files, ...binding }) => ({
444
+ ...binding,
445
+ files: files.map(({ signedUrl: _url, ...file }) => file)
446
+ }))
447
+ };
448
+ }
449
+ async restore(datasetId, versionId, expectedCurrentVersionId) {
450
+ [datasetId, versionId, expectedCurrentVersionId].forEach((id) => import_zod.z.string().uuid().parse(id));
451
+ if (!this.profile.datasetIds.includes(datasetId))
452
+ throw new import_errors.PipelineError(
453
+ "refused",
454
+ "RESTORE_SCOPE",
455
+ "Restore only a declared output dataset",
456
+ "Use an output dataset from the prepared profile."
457
+ );
458
+ return this.exclusive(async () => {
459
+ await this.idle();
460
+ let dataset;
461
+ try {
462
+ dataset = await this.client.pipelineRequest(
463
+ "POST",
464
+ `/labs/datasets/${datasetId}/versions/${versionId}/restore`,
465
+ { expectedCurrentVersionId }
466
+ );
467
+ } catch (error) {
468
+ const refused = [400, 401, 403, 404, 409].includes((0, import_errors.httpStatus)(error) ?? 0);
469
+ throw new import_errors.PipelineError(
470
+ refused ? "refused" : "unknown",
471
+ refused ? "RESTORE_REFUSED" : "RESTORE_UNCONFIRMED",
472
+ redact(String(error)),
473
+ "Read versions and current dataset state before any further restore. Do not blindly retry."
474
+ );
475
+ }
476
+ return {
477
+ dataset,
478
+ note: "A state-changing restore also cancels outstanding unpublished candidates and restores the matching reading position. Inspect model imports separately."
479
+ };
480
+ });
481
+ }
482
+ receipt() {
483
+ const name = path.join(this.stateDir, "current.json");
484
+ return fs.existsSync(name) ? JSON.parse(fs.readFileSync(name, "utf8")) : void 0;
485
+ }
486
+ save(receipt) {
487
+ const tmp = path.join(this.stateDir, (0, import_crypto.randomUUID)());
488
+ fs.writeFileSync(tmp, JSON.stringify(receipt, null, 2), { mode: 384 });
489
+ fs.renameSync(tmp, path.join(this.stateDir, "current.json"));
490
+ if (receipt.runUuid)
491
+ fs.writeFileSync(path.join(this.stateDir, `${receipt.runUuid}.json`), JSON.stringify(receipt), {
492
+ mode: 384
493
+ });
494
+ }
495
+ async exclusive(fn) {
496
+ const name = path.join(this.operationDir, "operation.lock");
497
+ let fd;
498
+ try {
499
+ fd = fs.openSync(name, "wx", 384);
500
+ } catch (error) {
501
+ if (error.code !== "EEXIST") throw error;
502
+ throw new import_errors.PipelineError(
503
+ "refused",
504
+ "PIPELINE_LOCAL_BUSY",
505
+ "Workspace operation in progress. An abandoned lock requires local recovery; do not resubmit.",
506
+ "Inspect the existing local command; use CLI recovery only after its process has stopped."
507
+ );
508
+ }
509
+ fs.writeFileSync(fd, String(process.pid));
510
+ fs.closeSync(fd);
511
+ try {
512
+ return await fn();
513
+ } finally {
514
+ fs.unlinkSync(name);
515
+ }
516
+ }
517
+ /**
518
+ * Ends a queued run of this job: one a runner never started, which would otherwise stay queued
519
+ * in the job's history. A running run is refused: stopping work part-way is a person's call, made
520
+ * with Stop in the web app. The result reads the run back, so it says whether the run closed.
521
+ */
522
+ async terminate(uuid) {
523
+ import_zod.z.string().uuid().parse(uuid);
524
+ const run = await this.findRun(uuid);
525
+ if (!run)
526
+ throw new import_errors.PipelineError(
527
+ "refused",
528
+ "RUN_NOT_FOUND",
529
+ `Run ${uuid} is not a run of job ${this.profile.jobId}.`,
530
+ "Take the run UUID from runs or from the refusal that named it."
531
+ );
532
+ if (run.status === "RUNNING")
533
+ throw new import_errors.PipelineError(
534
+ "refused",
535
+ "RUN_NOT_QUEUED",
536
+ `Run ${uuid} is running. Stopping a run part-way is a person's call. Nothing was sent.`,
537
+ "Ask a person to stop it with Stop in the web app, then wait for it to end. Do not retry terminate.",
538
+ uuid
539
+ );
540
+ if (run.status !== "QUEUED")
541
+ throw new import_errors.PipelineError(
542
+ "refused",
543
+ "RUN_NOT_QUEUED",
544
+ `Run ${uuid} has already ended (${run.status}).`,
545
+ "Nothing to terminate; inspect it if you need its outcome.",
546
+ uuid
547
+ );
548
+ try {
549
+ await this.client.pipelineRequest("POST", `/remoteJobs/${this.profile.jobId}/cancelQueued/${uuid}`);
550
+ } catch (error) {
551
+ if ((0, import_errors.httpStatus)(error) === 409)
552
+ throw new import_errors.PipelineError(
553
+ "refused",
554
+ "RUN_NOT_QUEUED",
555
+ `Run ${uuid} started before cancellation. It was not stopped.`,
556
+ "Ask a person to stop it with Stop in the web app. Do not retry terminate.",
557
+ uuid
558
+ );
559
+ if ((0, import_errors.httpStatus)(error) === 404 || (0, import_errors.httpStatus)(error) === 405)
560
+ throw new import_errors.PipelineError(
561
+ "refused",
562
+ "QUEUED_CANCELLATION_UNAVAILABLE",
563
+ "Queued-only cancellation is unavailable, or the job or run no longer exists.",
564
+ "Inspect the run and check that the backend supports queued-only cancellation. Do not fall back to the general Stop endpoint.",
565
+ uuid
566
+ );
567
+ throw error;
568
+ }
569
+ const status = (await this.findRun(uuid))?.status ?? "unknown";
570
+ if (status !== "QUEUED")
571
+ return { runUuid: uuid, status, terminated: status === "ERROR" || status === "FINISHED" };
572
+ return {
573
+ runUuid: uuid,
574
+ status,
575
+ terminated: false,
576
+ 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."
577
+ };
578
+ }
579
+ async findRun(uuid) {
580
+ if (!/^[a-f0-9-]{36}$/i.test(uuid)) throw new Error("Invalid run UUID");
581
+ return (await this.history()).find((r) => r.uuid === uuid);
582
+ }
583
+ async history() {
584
+ const runs = await this.client.pipelineRequest("GET", `/remoteJobs/${this.profile.jobId}/remoteJobRuns`);
585
+ return runs.filter((r) => r.remoteJobId === this.profile.jobId);
586
+ }
587
+ async idle(requireRun = false) {
588
+ const receipt = this.receipt();
589
+ if (!receipt) {
590
+ if (requireRun) throw new Error("Run this workspace before querying outputs");
591
+ return;
592
+ }
593
+ if (!receipt.runUuid)
594
+ throw new import_errors.PipelineError(
595
+ "unknown",
596
+ "SUBMISSION_UNCONFIRMED",
597
+ `Submission outcome unknown; no automatic retry. ${RECOVER_HINT}`,
598
+ "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."
599
+ );
600
+ const run = await this.findRun(receipt.runUuid);
601
+ if (!run || !terminal(run.status))
602
+ throw new import_errors.PipelineError(
603
+ run ? "refused" : "unknown",
604
+ run ? "RUN_ACTIVE" : "RUN_UNCONFIRMED",
605
+ `Workspace run ${receipt.runUuid} is ${run?.status ?? "unconfirmed"}`,
606
+ "Inspect this run by UUID before any further changes or submission.",
607
+ receipt.runUuid
608
+ );
609
+ }
610
+ async verifyJob() {
611
+ const p = this.profile;
612
+ const job = await this.client.getApp(String(p.jobId));
613
+ if (job) (0, import_runtime.assertPipelineRuntime)(job.runnerImage ?? "");
614
+ const folder = await this.client.resolveSourceFolder(p.workspace);
615
+ if (!job || !folder || job.sourceFolderId !== p.sourceFolderId || folder.id !== p.sourceFolderId || !folder.scripts.some((s) => s.id === job.mainScriptFileId && s.name === p.entrypoint)) {
616
+ throw new import_errors.PipelineError(
617
+ "refused",
618
+ "SETUP_CHANGED",
619
+ "Prepared job, entrypoint or workspace changed. Repair pipeline setup before continuing.",
620
+ "Ask the setup owner to reconcile the prepared job and profile before continuing."
621
+ );
622
+ }
623
+ return job;
624
+ }
625
+ /** Workspace source files in the pull/push scope, as tenant-relative paths. */
626
+ localSources() {
627
+ return localSourceFiles(this.profile, this.filesDir);
628
+ }
629
+ /** The job's run history, newest first, with whether a local receipt names each run. */
630
+ async runs(limit = 20) {
631
+ import_zod.z.number().int().positive().parse(limit);
632
+ const history = await this.client.pipelineRequest(
633
+ "GET",
634
+ `/remoteJobs/${this.profile.jobId}/remoteJobRuns`
635
+ );
636
+ const runs = history.filter((r) => r.remoteJobId === this.profile.jobId).sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt) || b.id - a.id).slice(0, limit).map((r) => ({
637
+ uuid: r.uuid,
638
+ status: r.status,
639
+ startedAt: r.startedAt,
640
+ ...r.finishedAt ? { finishedAt: r.finishedAt } : {},
641
+ receipt: fs.existsSync(path.join(this.stateDir, `${r.uuid}.json`))
642
+ }));
643
+ return { tenant: this.profile.tenant, jobId: this.profile.jobId, runs };
644
+ }
645
+ async sources() {
646
+ const local = this.localSources();
647
+ const remote = (await this.client.listFiles(["Files", ...this.profile.workspace.split("/")])).filter(
648
+ (f) => sourcePath(this.profile, f.path)
649
+ );
650
+ const onlyFiles = [
651
+ .../* @__PURE__ */ new Set([
652
+ ...local,
653
+ ...remote.map((f) => f.path),
654
+ ...Object.keys(this.sync.loadSyncState().files).filter((f) => sourcePath(this.profile, f))
655
+ ])
656
+ ];
657
+ if (!onlyFiles.length) throw new Error("Empty source scope; refusing tenant-wide fallback");
658
+ return { local, remote, onlyFiles };
659
+ }
660
+ async syncSources(direction) {
661
+ return this.exclusive(async () => {
662
+ await this.idle();
663
+ const job = await this.verifyJob();
664
+ const runtime = (0, import_runtime.compareRuntime)(job.runnerImage ?? "");
665
+ if (direction === "push" && runtime.status === "behind")
666
+ throw new import_errors.PipelineError(
667
+ "refused",
668
+ "RUNTIME_UPGRADE_REQUIRED",
669
+ `The job runs ${job.runnerImage}, older than ${import_runtime.PIPELINE_RUNNER_IMAGE} this CLI authors for. Nothing was pushed.`,
670
+ runtime.nextAction
671
+ );
672
+ const { onlyFiles } = await this.sources();
673
+ let result;
674
+ try {
675
+ result = await (direction === "pull" ? this.sync.pull({ onlyFiles }) : this.sync.push({ onlyFiles }));
676
+ } catch (error) {
677
+ throw new import_errors.PipelineError(
678
+ "unknown",
679
+ "SYNC_INCOMPLETE",
680
+ redact(String(error)),
681
+ "Some files may already have changed. Pull and reconcile source differences before running."
682
+ );
683
+ }
684
+ return direction === "push" && job.schedule ? { ...result, schedule: { cron: job.schedule, note: SCHEDULE_NOTE } } : result;
685
+ });
686
+ }
687
+ /**
688
+ * Move the job to the image this CLI authors for. Only a job behind it moves: a job on a
689
+ * moving tag or digest may already run a newer engine, and a job ahead needs a newer CLI.
690
+ */
691
+ async upgradeRuntime() {
692
+ return this.exclusive(async () => {
693
+ await this.idle();
694
+ const job = await this.verifyJob();
695
+ const from = job.runnerImage ?? "";
696
+ const runtime = (0, import_runtime.compareRuntime)(from);
697
+ if (runtime.status === "match") return { jobId: job.id, from, to: from, changed: false };
698
+ if (runtime.status === "ahead")
699
+ throw new import_errors.PipelineError(
700
+ "refused",
701
+ "CLI_UPDATE_REQUIRED",
702
+ `The job runs ${from}, newer than ${import_runtime.PIPELINE_RUNNER_IMAGE} this CLI authors for.`,
703
+ import_reference.CLI_UPDATE_INSTRUCTION
704
+ );
705
+ if (runtime.status !== "behind")
706
+ throw new import_errors.PipelineError(
707
+ "refused",
708
+ "RUNTIME_UNVERSIONED",
709
+ `The job runs ${from}, a moving tag or digest, so this CLI cannot tell whether ${import_runtime.PIPELINE_RUNNER_IMAGE} is older or newer.`,
710
+ "Leave the job on its image, or pin an exact image deliberately in the web app."
711
+ );
712
+ const image = (0, import_apps.resolveRunnerImage)(import_runtime.PIPELINE_RUNNER_IMAGE, await this.client.getRunnerImageRepositories());
713
+ if ("error" in image) throw new Error(image.error);
714
+ try {
715
+ await this.client.updateApp(String(job.id), { runnerImage: image.image }, job);
716
+ } catch (error) {
717
+ const status = (0, import_errors.httpStatus)(error) ?? 0;
718
+ if (status >= 400 && status < 500)
719
+ throw new import_errors.PipelineError(
720
+ "refused",
721
+ "RUNTIME_UPGRADE_REFUSED",
722
+ `The backend refused the image change; the job stays on ${from}. ${redact(String(error))}`,
723
+ "Read the reason, fix the setup it names or ask the setup owner, then try again."
724
+ );
725
+ throw new import_errors.PipelineError(
726
+ "unknown",
727
+ "RUNTIME_UPGRADE_UNCONFIRMED",
728
+ `The image change may have been saved: the job is on ${from} or ${image.image}. ${redact(String(error))}`,
729
+ "Run check to read the job's image before anything else. Do not retry blindly."
730
+ );
731
+ }
732
+ const moved = { jobId: job.id, from, to: image.image, changed: true };
733
+ return job.schedule ? {
734
+ ...moved,
735
+ schedule: {
736
+ cron: job.schedule,
737
+ 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."
738
+ }
739
+ } : moved;
740
+ });
741
+ }
742
+ async submit(args = []) {
743
+ import_zod.z.array(import_zod.z.string()).parse(args);
744
+ return this.exclusive(async () => {
745
+ await this.idle();
746
+ const active = (await this.history()).find((r) => !terminal(r.status));
747
+ if (active)
748
+ throw new import_errors.PipelineError(
749
+ "refused",
750
+ "RUN_ACTIVE",
751
+ `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.`,
752
+ "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.",
753
+ active.uuid
754
+ );
755
+ const job = await this.verifyJob();
756
+ const runArguments = (0, import_runArguments.resolveRunArguments)(job.expectedArguments ?? [], args);
757
+ const { local, remote } = await this.sources();
758
+ const differences = [];
759
+ for (const file of /* @__PURE__ */ new Set([...local, ...remote.map((f) => f.path)])) {
760
+ const reference = remote.find((r) => r.path === file);
761
+ if (!local.includes(file) || !reference || digest(fs.readFileSync(path.join(this.filesDir, file))) !== digest(await this.client.getFileContentAsBuffer(reference.reference)))
762
+ differences.push(file);
763
+ }
764
+ if (!local.includes(`${this.profile.workspace}/${this.profile.entrypoint}`))
765
+ differences.push(this.profile.entrypoint);
766
+ if (differences.length)
767
+ throw new import_errors.PipelineError(
768
+ "refused",
769
+ "UNSYNCED_SOURCES",
770
+ `Unsynced source files: ${differences.join(", ")}`,
771
+ "Pull and reconcile the listed source files, then push the intended changes before running."
772
+ );
773
+ const { organisation, tenant, jobId, workspace, author } = this.profile;
774
+ const receipt = {
775
+ organisation,
776
+ tenant,
777
+ jobId,
778
+ workspace,
779
+ author,
780
+ submittedAt: (/* @__PURE__ */ new Date()).toISOString(),
781
+ phase: "unconfirmed"
782
+ };
783
+ const previousReceipt = this.receipt();
784
+ this.save(receipt);
785
+ let result;
786
+ try {
787
+ result = await this.client.pipelineRequest("POST", `/remoteJobs/${jobId}/run`, {
788
+ arguments: runArguments.positional
789
+ });
790
+ } catch (error) {
791
+ const status = (0, import_errors.httpStatus)(error);
792
+ if (status >= 400 && status < 500) {
793
+ if (previousReceipt) this.save(previousReceipt);
794
+ else fs.rmSync(path.join(this.stateDir, "current.json"), { force: true });
795
+ const reason = error.response?.data?.message ?? String(error);
796
+ throw new import_errors.PipelineError(
797
+ "refused",
798
+ "REQUEST_REFUSED",
799
+ `Submission refused by the backend (HTTP ${status}). No new run was accepted. ${redact(String(reason))}`,
800
+ "Read the reason, fix the setup it names or ask the setup owner, then run again."
801
+ );
802
+ }
803
+ throw new import_errors.PipelineError(
804
+ "unknown",
805
+ "SUBMISSION_UNCONFIRMED",
806
+ `Submission outcome unconfirmed; the receipt was saved. ${RECOVER_HINT} ${redact(String(error))}`,
807
+ "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."
808
+ );
809
+ }
810
+ if (!result?.runUuid || !/^[a-f0-9-]{36}$/i.test(result.runUuid))
811
+ throw new import_errors.PipelineError(
812
+ "unknown",
813
+ "SUBMISSION_UNCONFIRMED",
814
+ "Backend did not return a run UUID; submission remains unconfirmed",
815
+ "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."
816
+ );
817
+ try {
818
+ this.save({ ...receipt, runUuid: result.runUuid, phase: "accepted" });
819
+ } catch (error) {
820
+ throw new import_errors.PipelineError(
821
+ "unknown",
822
+ "RECEIPT_SAVE_FAILED",
823
+ `Run accepted but its local receipt could not be updated. ${redact(String(error))}`,
824
+ "Save this runUuid and inspect it. Do not resubmit.",
825
+ result.runUuid
826
+ );
827
+ }
828
+ return {
829
+ ...receipt,
830
+ ...result,
831
+ phase: "accepted",
832
+ observation: "pending",
833
+ arguments: runArguments.given
834
+ };
835
+ });
836
+ }
837
+ async inspect(uuid = this.receipt()?.runUuid, offset = 0) {
838
+ import_zod.z.number().int().nonnegative().parse(offset);
839
+ const receipt = this.receipt();
840
+ if (!uuid && !receipt)
841
+ throw new import_errors.PipelineError(
842
+ "refused",
843
+ "NO_RUN_RECORDED",
844
+ "No run has been submitted from this profile, so there is no run to inspect.",
845
+ "Pass a uuid from runs to inspect an earlier run, or run the pipeline."
846
+ );
847
+ if (!uuid) return { status: "unconfirmed", receipt };
848
+ const run = await this.findRun(uuid);
849
+ if (!run) return { runUuid: uuid, status: "unconfirmed", receipt: this.receipt() };
850
+ const logs = run.logs ?? [];
851
+ const page = [];
852
+ let bytes = 0;
853
+ let next = Math.max(0, offset);
854
+ for (; next < logs.length && page.length < 100; next++) {
855
+ const line = redact(logs[next]).slice(0, 4e3);
856
+ if (bytes + Buffer.byteLength(line) > 32e3) break;
857
+ page.push(line);
858
+ bytes += Buffer.byteLength(line);
859
+ }
860
+ const observations = parseMarkers(logs.map((line) => redact(line).slice(0, 4e3)));
861
+ const skipped = skippedOutputs(observations);
862
+ return {
863
+ tenant: this.profile.tenant,
864
+ workspace: this.profile.workspace,
865
+ jobId: this.profile.jobId,
866
+ runUuid: uuid,
867
+ status: run.status,
868
+ logs: page,
869
+ observations,
870
+ engine: (0, import_reference.engineReport)(observations),
871
+ loads: loadOutcomes(observations),
872
+ skippedOutputs: skipped,
873
+ ...skipped.length ? { attention: skippedAttention(run.status, skipped) } : {},
874
+ // Until the run ends more lines can come, so null means the run ended and nothing is left.
875
+ nextOffset: next < logs.length || !terminal(run.status) ? next : null,
876
+ // From what this run reported, not the profile: before init records dataset IDs, a run
877
+ // that writes datasets still reports their versions and never an output_written marker.
878
+ outputSemantics: observations.some((o) => String(o.event).startsWith("dataset_")) ? "version identifiers are reported in dataset observations" : observations.some((o) => o.event === "output_written") ? "current files; writes require an observed output_written marker" : "no output markers observed yet"
879
+ };
880
+ }
881
+ async query(bindings, sql, signal) {
882
+ import_zod.z.array(import_zod.z.object({ name: import_zod.z.string().regex(/^[a-zA-Z_][a-zA-Z0-9_]{0,62}$/), file: relative }).strict()).min(1).max(16).parse(bindings);
883
+ if (new Set(bindings.map((b) => b.name.toLowerCase())).size !== bindings.length)
884
+ throw new Error("SQL binding names must be distinct");
885
+ return this.exclusive(async () => {
886
+ await this.idle(true);
887
+ const inputs = [];
888
+ for (const binding of bindings) {
889
+ relative.parse(binding.file);
890
+ if (!binding.file.startsWith("Data/") || !binding.file.endsWith(".parquet"))
891
+ throw new Error("Query inputs must be Parquet files under this workspace\u2019s Data/");
892
+ const file = await this.client.getFileByPath(`${this.profile.workspace}/${binding.file}`);
893
+ if (!file || file.path !== `${this.profile.workspace}/${binding.file}`)
894
+ throw new Error("Workspace output not found");
895
+ let url = `farseer-file:${file.reference}`;
896
+ if (!this.client.agentSession) {
897
+ const access = await this.client.pipelineRequest(
898
+ "GET",
899
+ `/farseerFiles/${encodeURIComponent(file.reference)}/downloadUrl`
900
+ );
901
+ if (!access?.url?.startsWith("https://")) throw new Error("Signed object read access unavailable");
902
+ url = access.url;
903
+ }
904
+ inputs.push({
905
+ ...file,
906
+ metadata: await this.client.getFileMetadata(file.reference) ?? void 0,
907
+ name: binding.name,
908
+ url
909
+ });
910
+ }
911
+ const total = inputs.reduce((sum, input) => sum + (input.metadata?.size ?? 0), 0);
912
+ if (total > import_query.DEFAULT_LIMITS.inputBytes) throw new Error("Input download byte limit exceeded");
913
+ const result = await (0, import_query.queryFiles)(
914
+ { bindings: inputs, sql, limits: import_query.DEFAULT_LIMITS },
915
+ signal,
916
+ this.client.agentSession ? (binding, _file, downloadSignal) => this.client.downloadFarseerFile(inputs[binding].reference, downloadSignal) : void 0
917
+ );
918
+ return {
919
+ ...result,
920
+ tenant: this.profile.tenant,
921
+ workspace: this.profile.workspace,
922
+ queryTime: (/* @__PURE__ */ new Date()).toISOString(),
923
+ semantics: "current-file read; not a historical run snapshot",
924
+ inputs: inputs.map(({ url: _url, ...file }) => file)
925
+ };
926
+ });
927
+ }
928
+ async inspectImport(importId) {
929
+ import_zod.z.number().int().positive().parse(importId);
930
+ const job = await this.client.pipelineRequest("GET", `/importJobs/${importId}`).catch((error) => {
931
+ if ((0, import_errors.httpStatus)(error) !== 404) throw error;
932
+ throw new import_errors.PipelineError(
933
+ "refused",
934
+ "IMPORT_NOT_FOUND",
935
+ `Import ${importId} does not exist on ${this.profile.tenant}.`,
936
+ "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."
937
+ );
938
+ });
939
+ return {
940
+ tenant: this.profile.tenant,
941
+ importId: job.id,
942
+ title: redact(job.title).slice(0, 500),
943
+ status: job.status,
944
+ createdAt: job.createdAt,
945
+ commitConfirmed: job.status === "COMMITED",
946
+ note: "An uncommitted status does not rule out an in-flight commit. Inspect before retrying; no automatic retry."
947
+ };
948
+ }
949
+ /**
950
+ * Direct CLI recovery only, after the author resolves submission uncertainty in history. With a
951
+ * uuid, attach that run. Without one, clear a receipt whose submission history shows was never
952
+ * accepted: the backend records an admitted run before dispatching it, so no run of this job since
953
+ * the submission means none was accepted. Any run in that window is listed, never guessed at.
954
+ */
955
+ async recover(uuid) {
956
+ return this.exclusive(async () => {
957
+ const receipt = this.receipt();
958
+ if (!receipt) throw new Error("No submission receipt to recover");
959
+ if (uuid !== void 0) {
960
+ const run = await this.findRun(uuid);
961
+ if (!run) throw new Error("Cannot attach an unobserved run");
962
+ this.save({ ...receipt, runUuid: uuid, phase: "accepted" });
963
+ return this.inspect(uuid);
964
+ }
965
+ if (receipt.runUuid)
966
+ throw new Error(`The receipt already names run ${receipt.runUuid}; inspect it instead`);
967
+ const since = Date.parse(receipt.submittedAt) - CLOCK_SKEW_MARGIN_MS;
968
+ const candidates = (await this.history()).filter((r) => Date.parse(r.startedAt) >= since);
969
+ if (candidates.length)
970
+ throw new Error(
971
+ `Run history has ${candidates.length} run(s) of this job since the submission at ${receipt.submittedAt}: ` + candidates.map((r) => `${r.uuid} (${r.status}, started ${r.startedAt})`).join("; ") + ". If one is this submission, attach it with recover --uuid <uuid>. Nothing was cleared."
972
+ );
973
+ fs.rmSync(path.join(this.stateDir, "current.json"), { force: true });
974
+ return {
975
+ cleared: true,
976
+ submittedAt: receipt.submittedAt,
977
+ 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."
978
+ };
979
+ });
980
+ }
981
+ /** A local operator resolves a crashed command. Never clears its submission receipt. */
982
+ unlockAbandonedOperation() {
983
+ const name = path.join(this.operationDir, "operation.lock");
984
+ if (!fs.existsSync(name)) return { unlocked: false };
985
+ const pid = Number(fs.readFileSync(name, "utf8"));
986
+ if (!Number.isSafeInteger(pid) || pid <= 0) throw new Error("Unrecognized lock; inspect it manually");
987
+ try {
988
+ process.kill(pid, 0);
989
+ } catch (error) {
990
+ if (error.code === "ESRCH") {
991
+ fs.unlinkSync(name);
992
+ return { unlocked: true, receiptRetained: true };
993
+ }
994
+ throw error;
995
+ }
996
+ throw new Error("The workspace command is still running");
997
+ }
998
+ }
999
+ function redact(s) {
1000
+ return s.replace(/https?:\/\/[^\s'"<>]+/g, "[URL redacted]");
1001
+ }
1002
+ function setArgumentNames(source) {
1003
+ const names = /* @__PURE__ */ new Set();
1004
+ for (const pattern of [
1005
+ /\[\s*["']([A-Za-z_][A-Za-z0-9_]*)["']\s*\]\s*=(?!=)/g,
1006
+ /\.setdefault\(\s*["']([A-Za-z_][A-Za-z0-9_]*)["']/g,
1007
+ /["']([A-Za-z_][A-Za-z0-9_]*)["']\s*:/g
1008
+ ])
1009
+ for (const match of source.matchAll(pattern)) names.add(match[1]);
1010
+ return names;
1011
+ }
1012
+ // Annotate the CommonJS export names for ESM import in node:
1013
+ 0 && (module.exports = {
1014
+ BLANK_SETUP,
1015
+ PipelineService,
1016
+ SCHEDULE_NOTE,
1017
+ loadOutcomes,
1018
+ localSourceFiles,
1019
+ pipelineArgumentNames,
1020
+ profileSchema,
1021
+ readPipelineProfileFile,
1022
+ redact,
1023
+ scheduleCheck,
1024
+ skippedOutputs,
1025
+ sourcePath
1026
+ });
1027
+ //# sourceMappingURL=service.js.map