minimal-forge-work-pack-sync 0.1.55 → 0.1.57
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/dist/index.js +825 -416
- package/dist/python.js +771 -0
- package/dist/repair.js +1 -1
- package/package.json +4 -1
package/dist/python.js
ADDED
|
@@ -0,0 +1,771 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// packages/cli/src/paths.ts
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { existsSync } from "node:fs";
|
|
7
|
+
function resolvePaths(home = os.homedir(), platform = process.platform, env = process.env, exists = existsSync) {
|
|
8
|
+
const pathApi = platform === "win32" ? path.win32 : path.posix;
|
|
9
|
+
const userHome = platform === "win32" ? env.USERPROFILE ?? home : home;
|
|
10
|
+
const forgeConfigRoot = env.XDG_CONFIG_HOME ?? pathApi.join(userHome, ".config");
|
|
11
|
+
const forgeDir = pathApi.join(forgeConfigRoot, "forge");
|
|
12
|
+
const rollbackDir = pathApi.join(forgeDir, "rollback");
|
|
13
|
+
const explicitOpenCodeConfig = env.OPENCODE_CONFIG;
|
|
14
|
+
const opencodeDir = explicitOpenCodeConfig ? pathApi.dirname(explicitOpenCodeConfig) : resolveOpenCodeDir(userHome, platform, env, exists, pathApi);
|
|
15
|
+
const opencodeDataDir = resolveOpenCodeDataDir(userHome, platform, env, pathApi);
|
|
16
|
+
const opencodeJsonc = pathApi.join(opencodeDir, "opencode.jsonc");
|
|
17
|
+
const opencodeJson = pathApi.join(opencodeDir, "opencode.json");
|
|
18
|
+
return {
|
|
19
|
+
forgeDir,
|
|
20
|
+
credentialsPath: pathApi.join(forgeDir, "credentials.json"),
|
|
21
|
+
envPath: pathApi.join(forgeDir, "forge.env"),
|
|
22
|
+
powershellEnvPath: pathApi.join(forgeDir, "forge.ps1"),
|
|
23
|
+
rollbackDir,
|
|
24
|
+
rollbackCapsulePath: pathApi.join(rollbackDir, "capsule.json"),
|
|
25
|
+
rollbackLifecyclePath: pathApi.join(rollbackDir, "lifecycle.json"),
|
|
26
|
+
rollbackRescuesDir: pathApi.join(rollbackDir, "rescues"),
|
|
27
|
+
opencodeDir,
|
|
28
|
+
opencodeDataDir,
|
|
29
|
+
opencodeAuthPath: pathApi.join(opencodeDataDir, "auth.json"),
|
|
30
|
+
opencodeConfigPath: explicitOpenCodeConfig ?? (exists(opencodeJsonc) ? opencodeJsonc : exists(opencodeJson) ? opencodeJson : opencodeJsonc),
|
|
31
|
+
tuiConfigPath: pathApi.join(opencodeDir, "tui.json"),
|
|
32
|
+
skillsDir: pathApi.join(opencodeDir, "skills"),
|
|
33
|
+
agentsDir: pathApi.join(opencodeDir, "agents"),
|
|
34
|
+
commandsDir: pathApi.join(opencodeDir, "commands"),
|
|
35
|
+
pluginDir: pathApi.join(opencodeDir, "plugins")
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function resolveOpenCodeDataDir(userHome, platform, env, pathApi) {
|
|
39
|
+
if (platform === "win32") return pathApi.join(userHome, ".local", "share", "opencode");
|
|
40
|
+
return pathApi.join(env.XDG_DATA_HOME ?? pathApi.join(userHome, ".local", "share"), "opencode");
|
|
41
|
+
}
|
|
42
|
+
function resolveOpenCodeDir(home, platform, env, exists, pathApi) {
|
|
43
|
+
if (env.OPENCODE_CONFIG_DIR) return env.OPENCODE_CONFIG_DIR;
|
|
44
|
+
if (platform !== "win32") return pathApi.join(env.XDG_CONFIG_HOME ?? pathApi.join(home, ".config"), "opencode");
|
|
45
|
+
return pathApi.join(home, ".config", "opencode");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// packages/cli/src/pythonReadiness.ts
|
|
49
|
+
import { execFile } from "node:child_process";
|
|
50
|
+
import { createHash, randomUUID as randomUUID3 } from "node:crypto";
|
|
51
|
+
import { readFile as readFile2, stat as stat2 } from "node:fs/promises";
|
|
52
|
+
import os2 from "node:os";
|
|
53
|
+
import path4 from "node:path";
|
|
54
|
+
import { promisify } from "node:util";
|
|
55
|
+
|
|
56
|
+
// packages/shared/src/contracts/models.ts
|
|
57
|
+
var BUILT_IN_OPENROUTER_MODELS = [
|
|
58
|
+
{
|
|
59
|
+
id: "anthropic/claude-sonnet-4-6",
|
|
60
|
+
name: "Assistente de trabalho profundo",
|
|
61
|
+
approvedByDefault: true,
|
|
62
|
+
requiredInConfig: false,
|
|
63
|
+
upstreamModel: "anthropic/claude-sonnet-4.6",
|
|
64
|
+
metadata: {
|
|
65
|
+
family: "anthropic",
|
|
66
|
+
release_date: "2026-02-17",
|
|
67
|
+
attachment: true,
|
|
68
|
+
reasoning: true,
|
|
69
|
+
temperature: true,
|
|
70
|
+
tool_call: true,
|
|
71
|
+
limit: { context: 1e6, output: 128e3 },
|
|
72
|
+
modalities: { input: ["text", "image", "pdf"], output: ["text"] }
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
id: "anthropic/claude-haiku-4-5",
|
|
77
|
+
name: "Assistente r\xE1pido",
|
|
78
|
+
approvedByDefault: true,
|
|
79
|
+
requiredInConfig: false,
|
|
80
|
+
upstreamModel: "anthropic/claude-haiku-4.5",
|
|
81
|
+
metadata: {
|
|
82
|
+
family: "anthropic",
|
|
83
|
+
release_date: "2025-10-15",
|
|
84
|
+
attachment: true,
|
|
85
|
+
reasoning: true,
|
|
86
|
+
temperature: true,
|
|
87
|
+
tool_call: true,
|
|
88
|
+
limit: { context: 2e5, output: 64e3 },
|
|
89
|
+
modalities: { input: ["text", "image", "pdf"], output: ["text"] }
|
|
90
|
+
}
|
|
91
|
+
},
|
|
92
|
+
{
|
|
93
|
+
id: "openai/gpt-5.4-mini",
|
|
94
|
+
name: "Assistente de ficheiros e ecr\xE3",
|
|
95
|
+
approvedByDefault: true,
|
|
96
|
+
requiredInConfig: false,
|
|
97
|
+
metadata: {
|
|
98
|
+
family: "gpt-mini",
|
|
99
|
+
release_date: "2026-03-17",
|
|
100
|
+
attachment: true,
|
|
101
|
+
reasoning: true,
|
|
102
|
+
temperature: false,
|
|
103
|
+
tool_call: true,
|
|
104
|
+
limit: { context: 4e5, input: 272e3, output: 128e3 },
|
|
105
|
+
modalities: { input: ["text", "image", "pdf"], output: ["text"] },
|
|
106
|
+
variants: openRouterReasoningVariants(["none", "xhigh"])
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
id: "minimax/minimax-m3",
|
|
111
|
+
name: "Assistente de pesquisa",
|
|
112
|
+
approvedByDefault: true,
|
|
113
|
+
requiredInConfig: false,
|
|
114
|
+
metadata: {
|
|
115
|
+
family: "minimax",
|
|
116
|
+
release_date: "2026-04-07",
|
|
117
|
+
attachment: true,
|
|
118
|
+
reasoning: true,
|
|
119
|
+
temperature: true,
|
|
120
|
+
tool_call: true,
|
|
121
|
+
limit: { context: 524288, output: 512e3 },
|
|
122
|
+
modalities: { input: ["text", "image", "video"], output: ["text"] }
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
id: "minimax/minimax-m2.7",
|
|
127
|
+
name: "Assistente de reda\xE7\xE3o",
|
|
128
|
+
approvedByDefault: true,
|
|
129
|
+
requiredInConfig: false,
|
|
130
|
+
metadata: {
|
|
131
|
+
family: "minimax",
|
|
132
|
+
release_date: "2026-03-18",
|
|
133
|
+
attachment: false,
|
|
134
|
+
reasoning: true,
|
|
135
|
+
temperature: true,
|
|
136
|
+
tool_call: true,
|
|
137
|
+
limit: { context: 196608, output: 196608 },
|
|
138
|
+
modalities: { input: ["text"], output: ["text"] }
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
{
|
|
142
|
+
id: "xiaomi/mimo-v2.5",
|
|
143
|
+
name: "Assistente de revis\xE3o multim\xE9dia",
|
|
144
|
+
approvedByDefault: true,
|
|
145
|
+
requiredInConfig: false,
|
|
146
|
+
metadata: {
|
|
147
|
+
family: "mimo",
|
|
148
|
+
release_date: "2026-04-22",
|
|
149
|
+
attachment: true,
|
|
150
|
+
reasoning: true,
|
|
151
|
+
temperature: true,
|
|
152
|
+
tool_call: true,
|
|
153
|
+
interleaved: { field: "reasoning_details" },
|
|
154
|
+
limit: { context: 32e3, output: 131072 },
|
|
155
|
+
modalities: { input: ["text", "audio", "image", "video"], output: ["text"] }
|
|
156
|
+
}
|
|
157
|
+
},
|
|
158
|
+
{
|
|
159
|
+
id: "xiaomi/mimo-v2.5-pro",
|
|
160
|
+
name: "Assistente de contexto longo",
|
|
161
|
+
approvedByDefault: true,
|
|
162
|
+
requiredInConfig: false,
|
|
163
|
+
metadata: {
|
|
164
|
+
family: "mimo",
|
|
165
|
+
release_date: "2026-04-22",
|
|
166
|
+
attachment: false,
|
|
167
|
+
reasoning: true,
|
|
168
|
+
temperature: true,
|
|
169
|
+
tool_call: true,
|
|
170
|
+
interleaved: { field: "reasoning_content" },
|
|
171
|
+
limit: { context: 1048576, output: 131072 },
|
|
172
|
+
modalities: { input: ["text"], output: ["text"] }
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
{
|
|
176
|
+
id: "z-ai/glm-5.2",
|
|
177
|
+
name: "Assistente de an\xE1lise",
|
|
178
|
+
approvedByDefault: false,
|
|
179
|
+
requiredInConfig: false,
|
|
180
|
+
metadata: {
|
|
181
|
+
family: "glm",
|
|
182
|
+
release_date: "2026-02-12",
|
|
183
|
+
attachment: false,
|
|
184
|
+
reasoning: true,
|
|
185
|
+
temperature: true,
|
|
186
|
+
tool_call: true,
|
|
187
|
+
interleaved: { field: "reasoning_content" },
|
|
188
|
+
limit: { context: 1048576, output: 32768 },
|
|
189
|
+
modalities: { input: ["text"], output: ["text"] }
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
];
|
|
193
|
+
var APPROVED_MODELS = BUILT_IN_OPENROUTER_MODELS.filter((model) => model.approvedByDefault).map(stripCatalogFlags);
|
|
194
|
+
function cloneModel(model) {
|
|
195
|
+
return {
|
|
196
|
+
id: model.id,
|
|
197
|
+
name: model.name,
|
|
198
|
+
...model.provider ? { provider: model.provider } : {},
|
|
199
|
+
...model.upstreamModel ? { upstreamModel: model.upstreamModel } : {},
|
|
200
|
+
...model.billingMode ? { billingMode: model.billingMode } : {},
|
|
201
|
+
...model.metadata ? { metadata: structuredClone(model.metadata) } : {}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
function stripCatalogFlags(model) {
|
|
205
|
+
const { approvedByDefault: _approvedByDefault, requiredInConfig: _requiredInConfig, ...approved } = model;
|
|
206
|
+
return cloneModel(approved);
|
|
207
|
+
}
|
|
208
|
+
function openRouterReasoningVariants(efforts) {
|
|
209
|
+
return Object.fromEntries(efforts.map((effort) => [effort, { reasoning: { effort } }]));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// packages/shared/src/contracts/debugTrace.ts
|
|
213
|
+
var DEFAULT_DEBUG_TRACE_LIMITS = {
|
|
214
|
+
eventEnvelopeBytes: 256 * 1024,
|
|
215
|
+
artifactChunkBytes: 2 * 1024 * 1024,
|
|
216
|
+
// Serialized request bodies must remain comfortably below Vercel's 4.5 MB
|
|
217
|
+
// function request limit after JSON and base64 overhead.
|
|
218
|
+
uploadBatchBytes: 3 * 1024 * 1024,
|
|
219
|
+
uploadBatchRecords: 100,
|
|
220
|
+
fileSnapshotBytes: 1024 * 1024,
|
|
221
|
+
serverTraceBudgetBytes: 250 * 1024 * 1024,
|
|
222
|
+
workerTraceQuotaPer24h: 100,
|
|
223
|
+
workerBytesQuotaPer24h: 1024 * 1024 * 1024,
|
|
224
|
+
localQueueBytes: 1024 * 1024 * 1024,
|
|
225
|
+
retryBackoffMinMs: 5e3,
|
|
226
|
+
retryBackoffMaxMs: 5 * 60 * 1e3,
|
|
227
|
+
queueMaxAgeDays: 7,
|
|
228
|
+
rawTempExposureSeconds: 15 * 60
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
// packages/shared/src/contracts/settings.ts
|
|
232
|
+
var WORK_PACK_SYNC_PLUGIN_VERSION = "0.1.57";
|
|
233
|
+
var WORK_PACK_SYNC_PLUGIN_PACKAGE = `minimal-forge-work-pack-sync@${WORK_PACK_SYNC_PLUGIN_VERSION}`;
|
|
234
|
+
var WORK_PACK_SYNC_PLUGIN_FILENAME = `minimal-forge-work-pack-sync-${WORK_PACK_SYNC_PLUGIN_VERSION}.tgz`;
|
|
235
|
+
var FIRECRAWL_KEYLESS_MCP_NAME = "firecrawl";
|
|
236
|
+
var FIRECRAWL_KEYLESS_PERMISSION = `${FIRECRAWL_KEYLESS_MCP_NAME}_*`;
|
|
237
|
+
|
|
238
|
+
// packages/shared/src/pythonRequirements.ts
|
|
239
|
+
var PYTHON_REQUIREMENTS = [
|
|
240
|
+
{ name: "pandas", importName: "pandas", requirement: "pandas>=2.1,<3" },
|
|
241
|
+
{ name: "numpy", importName: "numpy", requirement: "numpy>=1.26,<3" },
|
|
242
|
+
{ name: "scipy", importName: "scipy", requirement: "scipy>=1.11,<2" },
|
|
243
|
+
{ name: "openpyxl", importName: "openpyxl", requirement: "openpyxl>=3.1,<4" },
|
|
244
|
+
{ name: "pyreadstat", importName: "pyreadstat", requirement: "pyreadstat>=1.2,<2" },
|
|
245
|
+
{ name: "python-docx", importName: "docx", requirement: "python-docx>=1.1,<2" },
|
|
246
|
+
{ name: "python-pptx", importName: "pptx", requirement: "python-pptx>=1,<2" },
|
|
247
|
+
{ name: "pypdf", importName: "pypdf", requirement: "pypdf>=5,<8" },
|
|
248
|
+
{ name: "PyYAML", importName: "yaml", requirement: "PyYAML>=6,<7" },
|
|
249
|
+
{ name: "Pillow", importName: "PIL", requirement: "Pillow>=10,<13" }
|
|
250
|
+
];
|
|
251
|
+
|
|
252
|
+
// packages/cli/src/coreSyncLock.ts
|
|
253
|
+
import { randomUUID } from "node:crypto";
|
|
254
|
+
import { mkdir, readdir, readFile, rename, rmdir, unlink, writeFile } from "node:fs/promises";
|
|
255
|
+
import { hostname } from "node:os";
|
|
256
|
+
import path2 from "node:path";
|
|
257
|
+
function hasCode(error, ...codes) {
|
|
258
|
+
return error instanceof Error && codes.includes(error.code ?? "");
|
|
259
|
+
}
|
|
260
|
+
var CoreSyncLockError = class extends Error {
|
|
261
|
+
};
|
|
262
|
+
function unknownOwner() {
|
|
263
|
+
return new CoreSyncLockError("O propriet\xE1rio do bloqueio de sincroniza\xE7\xE3o Forge n\xE3o foi confirmado nesta m\xE1quina. Pe\xE7a ao operador para verificar o processo e a m\xE1quina de origem.");
|
|
264
|
+
}
|
|
265
|
+
async function removeEmpty(directory) {
|
|
266
|
+
try {
|
|
267
|
+
await rmdir(directory);
|
|
268
|
+
} catch (error) {
|
|
269
|
+
if (!hasCode(error, "ENOENT", "EEXIST", "ENOTEMPTY")) throw error;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
async function reclaim(lockPath, renameError) {
|
|
273
|
+
let entries;
|
|
274
|
+
try {
|
|
275
|
+
entries = await readdir(lockPath);
|
|
276
|
+
} catch (error) {
|
|
277
|
+
if (!hasCode(error, "ENOENT")) throw error;
|
|
278
|
+
if (hasCode(renameError, "EACCES", "EPERM")) throw renameError;
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
if (entries.length) {
|
|
282
|
+
const marker = entries[0];
|
|
283
|
+
const match = /^owner-([1-9]\d*)-[0-9a-f-]{36}$/.exec(marker);
|
|
284
|
+
if (entries.length !== 1 || !match) throw unknownOwner();
|
|
285
|
+
const markerPath = path2.join(lockPath, marker);
|
|
286
|
+
let host;
|
|
287
|
+
try {
|
|
288
|
+
host = await readFile(markerPath, "utf8");
|
|
289
|
+
} catch (error) {
|
|
290
|
+
if (hasCode(error, "ENOENT")) return;
|
|
291
|
+
throw error;
|
|
292
|
+
}
|
|
293
|
+
if (host !== hostname()) throw unknownOwner();
|
|
294
|
+
try {
|
|
295
|
+
process.kill(Number(match[1]), 0);
|
|
296
|
+
} catch (error) {
|
|
297
|
+
if (!hasCode(error, "ESRCH")) throw error;
|
|
298
|
+
await unlink(markerPath).catch((cause) => {
|
|
299
|
+
if (!hasCode(cause, "ENOENT")) throw cause;
|
|
300
|
+
});
|
|
301
|
+
await removeEmpty(lockPath);
|
|
302
|
+
return;
|
|
303
|
+
}
|
|
304
|
+
throw new CoreSyncLockError("J\xE1 est\xE1 em curso uma sincroniza\xE7\xE3o do Forge. Aguarde que termine e volte a tentar.");
|
|
305
|
+
}
|
|
306
|
+
await removeEmpty(lockPath);
|
|
307
|
+
}
|
|
308
|
+
async function withCoreSyncLock(journalPath, operation) {
|
|
309
|
+
const lockPath = journalPath + ".lock";
|
|
310
|
+
const id = randomUUID();
|
|
311
|
+
const candidate = lockPath + "-" + id;
|
|
312
|
+
const marker = `owner-${process.pid}-${id}`;
|
|
313
|
+
await mkdir(path2.dirname(lockPath), { recursive: true });
|
|
314
|
+
await mkdir(candidate, { mode: 448 });
|
|
315
|
+
let directory = candidate;
|
|
316
|
+
try {
|
|
317
|
+
await writeFile(path2.join(candidate, marker), hostname(), { mode: 384, flag: "wx" });
|
|
318
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
319
|
+
try {
|
|
320
|
+
await rename(candidate, lockPath);
|
|
321
|
+
} catch (error) {
|
|
322
|
+
if (!hasCode(error, "EEXIST", "ENOTEMPTY", "EPERM", "EACCES")) throw error;
|
|
323
|
+
await reclaim(lockPath, error);
|
|
324
|
+
continue;
|
|
325
|
+
}
|
|
326
|
+
directory = lockPath;
|
|
327
|
+
return await operation();
|
|
328
|
+
}
|
|
329
|
+
throw new CoreSyncLockError("Outra sincroniza\xE7\xE3o Forge pode estar em curso. Aguarde que termine e volte a tentar.");
|
|
330
|
+
} finally {
|
|
331
|
+
await unlink(path2.join(directory, marker)).catch((error) => {
|
|
332
|
+
if (!hasCode(error, "ENOENT")) throw error;
|
|
333
|
+
});
|
|
334
|
+
await removeEmpty(directory);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// packages/cli/src/ownerOnlyFile.ts
|
|
339
|
+
import { spawnSync as nodeSpawnSync } from "node:child_process";
|
|
340
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
341
|
+
import { chmod, mkdir as mkdir2, rename as rename2, rm, stat, writeFile as writeFile2 } from "node:fs/promises";
|
|
342
|
+
import path3 from "node:path";
|
|
343
|
+
async function protectOwnerOnlyPath(filePath, kind, options = {}) {
|
|
344
|
+
const platform = options.platform ?? process.platform;
|
|
345
|
+
if (platform !== "win32") {
|
|
346
|
+
await chmod(filePath, kind === "directory" ? 448 : 384);
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
const spawn = options.spawnSync ?? nodeSpawnSync;
|
|
350
|
+
const command = kind === "directory" ? "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.DirectorySecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $inheritance = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit; $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, $inheritance, [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.Directory]::SetAccessControl($path, $acl)" : "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.FileSecurity]::new(); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($identity, [System.Security.AccessControl.FileSystemRights]::FullControl, [System.Security.AccessControl.AccessControlType]::Allow); [void]$acl.AddAccessRule($rule); [System.IO.File]::SetAccessControl($path, $acl)";
|
|
351
|
+
const result2 = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
|
|
352
|
+
encoding: "utf8",
|
|
353
|
+
input: filePath
|
|
354
|
+
});
|
|
355
|
+
if (result2.status !== 0) {
|
|
356
|
+
const detail = typeof result2.stderr === "string" ? result2.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
|
|
357
|
+
const context = options.failureContext ?? (kind === "directory" ? "o diret\xF3rio" : "o ficheiro");
|
|
358
|
+
throw new Error(`N\xE3o foi poss\xEDvel proteger ${context} em ${filePath}${detail ? `: ${detail}` : ""}`);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
async function assertExistingDirectoryIsSafe(directory, options) {
|
|
362
|
+
const platform = options.platform ?? process.platform;
|
|
363
|
+
if (platform !== "win32") {
|
|
364
|
+
const info = await stat(directory);
|
|
365
|
+
const currentUid = process.getuid?.();
|
|
366
|
+
if (currentUid !== void 0 && info.uid !== currentUid || (info.mode & 18) !== 0) {
|
|
367
|
+
const mode = (info.mode & 511).toString(8).padStart(3, "0");
|
|
368
|
+
throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual (modo ${mode})`);
|
|
369
|
+
}
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
const spawn = options.spawnSync ?? nodeSpawnSync;
|
|
373
|
+
const command = "$ErrorActionPreference = 'Stop'; $path = [Console]::In.ReadToEnd(); $current = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value; $trusted = @($current, 'S-1-5-18', 'S-1-5-32-544'); $dangerous = [System.Security.AccessControl.FileSystemRights]::Write -bor [System.Security.AccessControl.FileSystemRights]::Delete -bor [System.Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor [System.Security.AccessControl.FileSystemRights]::ChangePermissions -bor [System.Security.AccessControl.FileSystemRights]::TakeOwnership; $acl = [System.IO.Directory]::GetAccessControl($path); $rules = $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier]); foreach ($rule in $rules) { if ($rule.AccessControlType -eq [System.Security.AccessControl.AccessControlType]::Allow -and $rule.PropagationFlags -ne [System.Security.AccessControl.PropagationFlags]::InheritOnly -and ($rule.FileSystemRights -band $dangerous) -ne 0 -and $trusted -notcontains $rule.IdentityReference.Value) { throw ('O diret\xF3rio permite escrita por ' + $rule.IdentityReference.Value) } }";
|
|
374
|
+
const result2 = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
|
|
375
|
+
encoding: "utf8",
|
|
376
|
+
input: directory
|
|
377
|
+
});
|
|
378
|
+
if (result2.status !== 0) {
|
|
379
|
+
const detail = typeof result2.stderr === "string" ? result2.stderr.trim().replace(/\s+/g, " ").slice(0, 500) : "";
|
|
380
|
+
throw new Error(`O diret\xF3rio existente ${directory} n\xE3o \xE9 controlado apenas pelo utilizador atual${detail ? `: ${detail}` : ""}`);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
async function prepareOwnerOnlyFileDestination(filePath, options = {}) {
|
|
384
|
+
const directory = path3.dirname(filePath);
|
|
385
|
+
let existing;
|
|
386
|
+
try {
|
|
387
|
+
existing = await stat(directory);
|
|
388
|
+
} catch (error) {
|
|
389
|
+
if (error.code !== "ENOENT") throw error;
|
|
390
|
+
}
|
|
391
|
+
if (existing) {
|
|
392
|
+
if (!existing.isDirectory()) throw new Error(`O destino ${directory} existe, mas n\xE3o \xE9 um diret\xF3rio`);
|
|
393
|
+
await assertExistingDirectoryIsSafe(directory, options);
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
let createdDirectory;
|
|
397
|
+
try {
|
|
398
|
+
createdDirectory = await mkdir2(directory, { recursive: true, mode: 448 });
|
|
399
|
+
} catch (error) {
|
|
400
|
+
if (error.code !== "EEXIST" || !(await stat(directory)).isDirectory()) throw error;
|
|
401
|
+
await assertExistingDirectoryIsSafe(directory, options);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
if (createdDirectory !== void 0) await protectOwnerOnlyPath(directory, "directory", options);
|
|
405
|
+
else await assertExistingDirectoryIsSafe(directory, options);
|
|
406
|
+
}
|
|
407
|
+
async function writeOwnerOnlyTextAtomic(filePath, content, options = {}) {
|
|
408
|
+
const directory = path3.dirname(filePath);
|
|
409
|
+
await prepareOwnerOnlyFileDestination(filePath, options);
|
|
410
|
+
const temporary = path3.join(directory, `.${path3.basename(filePath)}.${randomUUID2()}.tmp`);
|
|
411
|
+
try {
|
|
412
|
+
await writeFile2(temporary, content, { flag: "wx", mode: 384 });
|
|
413
|
+
await protectOwnerOnlyPath(temporary, "file", options);
|
|
414
|
+
await rename2(temporary, filePath);
|
|
415
|
+
await protectOwnerOnlyPath(filePath, "file", options);
|
|
416
|
+
} catch (error) {
|
|
417
|
+
await rm(temporary, { force: true }).catch(() => void 0);
|
|
418
|
+
throw error;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// packages/cli/src/pythonReadiness.ts
|
|
423
|
+
var runPython = promisify(execFile);
|
|
424
|
+
var CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
|
|
425
|
+
var PROBE_MARKER = "FORGE_PYTHON_READINESS=";
|
|
426
|
+
var PROBE = String.raw`
|
|
427
|
+
import sys
|
|
428
|
+
|
|
429
|
+
# The check runs against the interpreter's installed packages without importing
|
|
430
|
+
# scripts from the directory in which OpenWork or the CLI was opened.
|
|
431
|
+
if sys.path and sys.path[0] == "":
|
|
432
|
+
sys.path.pop(0)
|
|
433
|
+
|
|
434
|
+
import json
|
|
435
|
+
import os
|
|
436
|
+
import platform
|
|
437
|
+
|
|
438
|
+
identity = {
|
|
439
|
+
"interpreter": os.path.abspath(sys.executable) if sys.executable else "",
|
|
440
|
+
"pythonVersion": platform.python_version(),
|
|
441
|
+
"supported": sys.version_info >= (3, 10),
|
|
442
|
+
}
|
|
443
|
+
if not identity["supported"]:
|
|
444
|
+
print("${PROBE_MARKER}" + json.dumps(identity))
|
|
445
|
+
sys.exit(0)
|
|
446
|
+
|
|
447
|
+
import importlib
|
|
448
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
449
|
+
from io import BytesIO
|
|
450
|
+
import re
|
|
451
|
+
import site
|
|
452
|
+
|
|
453
|
+
def release(value):
|
|
454
|
+
# The approved ranges are inclusive/exclusive numeric releases. Accept
|
|
455
|
+
# post and local builds, and leave prereleases outside the baseline.
|
|
456
|
+
match = re.fullmatch(r"(?:0!)?(\d+(?:\.\d+)*)(?:(?:[._-]?(?:post|rev|r)[._-]?\d+)|-\d+)?(?:\+[a-z0-9._-]+)?", value.lower())
|
|
457
|
+
if not match:
|
|
458
|
+
return None
|
|
459
|
+
parts = [int(part) for part in match[1].split(".")]
|
|
460
|
+
while len(parts) > 1 and parts[-1] == 0:
|
|
461
|
+
parts.pop()
|
|
462
|
+
return tuple(parts)
|
|
463
|
+
|
|
464
|
+
def compatible(installed, requirement):
|
|
465
|
+
minimum, before = requirement.split(">=", 1)[1].split(",<", 1)
|
|
466
|
+
installed = release(installed)
|
|
467
|
+
return installed is not None and release(minimum) <= installed < release(before)
|
|
468
|
+
|
|
469
|
+
def check_package(package):
|
|
470
|
+
try:
|
|
471
|
+
installed = version(package["name"])
|
|
472
|
+
except PackageNotFoundError:
|
|
473
|
+
return {**package, "status": "missing"}
|
|
474
|
+
try:
|
|
475
|
+
module = importlib.import_module(package["importName"])
|
|
476
|
+
except Exception:
|
|
477
|
+
status = "import-failed" if compatible(installed, package["requirement"]) else "incompatible"
|
|
478
|
+
return {**package, "version": installed, "status": status}
|
|
479
|
+
imported = getattr(module, "__version__", installed)
|
|
480
|
+
if not isinstance(imported, str):
|
|
481
|
+
imported = installed
|
|
482
|
+
status = "ready" if compatible(imported, package["requirement"]) and compatible(installed, package["requirement"]) else "incompatible"
|
|
483
|
+
return {**package, "version": imported, "status": status}
|
|
484
|
+
|
|
485
|
+
def example_image():
|
|
486
|
+
from PIL import Image
|
|
487
|
+
|
|
488
|
+
contents = BytesIO()
|
|
489
|
+
Image.new("RGB", (12, 12), "blue").save(contents, format="PNG")
|
|
490
|
+
contents.seek(0)
|
|
491
|
+
return contents
|
|
492
|
+
|
|
493
|
+
def check_word():
|
|
494
|
+
from docx import Document
|
|
495
|
+
|
|
496
|
+
document = Document()
|
|
497
|
+
document.add_paragraph("Forge")
|
|
498
|
+
document.add_picture(example_image())
|
|
499
|
+
contents = BytesIO()
|
|
500
|
+
document.save(contents)
|
|
501
|
+
contents.seek(0)
|
|
502
|
+
reopened = Document(contents)
|
|
503
|
+
return reopened.paragraphs[0].text == "Forge" and len(reopened.inline_shapes) == 1
|
|
504
|
+
|
|
505
|
+
def check_excel():
|
|
506
|
+
from openpyxl import Workbook, load_workbook
|
|
507
|
+
from openpyxl.drawing.image import Image
|
|
508
|
+
|
|
509
|
+
workbook = Workbook()
|
|
510
|
+
workbook.active["A1"] = "Forge"
|
|
511
|
+
workbook.active.add_image(Image(example_image()), "B2")
|
|
512
|
+
contents = BytesIO()
|
|
513
|
+
workbook.save(contents)
|
|
514
|
+
contents.seek(0)
|
|
515
|
+
reopened = load_workbook(contents)
|
|
516
|
+
try:
|
|
517
|
+
return reopened.active["A1"].value == "Forge" and len(reopened.active._images) == 1
|
|
518
|
+
finally:
|
|
519
|
+
reopened.close()
|
|
520
|
+
|
|
521
|
+
def check_powerpoint():
|
|
522
|
+
from pptx import Presentation
|
|
523
|
+
from pptx.enum.shapes import MSO_SHAPE_TYPE
|
|
524
|
+
from pptx.util import Inches
|
|
525
|
+
|
|
526
|
+
presentation = Presentation()
|
|
527
|
+
slide = presentation.slides.add_slide(presentation.slide_layouts[6])
|
|
528
|
+
slide.shapes.add_textbox(Inches(1), Inches(1), Inches(4), Inches(1)).text_frame.text = "Forge"
|
|
529
|
+
slide.shapes.add_picture(example_image(), Inches(1), Inches(2))
|
|
530
|
+
contents = BytesIO()
|
|
531
|
+
presentation.save(contents)
|
|
532
|
+
contents.seek(0)
|
|
533
|
+
reopened = Presentation(contents)
|
|
534
|
+
texts = [shape.text for shape in reopened.slides[0].shapes if shape.has_text_frame]
|
|
535
|
+
pictures = [shape for shape in reopened.slides[0].shapes if shape.shape_type == MSO_SHAPE_TYPE.PICTURE]
|
|
536
|
+
return "Forge" in texts and len(pictures) == 1
|
|
537
|
+
|
|
538
|
+
def check_document(check):
|
|
539
|
+
try:
|
|
540
|
+
return check()
|
|
541
|
+
except Exception:
|
|
542
|
+
return False
|
|
543
|
+
|
|
544
|
+
packages = [check_package(package) for package in json.loads(sys.argv[1])]
|
|
545
|
+
ready = {package["name"] for package in packages if package["status"] == "ready"}
|
|
546
|
+
result = {
|
|
547
|
+
**identity,
|
|
548
|
+
"virtualEnvironment": sys.prefix != sys.base_prefix,
|
|
549
|
+
"userSiteEnabled": site.ENABLE_USER_SITE is True,
|
|
550
|
+
"packages": packages,
|
|
551
|
+
"documents": {
|
|
552
|
+
"word": {"python-docx", "Pillow"} <= ready and check_document(check_word),
|
|
553
|
+
"excel": {"openpyxl", "Pillow"} <= ready and check_document(check_excel),
|
|
554
|
+
"powerpoint": {"python-pptx", "Pillow"} <= ready and check_document(check_powerpoint),
|
|
555
|
+
},
|
|
556
|
+
}
|
|
557
|
+
print("${PROBE_MARKER}" + json.dumps(result))
|
|
558
|
+
`;
|
|
559
|
+
var BASELINE_KEY = createHash("sha256").update(PROBE).update(JSON.stringify(PYTHON_REQUIREMENTS)).digest("hex");
|
|
560
|
+
function needsInstall(entry) {
|
|
561
|
+
return entry.status === "missing" || entry.status === "incompatible";
|
|
562
|
+
}
|
|
563
|
+
var selectionUnreadable = "N\xE3o foi poss\xEDvel ler a sele\xE7\xE3o Python do Forge. Selecione novamente o Python com --python.";
|
|
564
|
+
function selectionPath(paths) {
|
|
565
|
+
return path4.join(paths.forgeDir, "python-readiness.json");
|
|
566
|
+
}
|
|
567
|
+
function cachePath(paths) {
|
|
568
|
+
return path4.join(paths.forgeDir, "python-readiness-cache.json");
|
|
569
|
+
}
|
|
570
|
+
function result(fields) {
|
|
571
|
+
return { ...fields, checkedAt: (/* @__PURE__ */ new Date()).toISOString(), cached: false };
|
|
572
|
+
}
|
|
573
|
+
function unverified(reason, interpreter) {
|
|
574
|
+
return result({ status: "unverified", interpreter, reason });
|
|
575
|
+
}
|
|
576
|
+
function selectPython(reason, interpreter) {
|
|
577
|
+
return { ...unverified(reason, interpreter), requiresPythonSelection: true };
|
|
578
|
+
}
|
|
579
|
+
async function readSelection(paths) {
|
|
580
|
+
let contents;
|
|
581
|
+
try {
|
|
582
|
+
contents = await readFile2(selectionPath(paths), "utf8");
|
|
583
|
+
} catch (error) {
|
|
584
|
+
if (error.code === "ENOENT") return void 0;
|
|
585
|
+
throw error;
|
|
586
|
+
}
|
|
587
|
+
const selected = JSON.parse(contents);
|
|
588
|
+
if (typeof selected?.interpreter !== "string" || !path4.isAbsolute(selected.interpreter) || typeof selected.revision !== "string") {
|
|
589
|
+
throw new Error("Invalid Python selection");
|
|
590
|
+
}
|
|
591
|
+
return selected;
|
|
592
|
+
}
|
|
593
|
+
async function cacheKey(selection) {
|
|
594
|
+
try {
|
|
595
|
+
const executable = await stat2(selection.interpreter);
|
|
596
|
+
if (!executable.isFile()) return void 0;
|
|
597
|
+
const venvConfig = await stat2(path4.resolve(path4.dirname(selection.interpreter), "..", "pyvenv.cfg")).catch(() => void 0);
|
|
598
|
+
return JSON.stringify([BASELINE_KEY, selection, executable.ino, executable.size, executable.mtimeMs, executable.ctimeMs, venvConfig?.mtimeMs]);
|
|
599
|
+
} catch {
|
|
600
|
+
return void 0;
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
async function saveCache(paths, key, checked) {
|
|
604
|
+
if (!key) return;
|
|
605
|
+
const cache = { key, result: checked };
|
|
606
|
+
await writeOwnerOnlyTextAtomic(cachePath(paths), `${JSON.stringify(cache)}
|
|
607
|
+
`).catch(() => void 0);
|
|
608
|
+
}
|
|
609
|
+
async function probePython(interpreter) {
|
|
610
|
+
if (!interpreter || !path4.isAbsolute(interpreter)) {
|
|
611
|
+
return { checked: selectPython("Selecione um execut\xE1vel Python 3 atrav\xE9s de --python com o caminho absoluto.") };
|
|
612
|
+
}
|
|
613
|
+
try {
|
|
614
|
+
const { stdout } = await runPython(interpreter, ["-B", "-c", PROBE, JSON.stringify(PYTHON_REQUIREMENTS)], {
|
|
615
|
+
cwd: os2.homedir(),
|
|
616
|
+
encoding: "utf8",
|
|
617
|
+
timeout: 6e4,
|
|
618
|
+
windowsHide: true
|
|
619
|
+
});
|
|
620
|
+
const record = stdout.split(/\r?\n/).reverse().find((line) => line.startsWith(PROBE_MARKER));
|
|
621
|
+
const probe = JSON.parse(record?.slice(PROBE_MARKER.length) ?? "null");
|
|
622
|
+
if (!probe || typeof probe.interpreter !== "string" || !path4.isAbsolute(probe.interpreter) || typeof probe.pythonVersion !== "string") {
|
|
623
|
+
return { checked: selectPython("O execut\xE1vel selecionado n\xE3o devolveu um diagn\xF3stico Python v\xE1lido.", interpreter) };
|
|
624
|
+
}
|
|
625
|
+
if (probe.supported === false) {
|
|
626
|
+
return { checked: result({ interpreter: probe.interpreter, pythonVersion: probe.pythonVersion, status: "not-ready", reason: "Selecione Python 3.10 ou posterior.", requiresPythonSelection: true }) };
|
|
627
|
+
}
|
|
628
|
+
if (probe.supported !== true || !probe.documents || probe.packages?.length !== PYTHON_REQUIREMENTS.length) {
|
|
629
|
+
return { checked: selectPython("O execut\xE1vel selecionado n\xE3o devolveu um diagn\xF3stico Python v\xE1lido.", interpreter) };
|
|
630
|
+
}
|
|
631
|
+
const details = { interpreter: probe.interpreter, pythonVersion: probe.pythonVersion, packages: probe.packages, documents: probe.documents };
|
|
632
|
+
if (probe.packages.some(needsInstall)) {
|
|
633
|
+
return { probe, checked: result({ ...details, status: "not-ready", reason: "O Python selecionado tem bibliotecas em falta ou incompat\xEDveis. Execute prepare para instalar as bibliotecas indicadas." }) };
|
|
634
|
+
}
|
|
635
|
+
if (probe.packages.some((entry) => entry.status === "import-failed")) {
|
|
636
|
+
return { probe, checked: result({ ...details, status: "not-ready", reason: "Uma biblioteca instalada falhou ao importar. Envie o diagn\xF3stico ao suporte para reparar o ambiente ou selecionar outro Python." }) };
|
|
637
|
+
}
|
|
638
|
+
if (!probe.documents.word || !probe.documents.excel || !probe.documents.powerpoint) {
|
|
639
|
+
return { probe, checked: result({ ...details, status: "not-ready", reason: "O Python selecionado n\xE3o concluiu o ensaio de Word, Excel ou PowerPoint com imagens. Envie o diagn\xF3stico ao suporte para verificar esse ambiente." }) };
|
|
640
|
+
}
|
|
641
|
+
return { probe, checked: result({ ...details, status: "ready" }) };
|
|
642
|
+
} catch (error) {
|
|
643
|
+
const failure = error;
|
|
644
|
+
if (failure.code === "ENOENT") {
|
|
645
|
+
return { checked: selectPython("O execut\xE1vel Python selecionado j\xE1 n\xE3o est\xE1 dispon\xEDvel. Selecione novamente o Python com --python.", interpreter) };
|
|
646
|
+
}
|
|
647
|
+
if (failure.code === "EACCES" || failure.code === "EPERM") {
|
|
648
|
+
return { checked: selectPython("O utilizador atual n\xE3o tem permiss\xE3o para executar o Python selecionado.", interpreter) };
|
|
649
|
+
}
|
|
650
|
+
return { checked: unverified(failure.killed ? "O Python selecionado n\xE3o concluiu a verifica\xE7\xE3o no tempo dispon\xEDvel." : "N\xE3o foi poss\xEDvel verificar o Python selecionado.", interpreter) };
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
async function probeSavedPython(interpreter) {
|
|
654
|
+
const outcome = await probePython(interpreter);
|
|
655
|
+
if (outcome.checked.interpreter && outcome.checked.interpreter !== interpreter) {
|
|
656
|
+
return { checked: selectPython("O caminho guardado aponta agora para outro Python. Selecione novamente o Python com --python.", interpreter) };
|
|
657
|
+
}
|
|
658
|
+
return outcome;
|
|
659
|
+
}
|
|
660
|
+
async function checkPythonReadiness(paths, interpreter) {
|
|
661
|
+
try {
|
|
662
|
+
return (await (interpreter === void 0 ? probeSavedPython((await readSelection(paths))?.interpreter) : probePython(interpreter))).checked;
|
|
663
|
+
} catch {
|
|
664
|
+
return selectPython(selectionUnreadable);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
function installFailure(error) {
|
|
668
|
+
const failure = error;
|
|
669
|
+
const stderr = failure.stderr ?? "";
|
|
670
|
+
if (failure.killed) return { reason: "A instala\xE7\xE3o de bibliotecas Python excedeu o tempo dispon\xEDvel." };
|
|
671
|
+
if (/no module named pip/i.test(stderr)) {
|
|
672
|
+
return { reason: "O Python selecionado n\xE3o tem pip. Selecione um Python com pip dispon\xEDvel.", requiresPythonSelection: true };
|
|
673
|
+
}
|
|
674
|
+
if (/externally-managed-environment|externally managed/i.test(stderr)) {
|
|
675
|
+
return { reason: "A pol\xEDtica do Python selecionado impede altera\xE7\xF5es por pip. Selecione um ambiente Python do utilizador onde pip possa instalar bibliotecas.", requiresPythonSelection: true };
|
|
676
|
+
}
|
|
677
|
+
if (/permission denied|access is denied|winerror 5/i.test(stderr)) {
|
|
678
|
+
return { reason: "O utilizador atual n\xE3o tem permiss\xE3o para instalar bibliotecas no Python selecionado. Selecione um ambiente Python onde tenha acesso de escrita.", requiresPythonSelection: true };
|
|
679
|
+
}
|
|
680
|
+
if (/no matching distribution|could not find a version/i.test(stderr)) {
|
|
681
|
+
return { reason: "O pip n\xE3o encontrou uma vers\xE3o compat\xEDvel das bibliotecas pedidas para o Python selecionado." };
|
|
682
|
+
}
|
|
683
|
+
return { reason: "O pip n\xE3o concluiu a instala\xE7\xE3o das bibliotecas Python pedidas." };
|
|
684
|
+
}
|
|
685
|
+
async function preparePythonReadiness(paths, interpreter) {
|
|
686
|
+
let selected;
|
|
687
|
+
try {
|
|
688
|
+
selected = interpreter ?? (await readSelection(paths))?.interpreter;
|
|
689
|
+
} catch {
|
|
690
|
+
return selectPython(selectionUnreadable);
|
|
691
|
+
}
|
|
692
|
+
if (!selected || !path4.isAbsolute(selected)) return (await probePython(selected)).checked;
|
|
693
|
+
try {
|
|
694
|
+
return await withCoreSyncLock(selectionPath(paths), async () => {
|
|
695
|
+
const saved = await readSelection(paths).catch(() => void 0);
|
|
696
|
+
const actual = interpreter ?? saved?.interpreter;
|
|
697
|
+
const initial = await (interpreter === void 0 ? probeSavedPython(actual) : probePython(actual));
|
|
698
|
+
const { checked, probe } = initial.probe && initial.probe.interpreter !== actual ? await probeSavedPython(initial.probe.interpreter) : initial;
|
|
699
|
+
if (!probe) return checked;
|
|
700
|
+
const selection = { interpreter: probe.interpreter, revision: randomUUID3() };
|
|
701
|
+
const sameAsSaved = saved?.interpreter === probe.interpreter;
|
|
702
|
+
let prepared = checked;
|
|
703
|
+
if (probe.packages.some(needsInstall)) {
|
|
704
|
+
let failure;
|
|
705
|
+
if (!probe.virtualEnvironment && !probe.userSiteEnabled) {
|
|
706
|
+
failure = { reason: "O Python selecionado tem a instala\xE7\xE3o de bibliotecas do utilizador desativada. Selecione um ambiente Python do utilizador.", requiresPythonSelection: true };
|
|
707
|
+
prepared = { ...checked, status: "not-ready", ...failure };
|
|
708
|
+
} else {
|
|
709
|
+
if (sameAsSaved) {
|
|
710
|
+
await writeOwnerOnlyTextAtomic(selectionPath(paths), `${JSON.stringify({ ...selection, preparing: true })}
|
|
711
|
+
`);
|
|
712
|
+
}
|
|
713
|
+
try {
|
|
714
|
+
await runPython(probe.interpreter, [
|
|
715
|
+
"-B",
|
|
716
|
+
"-m",
|
|
717
|
+
"pip",
|
|
718
|
+
"--disable-pip-version-check",
|
|
719
|
+
"--no-input",
|
|
720
|
+
"install",
|
|
721
|
+
"--progress-bar",
|
|
722
|
+
"off",
|
|
723
|
+
...probe.virtualEnvironment ? [] : ["--user"],
|
|
724
|
+
...PYTHON_REQUIREMENTS.map((entry) => entry.requirement)
|
|
725
|
+
], {
|
|
726
|
+
cwd: os2.homedir(),
|
|
727
|
+
encoding: "utf8",
|
|
728
|
+
timeout: 10 * 6e4,
|
|
729
|
+
windowsHide: true
|
|
730
|
+
});
|
|
731
|
+
} catch (error) {
|
|
732
|
+
failure = installFailure(error);
|
|
733
|
+
}
|
|
734
|
+
prepared = (await probeSavedPython(probe.interpreter)).checked;
|
|
735
|
+
if (failure) prepared = { ...prepared, status: "not-ready", ...failure };
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (prepared.status === "ready" || sameAsSaved) {
|
|
739
|
+
await saveCache(paths, await cacheKey(selection), prepared);
|
|
740
|
+
await writeOwnerOnlyTextAtomic(selectionPath(paths), `${JSON.stringify(selection)}
|
|
741
|
+
`);
|
|
742
|
+
}
|
|
743
|
+
return prepared;
|
|
744
|
+
});
|
|
745
|
+
} catch {
|
|
746
|
+
return unverified("N\xE3o foi poss\xEDvel guardar a prepara\xE7\xE3o Python no Forge. Verifique as permiss\xF5es e se j\xE1 est\xE1 a decorrer uma prepara\xE7\xE3o.", selected);
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// packages/cli/src/pythonReadinessCli.ts
|
|
751
|
+
var usage = "Utiliza\xE7\xE3o: forge-python check|prepare [--python <caminho absoluto para o execut\xE1vel Python>]";
|
|
752
|
+
async function main() {
|
|
753
|
+
const [action, ...options] = process.argv.slice(2);
|
|
754
|
+
if (action === "--help" || action === "-h") {
|
|
755
|
+
console.log(usage);
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
if (action !== "check" && action !== "prepare" || options.length && (options.length !== 2 || options[0] !== "--python" || !options[1])) {
|
|
759
|
+
console.error(usage);
|
|
760
|
+
process.exitCode = 1;
|
|
761
|
+
return;
|
|
762
|
+
}
|
|
763
|
+
const run = action === "check" ? checkPythonReadiness : preparePythonReadiness;
|
|
764
|
+
const checked = await run(resolvePaths(), options[1]);
|
|
765
|
+
console.log(JSON.stringify(checked, null, 2));
|
|
766
|
+
if (checked.status !== "ready") process.exitCode = 2;
|
|
767
|
+
}
|
|
768
|
+
main().catch(() => {
|
|
769
|
+
console.error("N\xE3o foi poss\xEDvel verificar ou preparar o Python no Forge.");
|
|
770
|
+
process.exitCode = 1;
|
|
771
|
+
});
|