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
|
@@ -34,6 +34,7 @@ __export(workflow_exports, {
|
|
|
34
34
|
planModel: () => planModel,
|
|
35
35
|
pruneDrafts: () => pruneDrafts,
|
|
36
36
|
pullModel: () => pullModel,
|
|
37
|
+
useWaitPause: () => useWaitPause,
|
|
37
38
|
waitSeconds: () => waitSeconds
|
|
38
39
|
});
|
|
39
40
|
module.exports = __toCommonJS(workflow_exports);
|
|
@@ -51,7 +52,11 @@ var import_output = require("./output");
|
|
|
51
52
|
var import_workspace = require("./workspace");
|
|
52
53
|
var import_workspaceLock = require("./workspaceLock");
|
|
53
54
|
var import_workspaceRoot = require("./workspaceRoot");
|
|
54
|
-
|
|
55
|
+
let pauseMs = 2e3;
|
|
56
|
+
const pause = () => new Promise((resolve) => setTimeout(resolve, pauseMs));
|
|
57
|
+
function useWaitPause(ms = 2e3) {
|
|
58
|
+
pauseMs = ms;
|
|
59
|
+
}
|
|
55
60
|
function waitSeconds(value) {
|
|
56
61
|
const seconds = Number(value);
|
|
57
62
|
if (!Number.isFinite(seconds) || seconds < 0 || seconds > 3600)
|
|
@@ -83,8 +88,8 @@ function workspaceApi(workspace) {
|
|
|
83
88
|
);
|
|
84
89
|
return api;
|
|
85
90
|
}
|
|
86
|
-
function
|
|
87
|
-
const operations = (
|
|
91
|
+
function planSignature(plan) {
|
|
92
|
+
const operations = (plan.operations ?? []).map(
|
|
88
93
|
(op) => (0, import_documents.canonicalText)({
|
|
89
94
|
action: op.action,
|
|
90
95
|
kind: op.kind,
|
|
@@ -94,7 +99,7 @@ function sameStoredPlan(stored, draft) {
|
|
|
94
99
|
paths: op.fieldDiff.map((diff) => diff.path)
|
|
95
100
|
})
|
|
96
101
|
).sort();
|
|
97
|
-
return (0, import_documents.canonicalText)(
|
|
102
|
+
return (0, import_documents.canonicalText)([[...plan.documentKeys ?? []], plan.handles ?? {}, operations]);
|
|
98
103
|
}
|
|
99
104
|
function composeWorkspace(root, state) {
|
|
100
105
|
const evidence = {
|
|
@@ -129,7 +134,7 @@ async function readHead(api, deadline, print) {
|
|
|
129
134
|
const PRESERVE_NOTICE = {
|
|
130
135
|
unmaterialized: "unmaterialized",
|
|
131
136
|
"kept-local": "kept local",
|
|
132
|
-
"kept-local-edits": "kept local edits",
|
|
137
|
+
"kept-local-edits": "kept local edits (deleted, or no longer visible)",
|
|
133
138
|
conflict: "conflict",
|
|
134
139
|
"local-deletion-pending": "kept local",
|
|
135
140
|
"pull-needed": "pull needed",
|
|
@@ -278,20 +283,25 @@ async function materializeReceipt(api, root, planId, head, print) {
|
|
|
278
283
|
const result = requireComplete(
|
|
279
284
|
await (0, import_layoutReceipt.materializeLayoutPlan)({ root, head, source: { kind: "receipt", planId }, api })
|
|
280
285
|
);
|
|
281
|
-
const written = loadState(root);
|
|
282
|
-
delete written.layout.receipts[planId];
|
|
283
|
-
(0, import_workspace.saveState)(root, written);
|
|
284
286
|
const notices = planNotices(result);
|
|
285
287
|
(0, import_output.renderNotices)(notices).forEach((line) => print(line));
|
|
286
288
|
reportCompositionWarnings(result.compositionWarnings, print);
|
|
287
289
|
reportUnverified(result, print);
|
|
288
290
|
reportCleanup(result, print);
|
|
291
|
+
const superseded = result.droppedDrafts ?? [];
|
|
292
|
+
if (superseded.length)
|
|
293
|
+
print(
|
|
294
|
+
`Dropped the saved plan${superseded.length > 1 ? "s" : ""} ${superseded.map((id) => `p${id}`).join(", ")}: planned before p${planId}, which is now applied.`
|
|
295
|
+
);
|
|
289
296
|
return notices;
|
|
290
297
|
}
|
|
291
298
|
async function writeUnwrittenReceipts(api, root, head, print) {
|
|
292
299
|
let attention = false;
|
|
293
|
-
|
|
294
|
-
|
|
300
|
+
const applying = Object.entries(loadState(root).layout.receipts).sort(([left], [right]) => Number(left) - Number(right)).flatMap(
|
|
301
|
+
([planId, { applying: applying2, unanswered, receipt, submission }]) => applying2 ? [{ planId, unanswered, receipt, operations: submission.operations }] : []
|
|
302
|
+
);
|
|
303
|
+
for (const draft of applying) {
|
|
304
|
+
const { planId } = draft;
|
|
295
305
|
let receipt = draft.receipt;
|
|
296
306
|
if (!receipt) {
|
|
297
307
|
const observed = await api.attempt(planId);
|
|
@@ -310,7 +320,7 @@ async function writeUnwrittenReceipts(api, root, head, print) {
|
|
|
310
320
|
storeReceipt(root, planId, receipt);
|
|
311
321
|
}
|
|
312
322
|
print(`Writing the receipt of plan p${planId}: r${receipt.revisionId} (${receipt.status}).`);
|
|
313
|
-
(0, import_output.renderReceipt)(receipt, [...draft.
|
|
323
|
+
(0, import_output.renderReceipt)(receipt, [...draft.operations]).forEach((line) => print(line));
|
|
314
324
|
const notices = await materializeReceipt(api, root, planId, head, print);
|
|
315
325
|
if ((0, import_output.layoutExitCode)(notices, receipt.status)) attention = true;
|
|
316
326
|
}
|
|
@@ -332,7 +342,7 @@ async function pullWorkspace(workspace, force, seconds, print, options) {
|
|
|
332
342
|
if (attention) process.exitCode = 1;
|
|
333
343
|
return written;
|
|
334
344
|
}
|
|
335
|
-
async function uploadChangedBytes(api, root, state, current) {
|
|
345
|
+
async function uploadChangedBytes(api, root, state, current, only) {
|
|
336
346
|
const known = new Set(
|
|
337
347
|
state.layout.evidence.binaryRoutes.flatMap((route) => route.byteHash ? [route.byteHash] : [])
|
|
338
348
|
);
|
|
@@ -344,7 +354,8 @@ async function uploadChangedBytes(api, root, state, current) {
|
|
|
344
354
|
const sent = /* @__PURE__ */ new Set();
|
|
345
355
|
for (const fact of current.byteFacts) {
|
|
346
356
|
if (!referenced.has(fact.path) || fact.state !== "present") continue;
|
|
347
|
-
if (
|
|
357
|
+
if (sent.has(fact.content.sha256)) continue;
|
|
358
|
+
if (only ? !only.has(fact.content.sha256) : known.has((0, import_layoutCore.canonicalFragmentHash)(fact.content)))
|
|
348
359
|
continue;
|
|
349
360
|
if (fact.content.size > import_binaryDisk.BLOB_UPLOAD_LIMIT)
|
|
350
361
|
throw new Error(`Changed file ${fact.path} exceeds the 64 MiB upload limit`);
|
|
@@ -354,6 +365,19 @@ async function uploadChangedBytes(api, root, state, current) {
|
|
|
354
365
|
await api.uploadBlob(fact.content.sha256, fs.createReadStream(source));
|
|
355
366
|
sent.add(fact.content.sha256);
|
|
356
367
|
}
|
|
368
|
+
return sent.size;
|
|
369
|
+
}
|
|
370
|
+
function missingBlobHashes(plan, documents) {
|
|
371
|
+
const keys = new Set(plan?.diagnostics.flatMap((d) => d.code === "missing-blob" && d.key ? [d.key] : []));
|
|
372
|
+
const hashes = /* @__PURE__ */ new Set();
|
|
373
|
+
plan?.documentKeys?.forEach((key, index) => {
|
|
374
|
+
if (!keys.has(key)) return;
|
|
375
|
+
for (const field of ["content", "icon", "template"]) {
|
|
376
|
+
const sha256 = documents[index]?.[field]?.sha256;
|
|
377
|
+
if (typeof sha256 === "string") hashes.add(sha256);
|
|
378
|
+
}
|
|
379
|
+
});
|
|
380
|
+
return hashes;
|
|
357
381
|
}
|
|
358
382
|
async function planModel(workspace, seconds, print = console.log, options = {}) {
|
|
359
383
|
return (0, import_workspaceLock.withWorkspaceLock)(workspace.root, "code plan", () => planWorkspace(workspace, seconds, print, options));
|
|
@@ -375,13 +399,19 @@ async function planWorkspace(workspace, seconds, print, options) {
|
|
|
375
399
|
await uploadChangedBytes(api, root, state, current);
|
|
376
400
|
(0, import_layoutReceipt.refuseUnwrittenReceipts)(state);
|
|
377
401
|
const deadline = Date.now() + seconds * 1e3;
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
402
|
+
const submit = async () => {
|
|
403
|
+
let response2 = await api.plan(current.documents, state.baseline);
|
|
404
|
+
while (response2.status === 409 && Date.now() < deadline) {
|
|
405
|
+
note(`Apply r${response2.data.revisionId} in progress; retry shortly.`);
|
|
406
|
+
await pause();
|
|
407
|
+
response2 = await api.plan(current.documents, state.baseline);
|
|
408
|
+
}
|
|
409
|
+
if (response2.status === 409) throw new Error("Apply in progress; retry farseer code plan shortly");
|
|
410
|
+
return response2;
|
|
411
|
+
};
|
|
412
|
+
let response = await submit();
|
|
413
|
+
const missing = missingBlobHashes(planOf(response.data), current.documents);
|
|
414
|
+
if (missing.size && await uploadChangedBytes(api, root, state, current, missing)) response = await submit();
|
|
385
415
|
const planned = planOf(response.data);
|
|
386
416
|
if (planned && planned.documentKeys?.length === current.documents.length)
|
|
387
417
|
(0, import_documents.validateDocumentKeys)(current.documents, planned.documentKeys, true);
|
|
@@ -418,6 +448,18 @@ function planRefusal(status, body) {
|
|
|
418
448
|
if (typeof code !== "string") return `Invalid plan response (HTTP ${status})`;
|
|
419
449
|
return `The server refused the plan (HTTP ${status}, ${code})${typeof message === "string" ? `: ${message}` : ""}`;
|
|
420
450
|
}
|
|
451
|
+
function savedDraft(root, planId, print) {
|
|
452
|
+
const state = loadState(root), draft = state.layout.receipts[planId];
|
|
453
|
+
reportUnreadableReceipts(state, print);
|
|
454
|
+
if (!draft) {
|
|
455
|
+
const unreadable = (0, import_layoutReceipt.layoutReceiptDrafts)(state).find(([id, saved]) => id === planId && saved.quarantined);
|
|
456
|
+
throw new Error(
|
|
457
|
+
!unreadable ? `This plan was not created in this workspace, its receipt is already written, or its draft was dropped (planned before a plan applied here, or older than the newest ${KEPT_UNAPPLIED_DRAFTS} unapplied plans); run farseer code pull, then create a new plan here` : unreadable[1].applying ? (0, import_layoutReceipt.quarantinedApplyAdvice)(planId) : `The saved receipt for plan p${planId} could not be read; run farseer code plan and apply the new plan`
|
|
458
|
+
);
|
|
459
|
+
}
|
|
460
|
+
(0, import_layoutReceipt.refuseUnwrittenReceipts)(state, planId);
|
|
461
|
+
return { applying: !!draft.applying, unanswered: !!draft.unanswered, signature: planSignature(draft.submission) };
|
|
462
|
+
}
|
|
421
463
|
async function applyModel(workspace, rawId, seconds, print = console.log) {
|
|
422
464
|
return (0, import_workspaceLock.withWorkspaceLock)(
|
|
423
465
|
workspace.root,
|
|
@@ -431,14 +473,7 @@ async function applyWorkspace(workspace, rawId, seconds, print) {
|
|
|
431
473
|
const api = workspaceApi(workspace);
|
|
432
474
|
pruneSavedDrafts(workspace.root, print);
|
|
433
475
|
const root = workspace.root;
|
|
434
|
-
const
|
|
435
|
-
reportUnreadableReceipts(initial, print);
|
|
436
|
-
if (!draft) {
|
|
437
|
-
const unreadable = (0, import_layoutReceipt.layoutReceiptDrafts)(initial).find(([id, saved]) => id === planId && saved.quarantined);
|
|
438
|
-
throw new Error(
|
|
439
|
-
!unreadable ? `This plan was not created in this workspace, its receipt is already written, or it was dropped as older than the newest ${KEPT_UNAPPLIED_DRAFTS} unapplied plans; create a new plan here` : unreadable[1].applying ? (0, import_layoutReceipt.quarantinedApplyAdvice)(planId) : `The saved receipt for plan p${planId} could not be read; run farseer code plan and apply the new plan`
|
|
440
|
-
);
|
|
441
|
-
}
|
|
476
|
+
const draft = savedDraft(root, planId, print);
|
|
442
477
|
const reportExpired = (expiresAt) => {
|
|
443
478
|
const on = expiresAt && expiryText(expiresAt);
|
|
444
479
|
print(`Plan p${planId} expired${on ? ` on ${on}` : ""}; run farseer code plan again.`);
|
|
@@ -465,7 +500,7 @@ async function applyWorkspace(workspace, rawId, seconds, print) {
|
|
|
465
500
|
});
|
|
466
501
|
throw error;
|
|
467
502
|
}
|
|
468
|
-
if (
|
|
503
|
+
if (planSignature(storedPlan) !== draft.signature)
|
|
469
504
|
throw new Error(
|
|
470
505
|
`Plan p${planId} on ${workspace.state.baseUrl} is not the plan this workspace created (its documents, operations or handles differ); run farseer code plan and apply the new plan`
|
|
471
506
|
);
|
|
@@ -576,6 +611,7 @@ async function applyWorkspace(workspace, rawId, seconds, print) {
|
|
|
576
611
|
planModel,
|
|
577
612
|
pruneDrafts,
|
|
578
613
|
pullModel,
|
|
614
|
+
useWaitPause,
|
|
579
615
|
waitSeconds
|
|
580
616
|
});
|
|
581
617
|
//# sourceMappingURL=workflow.js.map
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/services/codefirst/workflow.ts"],
|
|
4
|
-
"sourcesContent": ["import * as fs from 'fs';\nimport type { ErrorResponse } from 'farseer-client';\nimport * as path from 'path';\nimport { CodeFirstApi, requestSettled } from './api';\nimport { BLOB_UPLOAD_LIMIT, hashFile, sameBytes, type BlobApi } from './binaryDisk';\nimport { canonicalText, parseState, validateDocumentKeys } from './documents';\nimport { composeLayoutSubmission, submittedDocumentFiles, type ComposeLayoutSubmissionResult } from './layoutCompose';\nimport { canonicalFragmentHash } from './layoutCore';\nimport { rawBytesPath } from './layoutPaths';\nimport {\n bindLayoutReceiptSubmission,\n captureLayoutSubmissionComposition,\n type LayoutReceiptSubmission,\n type PhysicalMaterialization,\n type PreserveReason,\n} from './layoutReadback';\nimport {\n layoutReceiptDrafts,\n materializeLayoutPlan,\n quarantinedApplyAdvice,\n refuseUnwrittenReceipts,\n type LayoutPlanOutcome,\n} from './layoutReceipt';\nimport { loadLayoutByteEvidence, resolveLayoutPath, scanLayout, stateText } from './layoutScan';\nimport { layoutExitCode, renderNotices, renderPlan, renderReceipt } from './output';\nimport {\n ApplyingHead,\n Head,\n Json,\n LayoutReceiptDraft,\n Notice,\n Pending,\n Plan,\n PlanOperation,\n Receipt,\n State,\n} from './types';\nimport { saveLearnedByteHashes, saveState, STATE_FILE, workspacePath } from './workspace';\nimport { withWorkspaceLock } from './workspaceLock';\nimport { createCodeWorkspace, type CodeWorkspace } from './workspaceRoot';\nimport { TenantSession } from '../preflight';\n\n/** One resolved code workspace and the authenticated target its state names. */\nexport interface WorkspaceCommand extends CodeWorkspace {\n target: TenantSession;\n}\n\ntype CompleteComposition = Extract<ComposeLayoutSubmissionResult, { status: 'complete' }>;\n\nconst pause = () => new Promise<void>((resolve) => setTimeout(resolve, 2000));\nexport function waitSeconds(value: string): number {\n const seconds = Number(value);\n if (!Number.isFinite(seconds) || seconds < 0 || seconds > 3600)\n throw new Error('--wait-seconds must be between 0 and 3600');\n return seconds;\n}\nfunction loadState(root: string): State {\n if (!fs.existsSync(workspacePath(root, STATE_FILE)))\n throw new Error('No model workspace; run farseer code checkout <tenant> first');\n return parseState(stateText(root));\n}\n\n/**\n * Change one draft on the state as it is on disk now, never on a copy read earlier: another\n * command may have saved in between (a plan or a pull in another shell), and saving an older copy\n * would undo that save. Returns false when the draft is gone, so there is nothing to change.\n */\nfunction updateDraft(root: string, planId: string, change: (draft: LayoutReceiptDraft) => void): boolean {\n const current = loadState(root);\n const draft = current.layout.receipts[planId];\n if (!draft) return false;\n change(draft);\n saveState(root, current);\n return true;\n}\n\n/** What the author does when an apply request of `planId` may still be running on the server. */\nfunction unansweredApply(planId: string): string {\n return (\n `the apply request for plan p${planId} got no answer from the server, so it may still be running ` +\n `there; run farseer code apply p${planId} again, which resumes that apply and writes its receipt`\n );\n}\n\n/**\n * The API of one workspace command, refused when it would reach another server than the one the\n * workspace was checked out from. Plan ids are per-server sequences and a baseline names versions\n * only its own server stores, so `code apply 5` against another server would apply that server's\n * plan 5. `FARSEER_API_URL` or another stored credential is the usual way to get there.\n */\nfunction workspaceApi(workspace: WorkspaceCommand): CodeFirstApi {\n const api = new CodeFirstApi(workspace.target);\n const resolved = api.baseUrl();\n if (resolved !== workspace.state.baseUrl)\n throw new Error(\n `This workspace was checked out from ${workspace.state.baseUrl}, but this command would use ` +\n `${resolved}; run it with the credential and FARSEER_API_URL the workspace was checked out with`,\n );\n return api;\n}\n\n/**\n * Whether the server's stored plan is the one this workspace's draft recorded when it was created:\n * the same document keys, the same handles (the receipt writes assigned ids into files through\n * them), and per operation the same action, kind, key, handle, name and changed paths. The rendered\n * values are left out, because a stored plan's read masks job secrets for display.\n */\nfunction sameStoredPlan(stored: Plan, draft: LayoutReceiptSubmission): boolean {\n const operations = (items: readonly PlanOperation[]) =>\n items\n .map((op) =>\n canonicalText({\n action: op.action,\n kind: op.kind,\n key: op.key ?? null,\n handle: op.handle ?? null,\n name: op.name,\n paths: op.fieldDiff.map((diff) => diff.path),\n }),\n )\n .sort();\n return (\n canonicalText(stored.documentKeys ?? []) === canonicalText([...draft.documentKeys]) &&\n canonicalText((stored.handles ?? {}) as unknown as Json) === canonicalText(draft.handles as unknown as Json) &&\n canonicalText(operations(stored.operations ?? [])) === canonicalText(operations(draft.operations))\n );\n}\nfunction composeWorkspace(root: string, state: State): CompleteComposition {\n const evidence = {\n ...state.layout.evidence,\n groupedSubmissionProofs: [],\n binarySubmissionProofs: [],\n canonicalBaseline: state.baseline,\n };\n const scan = scanLayout({ root, tracked: state.layout.tracked });\n const composed = composeLayoutSubmission({\n scan,\n byteEvidence: loadLayoutByteEvidence({ root, scan, evidence }),\n evidence,\n });\n if (composed.status !== 'complete')\n throw new Error(\n `Workspace cannot be composed: ${composed.diagnostics.map((item) => `${item.code} ${item.path}: ${item.message}`).join('; ')}`,\n );\n return composed;\n}\nasync function readHead(api: CodeFirstApi, deadline: number, print: (line: string) => void): Promise<Head> {\n for (;;) {\n const response = await api.head();\n if (response.status === 200) return response.data as Head;\n if (response.status !== 409) throw new Error(`Unable to read model head (HTTP ${response.status})`);\n const revision = (response.data as ApplyingHead).revisionId;\n if (Date.now() >= deadline) throw new Error(`Apply r${revision} is in progress; retry pull shortly`);\n print(`Apply r${revision} in progress; retry shortly.`);\n await pause();\n }\n}\n\n/** Why a resource kept its local content, in the notice vocabulary the commands already print. */\nconst PRESERVE_NOTICE: Record<PreserveReason, Notice['status'] | undefined> = {\n unmaterialized: 'unmaterialized',\n 'kept-local': 'kept local',\n 'kept-local-edits': 'kept local edits',\n conflict: 'conflict',\n 'local-deletion-pending': 'kept local',\n 'pull-needed': 'pull needed',\n 'protected-descendant': 'conflict',\n // The one `kept-in-place` notice names the folder and everything that holds it; this is silent.\n 'folder-held': undefined,\n 'unsupported-evidence': 'conflict',\n 'post-submission-change': 'kept local edits',\n // A receipt says nothing about a resource it never carried; that is not news for the author.\n 'deferred-receipt': undefined,\n 'shared-container-relocation': 'kept local',\n 'shared-container-sibling': 'kept local',\n 'unsuccessful-outcome': undefined,\n 'missing-outcome': undefined,\n};\n\nfunction materializationPath(item: Extract<PhysicalMaterialization, { mode: 'set' }>): string {\n return item.codec === 'grouped' ? item.destination.file : item.bytes;\n}\n\nfunction preservePath(item: Extract<PhysicalMaterialization, { mode: 'preserve' }>): string {\n for (const contributor of item.contributors) {\n if (contributor.kind === 'grouped' || contributor.kind === 'grouped-navigation')\n return contributor.selector.file;\n if (contributor.kind === 'raw') return contributor.bytes ?? rawBytesPath(contributor.selector.sidecar);\n }\n return item.documentKey ?? 'workspace';\n}\n\nfunction planNotices(result: LayoutPlanOutcome): Notice[] {\n const notices: Notice[] = [];\n for (const item of result.materializations) {\n if (item.mode === 'set')\n notices.push({\n status: item.placement === 'insert-authoritative' ? 'new' : 'updated',\n key: item.documentKey,\n path: materializationPath(item),\n });\n else if (item.mode === 'preserve') {\n const status = PRESERVE_NOTICE[item.reason];\n if (status)\n notices.push({\n status,\n ...(item.documentKey ? { key: item.documentKey } : {}),\n path: preservePath(item),\n });\n }\n }\n for (const removal of result.deletes.json)\n notices.push({ status: 'deleted', key: removal.documentKeys[0], path: removal.path });\n for (const notice of result.notices) notices.push({ ...notice });\n return notices;\n}\n\n/** Name the resources that kept their old baseline, and once why the rescan could not prove them. */\nfunction reportUnverified(result: LayoutPlanOutcome, print: (line: string) => void): void {\n if (!result.unverifiedDocumentKeys.length) return;\n print(\n `warning: unverified-readback: ${result.unverifiedDocumentKeys.length} resources kept their previous baseline (${result.unverifiedDocumentKeys.slice(0, 5).join(', ')}${result.unverifiedDocumentKeys.length > 5 ? ', \u2026' : ''})`,\n );\n for (const item of result.verificationDiagnostics.slice(0, 5))\n print(`warning: ${item.code}: ${item.path}: ${item.message}`);\n}\n\n/** Per-resource composition problems: the command carried on, so they print as plain warnings. */\nfunction reportCompositionWarnings(\n warnings: readonly { code: string; path: string; message: string }[],\n print: (line: string) => void,\n): void {\n for (const item of warnings) print(`warning: ${item.code}: ${item.path}: ${item.message}`);\n}\n\n/** Temporary files the writer could not remove. The workspace is already saved and correct. */\nfunction reportCleanup(result: LayoutPlanOutcome, print: (line: string) => void): void {\n for (const warning of result.cleanupWarnings ?? []) print(`warning: cleanup: ${warning}`);\n}\n\n/**\n * Name every receipt the state reader set aside. The workspace stays usable; what it loses is the\n * receipt's own evidence, so a create that receipt assigned can reach the next plan as a create.\n */\nfunction reportUnreadableReceipts(state: State, print: (line: string) => void): void {\n for (const planId of Object.keys(state.layout.unreadableReceipts ?? {}).sort())\n print(\n `warning: the saved receipt for plan p${planId} could not be read and was set aside; ` +\n 'read the next plan before applying it, in case it creates a resource that apply already made',\n );\n}\n\n/**\n * Name the head resources the workspace does not hold. A command sends the baseline it has, so a\n * workspace that could not materialize everything otherwise reports no drift at all. A pull counts\n * them against the head it read; a plan takes the count the server computed against its own read.\n */\nfunction reportBehindHead(behind: number, print: (line: string) => void): void {\n if (behind > 0)\n print(`warning: workspace is behind head: ${behind} resources not materialized locally; run farseer code pull`);\n}\n\nfunction requireComplete(result: Awaited<ReturnType<typeof materializeLayoutPlan>>): LayoutPlanOutcome {\n if (result.status === 'blocked')\n throw new Error(\n `Workspace cannot be updated: ${result.diagnostics.map((item) => `${item.code} ${item.path}: ${item.message}`).join('; ')}`,\n );\n return result;\n}\n\n/** Fast-forward one workspace to the head the caller just read, and report every resource it touched. */\nasync function materializeHead(\n api: CodeFirstApi,\n root: string,\n head: Head,\n force: boolean,\n print: (line: string) => void,\n verbose = false,\n): Promise<number> {\n const result = requireComplete(\n await materializeLayoutPlan({ root, head, source: { kind: 'checkout', force }, api }),\n );\n const notices = planNotices(result);\n renderNotices(notices).forEach((line) => print(line));\n reportCompositionWarnings(result.compositionWarnings, print);\n reportUnverified(result, print);\n reportCleanup(result, print);\n // The head's diagnostics are tenant data the pull did not cause; only --verbose prints them.\n if (verbose) head.diagnostics.forEach((d) => print(`warning: ${d.code}: ${d.message}`));\n const saved = loadState(root);\n reportUnreadableReceipts(saved, print);\n reportBehindHead(Object.entries(head.manifest).filter(([key, hash]) => saved.baseline[key] !== hash).length, print);\n print(`Model pulled at r${head.revisionId}: ${Object.keys(head.manifest).length} resources.`);\n if (layoutExitCode(notices)) process.exitCode = 1;\n return notices.filter((notice) => ['new', 'updated', 'deleted'].includes(notice.status)).length;\n}\n\n/**\n * Create `<directory>/<tenant>/` and fill it with the head. The head is read before anything exists.\n * The directory and the stored identity come from the resolved target. `typedTenant` is the tenant\n * the command named, if it named one: it must be the resolved tenant and no other, so a saved\n * mapping can never redirect a named checkout to a different model. With no tenant typed, the\n * command asked for `FARSEER_TENANT`'s tenant and there is nothing to cross-check.\n */\nexport async function checkoutModel(\n target: TenantSession,\n typedTenant: string | undefined,\n directory: string,\n seconds: number,\n print = console.log,\n options: { verbose?: boolean } = {},\n): Promise<number> {\n if (typedTenant !== undefined && target.tenant !== typedTenant)\n throw new Error(\n `Refusing to check out: the command named the tenant ${typedTenant} but the resolved target is ${target.tenant}`,\n );\n const api = new CodeFirstApi(target);\n const head = await readHead(api, Date.now() + seconds * 1000, print);\n const root = createCodeWorkspace(directory, target.tenant, {\n organisation: target.organisation,\n baseUrl: api.baseUrl(),\n });\n return withWorkspaceLock(root, 'code checkout', async () => {\n print(`Checked out ${target.tenant} into ${root}`);\n return materializeHead(api, root, head, false, print, options.verbose);\n });\n}\n\n/** How many plans that were created but never applied stay applicable from this workspace. */\nexport const KEPT_UNAPPLIED_DRAFTS = 3;\n\n/**\n * Drop the drafts this workspace no longer needs: one whose receipt is written, and the oldest of\n * those never applied beyond the newest few. Each draft holds the whole submitted workspace, and an\n * author who re-plans ten times should not pay for ten copies. A draft that is `applying` is never\n * dropped. Returns whether anything was dropped, and the never-applied plans among the dropped ones.\n */\nexport function pruneDrafts(state: State): { changed: boolean; unapplied: string[] } {\n const before = Object.keys(state.layout.receipts).length;\n for (const [planId, draft] of Object.entries(state.layout.receipts))\n if (draft.receipt && !draft.applying) delete state.layout.receipts[planId];\n const unapplied = Object.entries(state.layout.receipts)\n .filter(([, draft]) => !draft.applying && !draft.receipt)\n .map(([planId]) => planId)\n .sort((left, right) => Number(right) - Number(left));\n const dropped = unapplied.slice(KEPT_UNAPPLIED_DRAFTS).reverse();\n for (const planId of dropped) delete state.layout.receipts[planId];\n return { changed: Object.keys(state.layout.receipts).length !== before, unapplied: dropped };\n}\n\n/**\n * The line that names the never-applied plans a prune dropped, so a later `code apply` of one of\n * them is not a surprise. A dropped draft whose receipt is written is done and goes unannounced.\n */\nfunction reportDroppedDrafts(unapplied: readonly string[], print: (line: string) => void): void {\n if (!unapplied.length) return;\n const plans = unapplied.map((planId) => `p${planId}`).join(', ');\n print(\n `Dropped the saved plan${unapplied.length > 1 ? 's' : ''} ${plans}: only the newest ` +\n `${KEPT_UNAPPLIED_DRAFTS} unapplied plans stay applicable.`,\n );\n}\n\n/** Every command starts by shedding the drafts it will never read again, before it loads anything else. */\nfunction pruneSavedDrafts(root: string, print: (line: string) => void): void {\n const current = loadState(root);\n const pruned = pruneDrafts(current);\n if (pruned.changed) saveState(root, current);\n reportDroppedDrafts(pruned.unapplied, print);\n}\n\n/**\n * Save an attempt's receipt in its draft before any document changes. The draft stays `applying`\n * until the receipt is written, so a pull or a retry that finds it still writes it first.\n */\nfunction storeReceipt(root: string, planId: string, receipt: Receipt): void {\n const stored = loadState(root);\n // The receipt is the server's answer, so no request of this draft is left running.\n const draft = { ...stored.layout.receipts[planId], receipt, revisionId: receipt.revisionId, applying: true };\n delete draft.unanswered;\n stored.layout.receipts[planId] = draft;\n saveState(root, stored);\n}\n\n/** Write one saved receipt into the workspace against the head the caller read, and report it. */\nasync function materializeReceipt(\n api: CodeFirstApi,\n root: string,\n planId: string,\n head: Head,\n print: (line: string) => void,\n): Promise<Notice[]> {\n const result = requireComplete(\n await materializeLayoutPlan({ root, head, source: { kind: 'receipt', planId }, api }),\n );\n // The draft existed to bind this receipt to the files it was planned from; written, it is done.\n const written = loadState(root);\n delete written.layout.receipts[planId];\n saveState(root, written);\n const notices = planNotices(result);\n renderNotices(notices).forEach((line) => print(line));\n reportCompositionWarnings(result.compositionWarnings, print);\n reportUnverified(result, print);\n reportCleanup(result, print);\n return notices;\n}\n\n/**\n * Write the receipt of every apply this workspace has not written yet, before the pull: one whose\n * response never arrived, and one saved but not written. The head holds that apply's creates, and\n * only its receipt proves which local file each of them is; without it the pull would place them a\n * second time. `GET \u2026/attempt` only observes, so this never resumes an attempt. A 404 from it proves\n * the plan was never admitted only when every apply request of the draft got the server's answer,\n * the same evidence `releaseIfAbsent` clears on in `code apply`: the `applying` guard is cleared and\n * the draft stays, still applicable. A draft whose request went unanswered (`unanswered`) may still\n * be admitted by that request, so it keeps the guard and the pull stops. Any other answer, or a\n * failed read, keeps the guard. Returns whether a receipt needs the author.\n */\nasync function writeUnwrittenReceipts(\n api: CodeFirstApi,\n root: string,\n head: Head,\n print: (line: string) => void,\n): Promise<boolean> {\n let attention = false;\n for (const [planId, draft] of Object.entries(loadState(root).layout.receipts).sort()) {\n if (!draft.applying) continue;\n let receipt = draft.receipt;\n if (!receipt) {\n const observed = await api.attempt(planId);\n if (observed.status === 404 && draft.unanswered)\n throw new Error(`Cannot pull yet: ${unansweredApply(planId)}`);\n // No attempt exists and no request can still create one, so the guard has nothing to protect.\n if (observed.status === 404) {\n updateDraft(root, planId, (current) => {\n current.applying = false;\n });\n print(`Plan p${planId} was never applied; it stays applicable with farseer code apply p${planId}`);\n continue;\n }\n if (observed.status !== 200)\n throw new Error(`Apply p${planId} is still in progress; resume it with farseer code apply p${planId}`);\n receipt = observed.data as Receipt;\n storeReceipt(root, planId, receipt);\n }\n print(`Writing the receipt of plan p${planId}: r${receipt.revisionId} (${receipt.status}).`);\n renderReceipt(receipt, [...draft.submission.operations]).forEach((line) => print(line));\n const notices = await materializeReceipt(api, root, planId, head, print);\n if (layoutExitCode(notices, receipt.status)) attention = true;\n }\n return attention;\n}\n\n/** `code pull`, holding the workspace lock. */\nexport async function pullModel(\n workspace: WorkspaceCommand,\n force: boolean,\n seconds: number,\n print: (line: string) => void = console.log,\n options: { verbose?: boolean } = {},\n): Promise<number> {\n return withWorkspaceLock(workspace.root, 'code pull', () =>\n pullWorkspace(workspace, force, seconds, print, options),\n );\n}\n\nasync function pullWorkspace(\n workspace: WorkspaceCommand,\n force: boolean,\n seconds: number,\n print: (line: string) => void,\n options: { verbose?: boolean },\n): Promise<number> {\n const api = workspaceApi(workspace);\n pruneSavedDrafts(workspace.root, print);\n const head = await readHead(api, Date.now() + seconds * 1000, print);\n const attention = await writeUnwrittenReceipts(api, workspace.root, head, print);\n const written = await materializeHead(api, workspace.root, head, force, print, options.verbose);\n if (attention) process.exitCode = 1;\n return written;\n}\n\n/** Upload every referenced blob whose descriptor the workspace evidence does not already know. */\nasync function uploadChangedBytes(\n api: Pick<BlobApi, 'uploadBlob'>,\n root: string,\n state: State,\n current: CompleteComposition,\n): Promise<void> {\n const known = new Set(\n state.layout.evidence.binaryRoutes.flatMap((route) => (route.byteHash ? [route.byteHash] : [])),\n );\n const referenced = new Set(\n [...current.binary.rawObservations, ...current.binary.attachmentObservations].flatMap((observation) =>\n observation.bytes ? [observation.bytes] : [],\n ),\n );\n const sent = new Set<string>();\n for (const fact of current.byteFacts) {\n if (!referenced.has(fact.path) || fact.state !== 'present') continue;\n if (known.has(canonicalFragmentHash(fact.content as unknown as Json)) || sent.has(fact.content.sha256))\n continue;\n if (fact.content.size > BLOB_UPLOAD_LIMIT)\n throw new Error(`Changed file ${fact.path} exceeds the 64 MiB upload limit`);\n const source = resolveLayoutPath(root, fact.path);\n if (!sameBytes(hashFile(source), fact.content))\n throw new Error(`Local bytes changed before upload: ${fact.path}`);\n await api.uploadBlob(fact.content.sha256, fs.createReadStream(source));\n sent.add(fact.content.sha256);\n }\n}\n\ntype PlanOptions = { verbose?: boolean; json?: boolean; note?: (line: string) => void };\n\n/**\n * `code plan`, holding the workspace lock. With `json`, `print` receives the plan response exactly\n * as the server returned it and nothing else, so stdout can be parsed; every other line goes to\n * `note` (stderr by default).\n */\nexport async function planModel(\n workspace: WorkspaceCommand,\n seconds: number,\n print: (line: string) => void = console.log,\n options: PlanOptions = {},\n): Promise<void> {\n return withWorkspaceLock(workspace.root, 'code plan', () => planWorkspace(workspace, seconds, print, options));\n}\n\nasync function planWorkspace(\n workspace: WorkspaceCommand,\n seconds: number,\n print: (line: string) => void,\n options: PlanOptions,\n): Promise<void> {\n const api = workspaceApi(workspace);\n const note = options.json ? (options.note ?? console.error) : print;\n pruneSavedDrafts(workspace.root, note);\n const root = workspace.root,\n readText = stateText(root),\n state = parseState(readText);\n const current = composeWorkspace(root, state);\n reportUnreadableReceipts(state, note);\n reportCompositionWarnings(current.warnings, note);\n if (!current.documents.length && !Object.keys(state.baseline).length)\n throw new Error('The workspace holds no model; run farseer code pull first');\n // A deleted tree or a `git clean -fd` (which keeps the ignored .fscode/) would plan to delete everything.\n if (!current.documents.length)\n throw new Error(\n `The workspace holds no model files, but its baseline has ${Object.keys(state.baseline).length} ` +\n 'resources, so a plan would delete them all; restore the files with farseer code pull --force',\n );\n await uploadChangedBytes(api, root, state, current);\n refuseUnwrittenReceipts(state);\n const deadline = Date.now() + seconds * 1000;\n let response = await api.plan(current.documents, state.baseline);\n while (response.status === 409 && Date.now() < deadline) {\n note(`Apply r${(response.data as ApplyingHead).revisionId} in progress; retry shortly.`);\n await pause();\n response = await api.plan(current.documents, state.baseline);\n }\n if (response.status === 409) throw new Error('Apply in progress; retry farseer code plan shortly');\n const planned = planOf(response.data);\n if (planned && planned.documentKeys?.length === current.documents.length)\n validateDocumentKeys(current.documents, planned.documentKeys, true);\n // The server holds the plan from here on, so its draft is saved before anything else can fail.\n let dropped: string[] = [];\n if (planned?.planId) {\n const submission = bindLayoutReceiptSubmission({\n planId: planned.planId,\n plan: planned,\n captured: captureLayoutSubmissionComposition(current),\n });\n const saved = parseState(stateText(root));\n saved.layout.receipts[planned.planId] = { submission };\n dropped = pruneDrafts(saved).unapplied;\n saveState(root, saved);\n } else saveLearnedByteHashes(root, readText);\n if (options.json) print(JSON.stringify(response.body, null, 2));\n if (!planned) throw new Error(planRefusal(response.status, response.data));\n if (!options.json)\n renderPlan(planned, { verbose: options.verbose, files: submittedDocumentFiles(current.sources) }).forEach(\n (line) => print(line),\n );\n reportBehindHead(planned.behindHead ?? 0, note);\n if (planned.planId)\n note(`Plan p${planned.planId} created against r${planned.observedRevisionId ?? state.revisionId}.`);\n reportDroppedDrafts(dropped, note);\n if (!planned.applicable || response.status === 400) process.exitCode = 1;\n}\n\n/** A plan's expiry as the server wrote it (ISO 8601); an unreadable date is left out. */\nconst expiryText = (date: Date) => (Number.isNaN(date.getTime()) ? undefined : date.toISOString());\n\n/** A POST plans answer as a plan (a 400 one carries a top-level `code`); a plain error is none. */\nfunction planOf(body: unknown): Plan | undefined {\n return body !== null && typeof body === 'object' && 'operations' in body ? (body as Plan) : undefined;\n}\n/** Why a POST plans answer holds no plan: the server's `{code, message}` error, or what it sent instead. */\nfunction planRefusal(status: number, body: unknown): string {\n const { code, message } = (body !== null && typeof body === 'object' ? body : {}) as Partial<ErrorResponse>;\n if (typeof code !== 'string') return `Invalid plan response (HTTP ${status})`;\n return `The server refused the plan (HTTP ${status}, ${code})${typeof message === 'string' ? `: ${message}` : ''}`;\n}\n\n/** `code apply`, holding the workspace lock. */\nexport async function applyModel(\n workspace: WorkspaceCommand,\n rawId: string,\n seconds: number,\n print: (line: string) => void = console.log,\n): Promise<void> {\n return withWorkspaceLock(workspace.root, `code apply ${rawId}`, () =>\n applyWorkspace(workspace, rawId, seconds, print),\n );\n}\n\nasync function applyWorkspace(\n workspace: WorkspaceCommand,\n rawId: string,\n seconds: number,\n print: (line: string) => void,\n): Promise<void> {\n // `workspace` is the one this command resolved, together with the state read at that moment.\n // Never carry it across commands: the state on disk moves with every write below.\n const planId = rawId.replace(/^p/, '');\n if (!/^[1-9][0-9]*$/.test(planId)) throw new Error('Expected a plan id such as p123');\n const api = workspaceApi(workspace);\n pruneSavedDrafts(workspace.root, print);\n const root = workspace.root;\n const initial = loadState(root),\n draft = initial.layout.receipts[planId];\n reportUnreadableReceipts(initial, print);\n if (!draft) {\n const unreadable = layoutReceiptDrafts(initial).find(([id, saved]) => id === planId && saved.quarantined);\n throw new Error(\n !unreadable\n ? 'This plan was not created in this workspace, its receipt is already written, or it was dropped ' +\n `as older than the newest ${KEPT_UNAPPLIED_DRAFTS} unapplied plans; create a new plan here`\n : unreadable[1].applying\n ? quarantinedApplyAdvice(planId)\n : `The saved receipt for plan p${planId} could not be read; run farseer code plan and apply the new plan`,\n );\n }\n const reportExpired = (expiresAt?: Date) => {\n const on = expiresAt && expiryText(expiresAt);\n print(`Plan p${planId} expired${on ? ` on ${on}` : ''}; run farseer code plan again.`);\n process.exitCode = 1;\n };\n let absentAttempt = false;\n if (draft.applying) {\n // Clear a stale admission guard only after the server proves no attempt exists.\n // Transport/auth errors and existing attempts remain fail-closed.\n const observed = await api.attempt(planId);\n if (observed.status === 404) {\n absentAttempt = true;\n } else if (observed.status !== 200 && observed.status !== 202) {\n throw new Error(\n `Unable to inspect saved attempt (HTTP ${observed.status}); retry farseer code apply p${planId}`,\n );\n }\n }\n let storedPlan: Plan;\n try {\n storedPlan = (await api.getPlan(planId)).data;\n } catch (error) {\n // A 404 is proof only when no earlier apply request of this draft can still be running.\n if (absentAttempt && !draft.unanswered)\n updateDraft(root, planId, (current) => {\n current.applying = false;\n });\n throw error;\n }\n // Checked before the guard and the POST: a plan this workspace did not create must never run.\n if (!sameStoredPlan(storedPlan, draft.submission))\n throw new Error(\n `Plan p${planId} on ${workspace.state.baseUrl} is not the plan this workspace created ` +\n '(its documents, operations or handles differ); run farseer code plan and apply the new plan',\n );\n if (storedPlan.expired) {\n // The server proved no attempt exists, and an expired plan can never admit one.\n if (absentAttempt)\n updateDraft(root, planId, (current) => {\n current.applying = false;\n delete current.unanswered;\n });\n reportExpired(storedPlan.expiresAt);\n return;\n }\n // The request counts as unanswered from before it is sent until the server answers it.\n if (\n !updateDraft(root, planId, (current) => {\n current.applying = true;\n current.unanswered = true;\n })\n )\n throw new Error(`The saved draft of plan p${planId} was removed by another command; run farseer code pull`);\n const deadline = Date.now() + seconds * 1000;\n /**\n * After a POST that is over on the server side: no request is left running, so the guard is\n * cleared once `GET \u2026/attempt` proves no attempt exists, and kept otherwise (or when the read fails).\n */\n const releaseIfAbsent = async () => {\n let observed;\n try {\n observed = await api.attempt(planId);\n } catch {\n observed = undefined;\n }\n updateDraft(root, planId, (current) => {\n delete current.unanswered;\n if (observed?.status === 404) current.applying = false;\n });\n };\n /**\n * A POST that may still be running on the server keeps the guard: admission can go on there and\n * assign ids nobody would record. Posting the same apply again is idempotent, so that is the way on.\n */\n const post = () =>\n api.apply(planId).catch(async (error: unknown) => {\n if (!requestSettled(error))\n throw new Error(\n `${error instanceof Error ? error.message : String(error)}: ${unansweredApply(planId)}`,\n { cause: error },\n );\n await releaseIfAbsent();\n throw error;\n });\n let response = await post();\n // Another apply holds the head, or the head moved twice during admission: both pass, so post again.\n while (\n response.status === 409 &&\n 'code' in response.data &&\n (response.data.code === 'apply-in-progress' || response.data.code === 'admission-conflict') &&\n Date.now() < deadline\n ) {\n print(\n response.data.code === 'apply-in-progress'\n ? `Apply r${(response.data as ApplyingHead).revisionId} in progress; retry shortly.`\n : `The head changed while plan p${planId} was being admitted; retry shortly.`,\n );\n await pause();\n response = await post();\n }\n if ('code' in response.data && response.data.code === 'admission-conflict') {\n // Nothing was admitted; the guard is cleared once the server confirms no attempt exists.\n await releaseIfAbsent();\n print(`The head kept changing while plan p${planId} was being admitted. Retry: farseer code apply p${planId}`);\n process.exitCode = 1;\n return;\n }\n while (response.status === 202 && Date.now() < deadline) {\n const pending = response.data as Pending;\n updateDraft(root, planId, (current) => {\n current.revisionId = pending.revisionId;\n delete current.unanswered;\n });\n print(`Pending r${pending.revisionId}; waiting for attempt receipt.`);\n await pause();\n // v1 has no background finalizer: an idempotent POST consumes new engine results and resumes stages.\n response = await post();\n }\n if ('code' in response.data && response.data.code === 'plan-expired') {\n // Expiry raced GET/POST. The server proves no attempt was admitted: clear only\n // the durable pre-POST guard, without consuming a receipt or altering model/baseline data.\n updateDraft(root, planId, (current) => {\n current.applying = false;\n delete current.unanswered;\n });\n reportExpired(response.data.expiresAt);\n return;\n }\n if (response.status === 202 || response.status === 409) {\n // The server answered: an attempt holds this plan (202), or another apply holds the head (409).\n const answered = response.data as Pending | ApplyingHead;\n updateDraft(root, planId, (current) => {\n if (response.status === 202) current.revisionId = answered.revisionId;\n delete current.unanswered;\n });\n print(\n `Revision r${answered.revisionId} is ${response.status === 202 ? 'pending' : 'applying'}. Resume: farseer code apply p${planId}`,\n );\n process.exitCode = 1;\n return;\n }\n if (response.status !== 200) {\n await releaseIfAbsent();\n throw new Error(`Apply failed (HTTP ${response.status})`);\n }\n const receipt = response.data as Receipt;\n storeReceipt(root, planId, receipt);\n let head: Head | undefined;\n try {\n head = await readHead(api, deadline, print);\n } catch (error) {\n print(\n `Post-apply readback unavailable: ${(error as Error).message}; the next farseer code pull writes the receipt`,\n );\n }\n renderReceipt(receipt, storedPlan.operations).forEach((line) => print(line));\n const notices = head ? await materializeReceipt(api, root, planId, head, print) : [];\n print(`Tenant '${workspace.target.tenant}' now at r${receipt.revisionId} (${receipt.status})`);\n if (!head || layoutExitCode(notices, receipt.status)) process.exitCode = 1;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AAGpB,iBAA6C;AAC7C,wBAAqE;AACrE,uBAAgE;AAChE,2BAAoG;AACpG,wBAAsC;AACtC,yBAA6B;AAC7B,4BAMO;AACP,2BAMO;AACP,wBAAiF;AACjF,oBAAyE;AAazE,uBAA4E;AAC5E,2BAAkC;AAClC,2BAAwD;AAUxD,MAAM,QAAQ,MAAM,IAAI,QAAc,CAAC,YAAY,WAAW,SAAS,GAAI,CAAC;AACrE,SAAS,YAAY,OAAuB;AAC/C,QAAM,UAAU,OAAO,KAAK;AAC5B,MAAI,CAAC,OAAO,SAAS,OAAO,KAAK,UAAU,KAAK,UAAU;AACtD,UAAM,IAAI,MAAM,2CAA2C;AAC/D,SAAO;AACX;AACA,SAAS,UAAU,MAAqB;AACpC,MAAI,CAAC,GAAG,eAAW,gCAAc,MAAM,2BAAU,CAAC;AAC9C,UAAM,IAAI,MAAM,8DAA8D;AAClF,aAAO,iCAAW,6BAAU,IAAI,CAAC;AACrC;AAOA,SAAS,YAAY,MAAc,QA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.ts"],
|
|
4
|
-
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport { createHash, randomUUID } from 'crypto';\nimport { Transform } from 'stream';\nimport { pipeline } from 'stream/promises';\nimport { parseState, serializeState } from './documents';\nimport { byteHashesChanged, persistableByteHashes } from './byteHashes';\nimport { BlobContent, State } from './types';\nimport { hashFile, sameBytes, type BlobApi } from './binaryDisk';\nimport { STATE_FILE } from './workspaceRoot';\n\nexport { STATE_DIR, STATE_FILE } from './workspaceRoot';\nfunction rejectSymlink(file: string): void {\n try {\n if (fs.lstatSync(file).isSymbolicLink()) throw new Error(`Refusing symlink: ${file}`);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n}\nexport function workspacePath(root: string, relative: string): string {\n if (\n relative.includes('\\\\') ||\n [...relative].some((character) => character.charCodeAt(0) < 0x20) ||\n relative.split('/').some((part) => !part || part === '.' || part === '..')\n )\n throw new Error(`Unsafe workspace path: ${JSON.stringify(relative)}`);\n const resolved = path.resolve(root, relative);\n const rel = path.relative(path.resolve(root), resolved);\n if (rel.startsWith('..') || path.isAbsolute(rel)) throw new Error('Workspace path escapes tenant directory');\n let current = path.resolve(root);\n rejectSymlink(current);\n for (const part of rel.split(path.sep)) {\n current = path.join(current, part);\n rejectSymlink(current);\n }\n return resolved;\n}\ninterface OwnedTemporary {\n path: string;\n dev: number;\n ino: number;\n}\n\nfunction removeOwnedTemporary(temporary: OwnedTemporary | undefined): void {\n if (!temporary) return;\n try {\n const stat = fs.lstatSync(temporary.path);\n if (stat.dev === temporary.dev && stat.ino === temporary.ino) fs.unlinkSync(temporary.path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n}\n\nfunction assertOwnedTemporary(temporary: OwnedTemporary | undefined): asserts temporary is OwnedTemporary {\n if (!temporary) throw new Error('Temporary file is no longer owned');\n const stat = fs.lstatSync(temporary.path);\n if (stat.dev !== temporary.dev || stat.ino !== temporary.ino)\n throw new Error(`Temporary file changed before replacement: ${temporary.path}`);\n}\n\n/**\n * The permission bits of the regular file a replacement takes the place of, so a committed\n * executable bit survives a pull. A new file keeps the writer's own 0600.\n */\nfunction existingMode(file: string): number | undefined {\n try {\n const stat = fs.lstatSync(file);\n return stat.isFile() ? stat.mode & 0o777 : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Atomically replace one text file without creating its parent directory. It keeps the file's mode. */\nexport function atomicReplaceText(file: string, content: string): void {\n const temporary = `${file}.tmp-${randomUUID()}`;\n let descriptor: number | undefined;\n let owned: OwnedTemporary | undefined;\n try {\n descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);\n const stat = fs.fstatSync(descriptor);\n owned = { path: temporary, dev: stat.dev, ino: stat.ino };\n const mode = existingMode(file);\n if (mode !== undefined) fs.fchmodSync(descriptor, mode);\n fs.writeFileSync(descriptor, content, { encoding: 'utf8' });\n fs.closeSync(descriptor);\n descriptor = undefined;\n assertOwnedTemporary(owned);\n fs.renameSync(temporary, file);\n owned = undefined;\n } finally {\n try {\n if (descriptor !== undefined) fs.closeSync(descriptor);\n } finally {\n removeOwnedTemporary(owned);\n }\n }\n}\n\nfunction atomicWrite(file: string, content: string): void {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n atomicReplaceText(file, content);\n}\n\nexport interface StagedWorkspaceFile {\n destination: string;\n temporary: string;\n commit(destination: string): void;\n cleanup(): void;\n}\n\n/**\n * Write one text file into a destination-local temporary without replacing its destination. The\n * caller commits it later with a single rename, so nothing but that rename stands between this\n * file and another the same commit has to keep it beside.\n */\nexport function stageText(destination: string, content: string): StagedWorkspaceFile {\n const temporary = `${destination}.tmp-${randomUUID()}`;\n let descriptor: number | undefined;\n let owned: OwnedTemporary | undefined;\n try {\n descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);\n const stat = fs.fstatSync(descriptor);\n owned = { path: temporary, dev: stat.dev, ino: stat.ino };\n const mode = existingMode(destination);\n if (mode !== undefined) fs.fchmodSync(descriptor, mode);\n fs.writeFileSync(descriptor, content, { encoding: 'utf8' });\n fs.closeSync(descriptor);\n descriptor = undefined;\n } catch (error) {\n try {\n if (descriptor !== undefined) fs.closeSync(descriptor);\n } finally {\n removeOwnedTemporary(owned);\n }\n throw error;\n }\n return {\n destination,\n temporary,\n commit(checkedDestination) {\n if (checkedDestination !== destination)\n throw new Error(`Staged destination changed before replacement: ${destination}`);\n assertOwnedTemporary(owned);\n fs.renameSync(temporary, checkedDestination);\n owned = undefined;\n },\n cleanup() {\n removeOwnedTemporary(owned);\n owned = undefined;\n },\n };\n}\n\n/** Copy and verify one destination-local temporary without replacing its destination. */\nexport function stageVerifiedFile(\n source: string,\n destination: string,\n content: BlobContent,\n label = destination,\n): StagedWorkspaceFile {\n const temporary = `${destination}.tmp-${randomUUID()}`;\n let input: number | undefined;\n let output: number | undefined;\n let owned: OwnedTemporary | undefined;\n try {\n input = fs.openSync(source, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);\n const sourceStat = fs.fstatSync(input);\n if (!sourceStat.isFile()) throw new Error(`Expected regular file: ${source}`);\n output = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);\n const stat = fs.fstatSync(output);\n owned = { path: temporary, dev: stat.dev, ino: stat.ino };\n const buffer = Buffer.allocUnsafe(1024 * 1024);\n let length: number;\n while ((length = fs.readSync(input, buffer, 0, buffer.length, null)) > 0) {\n let offset = 0;\n while (offset < length) offset += fs.writeSync(output, buffer, offset, length - offset);\n }\n fs.closeSync(input);\n input = undefined;\n if (!sameBytes(hashFile(temporary), content)) throw new Error(`Byte source changed while staging: ${label}`);\n assertOwnedTemporary(owned);\n fs.fchmodSync(output, existingMode(destination) ?? sourceStat.mode & 0o777);\n fs.closeSync(output);\n output = undefined;\n } catch (error) {\n try {\n if (input !== undefined) fs.closeSync(input);\n } finally {\n try {\n if (output !== undefined) fs.closeSync(output);\n } finally {\n removeOwnedTemporary(owned);\n }\n }\n throw error;\n }\n return {\n destination,\n temporary,\n commit(checkedDestination) {\n if (checkedDestination !== destination)\n throw new Error(`Staged destination changed before replacement: ${destination}`);\n assertOwnedTemporary(owned);\n fs.renameSync(temporary, checkedDestination);\n owned = undefined;\n },\n cleanup() {\n removeOwnedTemporary(owned);\n owned = undefined;\n },\n };\n}\n\n/**\n * Stream one blob from the server into a destination-local temporary and verify its size and hash\n * on the way, without replacing the destination. Nothing goes through `os.tmpdir()`: a large tenant\n * would otherwise hold every missing blob there at once, in memory where `/tmp` is a tmpfs.\n * `onStaging` receives a function that stops the stream and removes the partial temporary as soon\n * as the temporary exists, so a Ctrl-C during the stream leaves nothing behind.\n */\nexport async function stageDownloadedFile(\n api: Pick<BlobApi, 'downloadBlob'>,\n destination: string,\n content: BlobContent,\n onStaging?: (abandon: () => void) => void,\n): Promise<StagedWorkspaceFile> {\n const temporary = `${destination}.tmp-${randomUUID()}`;\n let owned: OwnedTemporary | undefined;\n let descriptor: number | undefined;\n let stream: Awaited<ReturnType<BlobApi['downloadBlob']>> | undefined;\n try {\n stream = await api.downloadBlob(content.sha256);\n descriptor = fs.openSync(temporary, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);\n const stat = fs.fstatSync(descriptor);\n owned = { path: temporary, dev: stat.dev, ino: stat.ino };\n const mode = existingMode(destination);\n if (mode !== undefined) fs.fchmodSync(descriptor, mode);\n const output = fs.createWriteStream(temporary, { fd: descriptor, autoClose: true });\n descriptor = undefined;\n const hash = createHash('sha256');\n let size = 0;\n const source = stream;\n stream = undefined;\n onStaging?.(() => {\n source.destroy();\n output.destroy();\n removeOwnedTemporary(owned);\n });\n await pipeline(\n source,\n new Transform({\n transform(chunk: Buffer, _encoding, done) {\n size += chunk.length;\n if (size > content.size) {\n done(new Error('Blob download exceeds its declared size'));\n return;\n }\n hash.update(chunk);\n done(null, chunk);\n },\n }),\n output,\n );\n if (size !== content.size || hash.digest('hex') !== content.sha256)\n throw new Error('Blob download hash/size mismatch');\n assertOwnedTemporary(owned);\n } catch (error) {\n try {\n if (stream && !stream.destroyed) stream.destroy();\n if (descriptor !== undefined) fs.closeSync(descriptor);\n } finally {\n removeOwnedTemporary(owned);\n }\n throw error;\n }\n return {\n destination,\n temporary,\n commit(checkedDestination) {\n if (checkedDestination !== destination)\n throw new Error(`Staged destination changed before replacement: ${destination}`);\n assertOwnedTemporary(owned);\n fs.renameSync(temporary, checkedDestination);\n owned = undefined;\n },\n cleanup() {\n removeOwnedTemporary(owned);\n owned = undefined;\n },\n };\n}\n\n/** Write the state, carrying the byte-hash cache this command holds for the workspace. */\nexport function saveState(root: string, state: State): void {\n atomicWrite(workspacePath(root, STATE_FILE), serializeState(withByteHashes(root, state)));\n}\n\nfunction withByteHashes(root: string, state: State): State {\n if (!state.layout) return state;\n const byteHashes = persistableByteHashes(root, state.layout.byteHashes);\n const layout = { ...state.layout };\n if (byteHashes) layout.byteHashes = byteHashes;\n else delete layout.byteHashes;\n return { ...state, layout };\n}\n\n/**\n * Save only the byte-hash cache a read-only command learned, when the state on disk is still the\n * text the command read. The new text is built first, so the file is compared and replaced in one\n * short step: any other change to the state wins, and the cache is simply rebuilt later.\n */\nexport function saveLearnedByteHashes(root: string, expectedStateText: string): void {\n if (!byteHashesChanged(root)) return;\n const file = workspacePath(root, STATE_FILE);\n const next = serializeState(withByteHashes(root, parseState(expectedStateText)));\n if (next === expectedStateText || fs.readFileSync(file, 'utf8') !== expectedStateText) return;\n atomicWrite(file, next);\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,oBAAuC;AACvC,oBAA0B;AAC1B,sBAAyB;AACzB,uBAA2C;AAC3C,wBAAyD;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,KAAK;AAAA,IAC9B;AACA,UAAM;AAAA,EACV;AACA,SAAO;AAAA,IACH;AAAA,IACA;AAAA,IACA,OAAO,oBAAoB;AACvB,UAAI,uBAAuB;AACvB,cAAM,IAAI,MAAM,kDAAkD,WAAW,EAAE;AACnF,2BAAqB,KAAK;AAC1B,SAAG,WAAW,WAAW,kBAAkB;AAC3C,cAAQ;AAAA,IACZ;AAAA,IACA,UAAU;AACN,2BAAqB,KAAK;AAC1B,cAAQ;AAAA,IACZ;AAAA,EACJ;AACJ;AAGO,SAAS,UAAU,MAAc,OAAoB;AACxD,cAAY,cAAc,MAAM,+BAAU,OAAG,iCAAe,eAAe,MAAM,KAAK,CAAC,CAAC;AAC5F;AAEA,SAAS,eAAe,MAAc,OAAqB;AACvD,MAAI,CAAC,MAAM,OAAQ,QAAO;AAC1B,QAAM,iBAAa,yCAAsB,MAAM,MAAM,OAAO,UAAU;AACtE,QAAM,SAAS,EAAE,GAAG,MAAM,OAAO;AACjC,MAAI,WAAY,QAAO,aAAa;AAAA,MAC/B,QAAO,OAAO;AACnB,SAAO,EAAE,GAAG,OAAO,OAAO;AAC9B;AAOO,SAAS,sBAAsB,MAAc,mBAAiC;AACjF,MAAI,KAAC,qCAAkB,IAAI,EAAG;AAC9B,QAAM,OAAO,cAAc,MAAM,+BAAU;AAC3C,QAAM,WAAO,iCAAe,eAAe,UAAM,6BAAW,iBAAiB,CAAC,CAAC;AAC/E,MAAI,SAAS,qBAAqB,GAAG,aAAa,MAAM,MAAM,MAAM,kBAAmB;AACvF,cAAY,MAAM,IAAI;AAC1B;",
|
|
6
5
|
"names": ["import_workspaceRoot"]
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/services/codefirst/workspaceLock.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * One `farseer code` command per workspace at a time, enforced with `.fscode/lock`, as git does with\n * `index.lock`. Two commands in one workspace would each save `state.json` over the other's save,\n * and the loser's final-save check fails after its files are written.\n *\n * The lock is its own file because the writer replaces `state.json` by a temporary file and a\n * rename, which would drop a lock held on it. Node has no portable OS file lock, so the lock is an\n * exclusive create (`wx`, atomic on every platform) holding `{ pid, hostname, command, startedAt }`.\n * A lock whose holder ran on this host and whose pid no longer exists is stale and taken over; any\n * other lock refuses the command and names its holder, because a live pid may be a reused one and a\n * pid from another host (a shared drive) cannot be checked. Staleness never reads mtimes: the writer\n * runs synchronously for long stretches and could not refresh one.\n *\n * The lock is released when the command ends, when it throws, and on every `process.exit`, through\n * an `exit` listener. Ctrl-C reaches `exit` too: the lock installs the writer's SIGINT listener\n * (`exitAfterWrites`), which exits only after the synchronous writes, so a command interrupted\n * before its writes also releases the lock instead of being killed by Node's default handler.\n */\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport { exitAfterWrites } from './layoutReceipt';\nimport { STATE_DIR } from './workspaceRoot';\n\nexport const LOCK_FILE = `${STATE_DIR}/lock`;\n\ninterface LockHolder {\n pid: number;\n hostname: string;\n command: string;\n startedAt: string;\n}\n\nconst deleteAdvice = `If no such command is running, delete ${LOCK_FILE}.`;\n\nfunction lockPath(root: string): string {\n return path.join(root, ...LOCK_FILE.split('/'));\n}\n\nfunction readLock(file: string): { text: string; holder?: LockHolder } | undefined {\n let text: string;\n try {\n text = fs.readFileSync(file, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n return { text: '' };\n }\n try {\n const value = JSON.parse(text) as Partial<LockHolder>;\n const valid =\n Number.isSafeInteger(value.pid) &&\n (value.pid as number) > 0 &&\n typeof value.hostname === 'string' &&\n typeof value.command === 'string' &&\n typeof value.startedAt === 'string' &&\n !Number.isNaN(Date.parse(value.startedAt));\n return { text, holder: valid ? (value as LockHolder) : undefined };\n } catch {\n return { text };\n }\n}\n\n/** Whether `pid` names a running process. Only `ESRCH` proves it gone; `EPERM` means it exists. */\nfunction running(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code !== 'ESRCH';\n }\n}\n\nfunction startedLabel(startedAt: string): string {\n const started = new Date(startedAt);\n const pad = (value: number) => String(value).padStart(2, '0');\n const time = `${pad(started.getHours())}:${pad(started.getMinutes())}`;\n if (started.toDateString() === new Date().toDateString()) return time;\n return `${started.getFullYear()}-${pad(started.getMonth() + 1)}-${pad(started.getDate())} ${time}`;\n}\n\nfunction refusal(holder: LockHolder | undefined): Error {\n if (!holder)\n return new Error(\n `The workspace lock ${LOCK_FILE} cannot be read, so another farseer code command may be running ` +\n `in this workspace. ${deleteAdvice}`,\n );\n const host = holder.hostname === os.hostname() ? '' : ` on ${holder.hostname}`;\n return new Error(\n `Another farseer code command is running in this workspace: ${holder.command}, pid ${holder.pid}${host}, ` +\n `started ${startedLabel(holder.startedAt)}. ${deleteAdvice}`,\n );\n}\n\n/** Create the lock file with `content`; false when it already exists. */\nfunction create(file: string, content: string): boolean {\n let descriptor: number;\n try {\n descriptor = fs.openSync(file, 'wx');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false;\n throw error;\n }\n try {\n fs.writeSync(descriptor, content);\n } catch (error) {\n fs.closeSync(descriptor);\n fs.rmSync(file, { force: true });\n throw error;\n }\n fs.closeSync(descriptor);\n return true;\n}\n\n/**\n * Take the workspace lock for `command` (as the user typed it, e.g. `code pull`) or throw the\n * refusal. Returns the release, which removes the lock only while it still holds this command's\n * content and is safe to call more than once.\n */\nexport function acquireWorkspaceLock(root: string, command: string): () => void {\n const file = lockPath(root);\n const content = JSON.stringify({\n pid: process.pid,\n hostname: os.hostname(),\n command,\n startedAt: new Date().toISOString(),\n } satisfies LockHolder);\n if (!create(file, content)) {\n const found = readLock(file);\n const stale = found?.holder && found.holder.hostname === os.hostname() && !running(found.holder.pid);\n if (found && !stale) throw refusal(found.holder);\n // Removed only while it is still the stale lock just read; a lost race below is refused.\n if (found && readLock(file)?.text === found.text) fs.rmSync(file, { force: true });\n if (!create(file, content)) throw refusal(readLock(file)?.holder);\n }\n let held = true;\n const release = () => {\n if (!held) return;\n held = false;\n process.removeListener('exit', release);\n try {\n if (fs.readFileSync(file, 'utf8') === content) fs.unlinkSync(file);\n } catch {\n // Already gone, or unreadable: the next command names it if it is still there.\n }\n };\n process.on('exit', release);\n if (!process.listeners('SIGINT').includes(exitAfterWrites)) process.on('SIGINT', exitAfterWrites);\n return release;\n}\n\n/** Run `action` holding the workspace lock, and release it however the action ends. */\nexport async function withWorkspaceLock<T>(root: string, command: string, action: () => Promise<T>): Promise<T> {\n const release = acquireWorkspaceLock(root, command);\n try {\n return await action();\n } finally {\n release();\n }\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkBA,SAAoB;AACpB,SAAoB;AACpB,WAAsB;AACtB,2BAAgC;AAChC,2BAA0B;AAEnB,MAAM,YAAY,GAAG,8BAAS;AASrC,MAAM,eAAe,yCAAyC,SAAS;AAEvE,SAAS,SAAS,MAAsB;AACpC,SAAO,KAAK,KAAK,MAAM,GAAG,UAAU,MAAM,GAAG,CAAC;AAClD;AAEA,SAAS,SAAS,MAAiE;AAC/E,MAAI;AACJ,MAAI;AACA,WAAO,GAAG,aAAa,MAAM,MAAM;AAAA,EACvC,SAAS,OAAO;AACZ,QAAK,MAAgC,SAAS,SAAU,QAAO;AAC/D,WAAO,EAAE,MAAM,GAAG;AAAA,EACtB;AACA,MAAI;AACA,UAAM,QAAQ,KAAK,MAAM,IAAI;AAC7B,UAAM,QACF,OAAO,cAAc,MAAM,GAAG,KAC7B,MAAM,MAAiB,KACxB,OAAO,MAAM,aAAa,YAC1B,OAAO,MAAM,YAAY,YACzB,OAAO,MAAM,cAAc,YAC3B,CAAC,OAAO,MAAM,KAAK,MAAM,MAAM,SAAS,CAAC;AAC7C,WAAO,EAAE,MAAM,QAAQ,QAAS,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O,MAAM,OAAO;AAAA,EACxB,UAAE;AACE,YAAQ;AAAA,EACZ;AACJ;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -101,7 +101,8 @@ function resolveCodeWorkspace(cwd) {
|
|
|
101
101
|
}
|
|
102
102
|
rejectSymlink(path.join(root, STATE_DIR));
|
|
103
103
|
rejectSymlink(stateFile(root));
|
|
104
|
-
|
|
104
|
+
const { tenant, organisation, baseUrl } = (0, import_documents.peekState)(fs.readFileSync(stateFile(root), "utf8"));
|
|
105
|
+
return { root, state: { tenant, organisation, baseUrl } };
|
|
105
106
|
}
|
|
106
107
|
function assertPortableTenant(tenant) {
|
|
107
108
|
const control = [...tenant].some((character) => (character.codePointAt(0) ?? 0) < 32);
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/services/codefirst/workspaceRoot.ts"],
|
|
4
|
-
"
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,SAAoB;AACpB,WAAsB;AACtB,uBAAuD;AAGhD,MAAM,YAAY;AAClB,MAAM,aAAa,GAAG,SAAS;AAE/B,MAAM,kBAAkB;AACxB,MAAM,sBACT;AAAA;AAAA,EAEG,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAST,MAAM,oBAAoB;AAE1B,MAAM,yBAAyB;AAC/B,MAAM,sBACT,6HAC2D,sBAAsB;AAQrF,SAAS,UAAU,MAAsB;AACrC,SAAO,KAAK,KAAK,MAAM,GAAG,WAAW,MAAM,GAAG,CAAC;AACnD;AAEA,SAAS,cAAc,QAAsB;AACzC,MAAI;AACA,QAAI,GAAG,UAAU,MAAM,EAAE,eAAe,EAAG,OAAM,IAAI,MAAM,qBAAqB,MAAM,EAAE;AAAA,EA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AAG,KAAK,CAAC,CAAC,GAAG,MAAM;AACzF,KAAG,cAAc,KAAK,KAAK,MAAM,YAAY,GAAG,qBAAqB,MAAM;AAC3E,SAAO;AACX;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/configService.ts"],
|
|
4
|
-
"sourcesContent": ["import * as fs from 'fs';\nimport * as path from 'path';\nimport * as os from 'os';\n\nexport interface ApiKeyCredential {\n type: 'apiKey';\n tenantId: string;\n apiKey: string;\n basePath: string;\n}\n\nexport interface UserAuth {\n accessToken: string;\n refreshToken: string;\n expiresAt: string;\n tenant?: string; // Tenant used for login (Keycloak client ID)\n realm?: string; // Keycloak realm (default: master)\n}\n\nexport const DEFAULT_REALM = 'master';\n\n// The backend issues agent sandbox turns short-lived API keys with this prefix.\nexport const AGENT_API_KEY_PREFIX = 'agent1.';\n\n// Resolved { org, tenant } pair. No longer persisted as a machine-global\n// default (that made it impossible to work on two tenants in two shells and\n// silently retargeted bare commands). It survives only as the shape the MCP\n// per-process pin and the CLI's env-based resolution both pass around.\nexport interface CurrentCheckout {\n organisation: string; // For URL: https://<organisation>.farseer.io\n tenant: string; // For X-TENANT-ID header\n}\n\nexport interface SyncIncludes {\n extensions?: string[];\n folders?: string[];\n}\n\nexport interface FarseerConfig {\n credentials: Record<string, ApiKeyCredential>;\n // One browser login per Keycloak realm: a token only works at organisations\n // whose tenants live in the realm that issued it.\n userAuths?: Record<string, UserAuth>;\n // The last login made, kept current through its refreshes, for CLIs from\n // before `userAuths` that share this file.\n userAuth?: UserAuth;\n organisationRealms?: Record<string, string>; // Organisation -> Keycloak realm\n tenantOrgMapping?: Record<string, string>; // Tenant -> Organisation mapping\n syncIncludes?: Record<string, SyncIncludes>; // Per-tenant sync includes\n}\n\nconst CONFIG_DIR = path.join(os.homedir(), '.farseer');\nconst CONFIG_FILE = path.join(CONFIG_DIR, 'config.json');\n\nfunction ensureConfigDir(): void {\n if (!fs.existsSync(CONFIG_DIR)) {\n fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });\n }\n}\n\nfunction getDefaultConfig(): FarseerConfig {\n return {\n credentials: {},\n };\n}\n\n/**\n * `userAuth` is either the mirror of a login in `userAuths` or one an older CLI\n * wrote since \u2014 never older \u2014 so it wins for its realm.\n */\nfunction mergeLegacyUserAuth(config: FarseerConfig): FarseerConfig {\n if (config.userAuth) {\n const realm = config.userAuth.realm || DEFAULT_REALM;\n config.userAuths = { ...config.userAuths, [realm]: { ...config.userAuth, realm } };\n }\n return config;\n}\n\nexport function loadConfig(): FarseerConfig {\n ensureConfigDir();\n\n if (!fs.existsSync(CONFIG_FILE)) {\n return getDefaultConfig();\n }\n\n try {\n const content = fs.readFileSync(CONFIG_FILE, 'utf-8');\n return mergeLegacyUserAuth(JSON.parse(content) as FarseerConfig);\n } catch {\n return getDefaultConfig();\n }\n}\n\n/**\n * This file holds every stored API key plus the Keycloak refresh and access\n * tokens, so it is owner-only. `mode` on writeFileSync applies to a file being\n * created, not an existing one, and the token refresh rewrites this file from\n * every request \u2014 so an existing 0644 file is corrected explicitly rather than\n * staying world-readable for the life of the install.\n */\nexport function saveConfig(config: FarseerConfig): void {\n ensureConfigDir();\n fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), { encoding: 'utf-8', mode: 0o600 });\n try {\n fs.chmodSync(CONFIG_FILE, 0o600);\n } catch {\n // A filesystem that will not take a mode (a Windows volume, a mounted\n // share) is not a reason to fail the write the caller asked for.\n }\n}\n\nexport function getCredential(tenant: string): ApiKeyCredential | undefined {\n const environment = environmentCredential();\n if (environment) {\n if (tenant !== environment.tenantId) throw new Error('Environment credentials are bound to another tenant');\n return environment;\n }\n const config = loadConfig();\n const credential = config.credentials[tenant];\n return credential && process.env.FARSEER_API_URL\n ? { ...credential, basePath: process.env.FARSEER_API_URL.replace(/\\/+$/, '') }\n : credential;\n}\n\nexport function setCredential(tenant: string, credential: ApiKeyCredential): void {\n const config = loadConfig();\n config.credentials[tenant] = credential;\n saveConfig(config);\n}\n\nexport function removeCredential(tenant: string): boolean {\n const config = loadConfig();\n if (config.credentials[tenant]) {\n delete config.credentials[tenant];\n saveConfig(config);\n return true;\n }\n return false;\n}\n\nexport function listCredentials(): Record<string, ApiKeyCredential> {\n const environment = environmentCredential();\n if (environment) return { [environment.tenantId]: environment };\n const config = loadConfig();\n return config.credentials;\n}\n\nexport function getUserAuth(realm: string = DEFAULT_REALM): UserAuth | undefined {\n if (environmentCredential()) return undefined;\n return loadConfig().userAuths?.[realm];\n}\n\n/** Every browser login, keyed by realm. */\nexport function listUserAuths(): Record<string, UserAuth> {\n if (environmentCredential()) return {};\n return loadConfig().userAuths ?? {};\n}\n\n/**\n * A refresh moves the legacy mirror only when it already holds that realm, or\n * an older CLI would follow whichever realm refreshed last and send its token to\n * the wrong organisations. It must still move then: left behind, it would win\n * over the newer token on the next load.\n */\nexport function setUserAuth(auth: UserAuth, { refresh = false }: { refresh?: boolean } = {}): void {\n const config = loadConfig();\n const realm = auth.realm || DEFAULT_REALM;\n config.userAuths = { ...config.userAuths, [realm]: { ...auth, realm } };\n if (!refresh || (config.userAuth?.realm || DEFAULT_REALM) === realm) {\n config.userAuth = config.userAuths[realm];\n }\n saveConfig(config);\n}\n\n/** One realm's login, or every login when no realm is given. */\nexport function clearUserAuth(realm?: string): void {\n const config = loadConfig();\n if (realm === undefined) {\n delete config.userAuths;\n } else if (config.userAuths) {\n delete config.userAuths[realm];\n }\n if (realm === undefined || (config.userAuth?.realm || DEFAULT_REALM) === realm) {\n delete config.userAuth;\n }\n saveConfig(config);\n}\n\nexport function getOrganisationRealm(organisation: string): string | undefined {\n return loadConfig().organisationRealms?.[organisation];\n}\n\n/**\n * Remembers the realm an organisation's tenants live in. Not while `FARSEER_API_URL` overrides the\n * host: the realm then comes from the override's server, and saving it under the organisation's\n * name would make the real organisation use it after the variable is unset.\n */\nexport function saveOrganisationRealm(organisation: string, realm: string): void {\n if (process.env.FARSEER_API_URL) return;\n const config = loadConfig();\n config.organisationRealms = { ...config.organisationRealms, [organisation]: realm };\n saveConfig(config);\n}\n\n/**\n * Pass `auth` when you already have it. The middleware asks this on every\n * request and re-reading the config file to answer it means a second\n * existsSync + readFileSync + JSON.parse per call.\n */\nexport function isUserAuthValid(auth: UserAuth | undefined = getUserAuth()): boolean {\n if (!auth) return false;\n\n const expiresAt = new Date(auth.expiresAt);\n // Add 10 second buffer to proactively refresh before actual expiry\n // Note: Keycloak tokens typically last 60 seconds, so buffer must be small\n const bufferMs = 10 * 1000;\n return expiresAt.getTime() > Date.now() + bufferMs;\n}\n\n/** The organisation's API URL, as a saved credential stores it; `FARSEER_API_URL` never reaches it. */\nexport function storedBasePath(organisation: string): string {\n return `https://${organisation}.farseer.io/api/v3`;\n}\n\n/** The API URL a request uses: `FARSEER_API_URL` when set, else the organisation's. */\nexport function generateBasePath(organisation: string): string {\n return process.env.FARSEER_API_URL?.replace(/\\/+$/, '') || storedBasePath(organisation);\n}\n\n// There is deliberately no persisted \"current tenant\" any more. A command's\n// target comes from an explicit argument or the FARSEER_TENANT env var (see\n// getEnvCheckout in utils/helpers.ts), and the CLI errors if neither is set\n// rather than falling back to a machine-global default. The tenant->org\n// mapping below is kept: it lets `export FARSEER_TENANT=<tenant>` resolve the\n// org on its own, so only new org != tenant tenants need FARSEER_ORG too.\n\n// Tenant-Organisation mapping\nexport function saveTenantOrgMapping(tenant: string, organisation: string): void {\n const config = loadConfig();\n if (!config.tenantOrgMapping) {\n config.tenantOrgMapping = {};\n }\n config.tenantOrgMapping[tenant] = organisation;\n saveConfig(config);\n}\n\nexport function getTenantOrg(tenant: string): string | undefined {\n const config = loadConfig();\n return config.tenantOrgMapping?.[tenant];\n}\n\n// Sync includes management\nexport function getSyncIncludes(tenant: string): SyncIncludes | null {\n const config = loadConfig();\n return config.syncIncludes?.[tenant] ?? null;\n}\n\nexport function setSyncIncludes(tenant: string, includes: SyncIncludes): void {\n const config = loadConfig();\n if (!config.syncIncludes) {\n config.syncIncludes = {};\n }\n // Clean up empty arrays\n if (includes.extensions?.length === 0) delete includes.extensions;\n if (includes.folders?.length === 0) delete includes.folders;\n // Remove entry entirely if empty\n if (!includes.extensions && !includes.folders) {\n delete config.syncIncludes[tenant];\n } else {\n config.syncIncludes[tenant] = includes;\n }\n // Remove syncIncludes key if no tenants left\n if (Object.keys(config.syncIncludes).length === 0) {\n delete config.syncIncludes;\n }\n saveConfig(config);\n}\n\n/**\n * Non-persistent credentials for an agent sandbox turn, which passes an agent key with\n * the backend URL and tenant. App scripts, the SDK and the data-export guide export the\n * same names with ordinary keys, so only an agent key overrides the saved logins.\n */\nexport function environmentCredential(): ApiKeyCredential | undefined {\n const { FARSEER_API_KEY: apiKey, FARSEER_URL: url, FARSEER_TENANT: tenantId } = process.env;\n if (!apiKey?.startsWith(AGENT_API_KEY_PREFIX)) return undefined;\n if (!url || !tenantId) throw new Error('Set FARSEER_API_KEY, FARSEER_URL and FARSEER_TENANT together');\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error('FARSEER_URL must be an HTTP(S) backend URL');\n }\n if (\n !['http:', 'https:'].includes(parsed.protocol) ||\n parsed.username ||\n parsed.password ||\n parsed.search ||\n parsed.hash\n )\n throw new Error('FARSEER_URL must be an HTTP(S) backend URL without credentials or query parameters');\n const base = parsed.toString().replace(/\\/+$/, '');\n return { type: 'apiKey', tenantId, apiKey, basePath: base.endsWith('/api/v3') ? base : base + '/api/v3' };\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAoB;AACpB,WAAsB;AACtB,SAAoB;AAiBb,MAAM,gBAAgB;AAG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S,WAAW;AAC1B,MAAI,CAAC,OAAO,cAAc;AACtB,WAAO,eAAe,CAAC;AAAA,EAC3B;AAEA,MAAI,SAAS,YAAY,WAAW,EAAG,QAAO,SAAS;AACvD,MAAI,SAAS,SAAS,WAAW,EAAG,QAAO,SAAS;AAEpD,MAAI,CAAC,SAAS,cAAc,CAAC,SAAS,SAAS;AAC3C,WAAO,OAAO,aAAa,MAAM;AAAA,EACrC,OAAO;AACH,WAAO,aAAa,MAAM,IAAI;AAAA,EAClC;AAEA,MAAI,OAAO,KAAK,OAAO,YAAY,EAAE,WAAW,GAAG;AAC/C,WAAO,OAAO;AAAA,EAClB;AACA,aAAW,MAAM;AACrB;AAOO,SAAS,wBAAsD;AAClE,QAAM,EAAE,iBAAiB,QAAQ,aAAa,KAAK,gBAAgB,SAAS,IAAI,QAAQ;AACxF,MAAI,CAAC,QAAQ,WAAW,oBAAoB,EAAG,QAAO;AACtD,MAAI,CAAC,OAAO,CAAC,SAAU,OAAM,IAAI,MAAM,8DAA8D;AACrG,MAAI;AACJ,MAAI;AACA,aAAS,IAAI,IAAI,GAAG;AAAA,EACxB,QAAQ;AACJ,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAChE;AACA,MACI,CAAC,CAAC,SAAS,QAAQ,EAAE,SAAS,OAAO,QAAQ,KAC7C,OAAO,YACP,OAAO,YACP,OAAO,UACP,OAAO;AAEP,UAAM,IAAI,MAAM,oFAAoF;AACxG,QAAM,OAAO,OAAO,SAAS,EAAE,QAAQ,QAAQ,EAAE;AACjD,SAAO,EAAE,MAAM,UAAU,UAAU,QAAQ,UAAU,KAAK,SAAS,SAAS,IAAI,OAAO,OAAO,UAAU;AAC5G;",
|
|
6
5
|
"names": []
|
|
7
6
|
}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/services/credentials.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Deciding which credential a command runs on.\n *\n * A browser login is preferred when there is a usable one, a stored API key\n * otherwise. The decision is made once, as a ResolvedAuth, and the client is\n * built from that \u2014 nothing downstream re-derives it.\n */\n\nimport { FarseerService, getFreshAccessToken, type ResolvedAuth } from './farseerService';\nimport { getCredential, generateBasePath, environmentCredential } from './configService';\nimport { realmForOrganisation } from './realms';\nimport { logger } from '../utils/logger';\n\n// Defined next to the refresh it calls, re-exported where callers look for it.\nexport { getFreshAccessToken } from './farseerService';\n\n/**\n * Always the organisation that was typed. A stored key's basePath belongs to\n * that key; letting it stand in here made the host depend on whether a key\n * happened to be named after the organisation.\n */\nfunction jwtAuth(accessToken: string, organisation: string, tenant: string, realm: string): ResolvedAuth {\n return { kind: 'jwt', accessToken, basePath: generateBasePath(organisation), tenant, realm };\n}\n\nexport function buildClient(auth: ResolvedAuth): FarseerService {\n return new FarseerService(auth);\n}\n\n/** Pick by what's available. Nothing is sent, so it can't tell whether the credential works. */\nexport async function resolveAuth(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n if (environmentCredential()) return { kind: 'apiKey', credential: getCredential(tenant)! };\n const realm = await realmForOrganisation(organisation);\n const accessToken = await getFreshAccessToken(realm);\n if (accessToken) {\n return jwtAuth(accessToken, organisation, tenant, realm);\n }\n\n const credential = getCredential(tenant);\n return credential ? { kind: 'apiKey', credential } : null;\n}\n\n/**\n * Pick one that actually connects. The probe is the point: a key is the only\n * thing that still works once the organisation route is dead.\n */\nexport async function resolveAuthByProbe(organisation: string, tenant: string): Promise<ResolvedAuth | null> {\n if (environmentCredential()) return { kind: 'apiKey', credential: getCredential(tenant)! };\n const realm = await realmForOrganisation(organisation);\n const accessToken = await getFreshAccessToken(realm);\n if (accessToken) {\n const auth = jwtAuth(accessToken, organisation, tenant, realm);\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('JWT auth failed for this tenant, trying API key...');\n }\n\n const credential = getCredential(tenant);\n if (credential) {\n const auth: ResolvedAuth = { kind: 'apiKey', credential };\n if (await connects(auth)) {\n return auth;\n }\n logger.dim('API key auth failed.');\n }\n\n return null;\n}\n\n/**\n * The same decision with a fresh browser token. A CLI command lives for one\n * request; an MCP server runs for hours, so the token is the part it re-takes.\n */\nexport async function refreshAuth(auth: ResolvedAuth): Promise<ResolvedAuth | null> {\n if (auth.kind === 'apiKey') {\n return auth;\n }\n const accessToken = await getFreshAccessToken(auth.realm);\n return accessToken ? { ...auth, accessToken } : null;\n}\n\nasync function connects(auth: ResolvedAuth): Promise<boolean> {\n const connection = await buildClient(auth).checkConnection();\n if (!connection.ok && connection.reason !== 'rejected') {\n // Nothing rejected the credential. Say so here: the caller's only\n // remaining move is \"no credential worked\", which blames the wrong thing.\n logger.dim(`The credential could not be checked: ${connection.message}`);\n }\n return connection.ok;\n}\n"],
|
|
5
4
|
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQA,4BAAuE;AACvE,2BAAuE;AACvE,oBAAqC;AACrC,oBAAuB;AAGvB,IAAAA,yBAAoC;AAOpC,SAAS,QAAQ,aAAqB,cAAsB,QAAgB,OAA6B;AACrG,SAAO,EAAE,MAAM,OAAO,aAAa,cAAU,uCAAiB,YAAY,GAAG,QAAQ,MAAM;AAC/F;AAEO,SAAS,YAAY,MAAoC;AAC5D,SAAO,IAAI,qCAAe,IAAI;AAClC;AAGA,eAAsB,YAAY,cAAsB,QAA8C;AAClG,UAAI,4CAAsB,EAAG,QAAO,EAAE,MAAM,UAAU,gBAAY,oCAAc,MAAM,EAAG;AACzF,QAAM,QAAQ,UAAM,oCAAqB,YAAY;AACrD,QAAM,cAAc,UAAM,2CAAoB,KAAK;AACnD,MAAI,aAAa;AACb,WAAO,QAAQ,aAAa,cAAc,QAAQ,KAAK;AAAA,EAC3D;AAEA,QAAM,iBAAa,oCAAc,MAAM;AACvC,SAAO,aAAa,EAAE,MAAM,UAAU,WAAW,IAAI;AACzD;AAMA,eAAsB,mBAAmB,cAAsB,QAA8C;AACzG,UAAI,4CAAsB,EAAG,QAAO,EAAE,MAAM,UAAU,gBAAY,oCAAc,MAAM,EAAG;AACzF,QAAM,QAAQ,UAAM,oCAAqB,YAAY;AACrD,QAAM,cAAc,UAAM,2CAAoB,KAAK;AACnD,MAAI,aAAa;AACb,UAAM,OAAO,QAAQ,aAAa,cAAc,QAAQ,KAAK;AAC7D,QAAI,MAAM,SAAS,IAAI,GAAG;AACtB,aAAO;AAAA,IACX;AACA,yBAAO,IAAI,oDAAoD;AAAA,EACnE;AAEA,QAAM,iBAAa,oCAAc,MAAM;AACvC,MAAI,YAAY;AACZ,UAAM,OAAqB,EAAE,MAAM,UAAU,WAAW;AACxD,QAAI,MAAM,SAAS,IAAI,GAAG;AACtB,aAAO;AAAA,IACX;AACA,yBAAO,IAAI,sBAAsB;AAAA,EACrC;AAEA,SAAO;AACX;AAMA,eAAsB,YAAY,MAAkD;AAChF,MAAI,KAAK,SAAS,UAAU;AACxB,WAAO;AAAA,EACX;AACA,QAAM,cAAc,UAAM,2CAAoB,KAAK,KAAK;AACxD,SAAO,cAAc,EAAE,GAAG,MAAM,YAAY,IAAI;AACpD;AAEA,eAAe,SAAS,MAAsC;AAC1D,QAAM,aAAa,MAAM,YAAY,IAAI,EAAE,gBAAgB;AAC3D,MAAI,CAAC,WAAW,MAAM,WAAW,WAAW,YAAY;AAGpD,yBAAO,IAAI,wCAAwC,WAAW,OAAO,EAAE;AAAA,EAC3E;AACA,SAAO,WAAW;AACtB;",
|
|
6
5
|
"names": ["import_farseerService"]
|
|
7
6
|
}
|
|
@@ -120,7 +120,9 @@ class FarseerService {
|
|
|
120
120
|
return {
|
|
121
121
|
ok: false,
|
|
122
122
|
reason: failureReason(error),
|
|
123
|
-
|
|
123
|
+
// Named the way every command names a failure, so an unreachable
|
|
124
|
+
// host says why ("fetch failed (… ECONNREFUSED …)").
|
|
125
|
+
message: await (0, import_errorFormatter.formatClientError)(error)
|
|
124
126
|
};
|
|
125
127
|
}
|
|
126
128
|
}
|