farming-code 2.2.28 → 2.2.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +9 -31
  2. package/README.zh_cn.md +8 -30
  3. package/THIRD_PARTY_NOTICES.md +25 -6
  4. package/backend/acp/packaged-claude-acp.js +13 -0
  5. package/backend/acp/packaged-codex-acp.js +2 -2
  6. package/backend/acp-runtime.js +37 -2
  7. package/backend/acp-transcript.js +174 -9
  8. package/backend/agent-manager.js +27 -2
  9. package/backend/config-manager.js +44 -0
  10. package/backend/data/LICENSE.agent-browser +201 -0
  11. package/backend/data/runtime-dependency-manifest.json +199 -0
  12. package/backend/data/runtime-dependency-sources.json +5 -0
  13. package/backend/executable-discovery.js +7 -0
  14. package/backend/farming-agent-bootstrap.zh_cn.md +4 -2
  15. package/backend/farming-app-cli.js +160 -64
  16. package/backend/farming-cli.js +5 -3
  17. package/backend/index-html.js +13 -0
  18. package/backend/main-agent-skills.js +6 -10
  19. package/backend/npm-update-helper.js +43 -6
  20. package/backend/provider-adapters.js +10 -0
  21. package/backend/runtime-dependency-manager.js +759 -0
  22. package/backend/runtime-executable-invocation.js +20 -0
  23. package/backend/server-process-identity.js +47 -0
  24. package/backend/server.js +140 -157
  25. package/backend/slash-command-discovery.js +138 -1
  26. package/backend/storage-layout.js +15 -0
  27. package/backend/update-service.js +27 -1
  28. package/config/farming.install.env.example +4 -0
  29. package/dist/acp/LICENSE.claude-agent-acp +191 -0
  30. package/dist/acp/LICENSE.claude-agent-sdk +1 -0
  31. package/dist/acp/claude-agent-acp-0.59.0.mjs +41606 -0
  32. package/dist/assets/{App-CM7Cy-l4.css → App-BKNUILuL.css} +1 -1
  33. package/dist/assets/App-Ex2oVVXO.js +693 -0
  34. package/dist/assets/{FileEditorMarkdownPreview-DYOMm-b1.js → FileEditorMarkdownPreview-Cs9cLv8a.js} +1 -1
  35. package/dist/assets/FileEditorPane-CNtuGjQ3.js +2 -0
  36. package/dist/assets/IconGlyphs-BClgag6E.js +1 -0
  37. package/dist/assets/ProjectFilesSection-Cf2BEcAN.js +12 -0
  38. package/dist/assets/ReviewPage-BRuxFaH5.js +3 -0
  39. package/dist/assets/code-dark-BEZTQwYZ.css +1 -0
  40. package/dist/assets/{index-BzQO3pUr.js → index-CQNaZc3l.js} +2 -2
  41. package/dist/assets/main-DK9Sy7-c.css +1 -0
  42. package/dist/assets/{workspace-editor-monaco-tXA-udGx.js → workspace-editor-monaco-CJNwbpCy.js} +1 -1
  43. package/dist/assets/workspace-editor-monaco-CO9w8YV0.js +1 -0
  44. package/dist/assets/workspace-view-state-BjKPYp0E.js +7 -0
  45. package/dist/index.html +32 -3
  46. package/extensions/browser/backend/agent-browser-runtime.js +1041 -0
  47. package/extensions/browser/backend/browser-mcp-server.js +352 -0
  48. package/extensions/browser/backend/browser-resource-manager.js +899 -114
  49. package/extensions/browser/backend/browser-resource-store.js +47 -6
  50. package/extensions/browser/backend/browser-router.js +7 -2
  51. package/extensions/browser/backend/executable-discovery.js +146 -13
  52. package/extensions/browser/bin/farming-browser +384 -30
  53. package/extensions/browser/frontend/BrowserSidebarPortals.tsx +17 -19
  54. package/extensions/browser/frontend/BrowserViewer.tsx +217 -46
  55. package/extensions/browser/frontend/browser.css +68 -17
  56. package/extensions/browser/frontend/types.ts +6 -0
  57. package/extensions/browser/frontend/useBrowserResources.ts +10 -3
  58. package/index.html +31 -2
  59. package/package.json +10 -6
  60. package/shared/backend-connection-status.d.ts +12 -0
  61. package/shared/backend-connection-status.js +35 -4
  62. package/backend/agent-activity.js +0 -35
  63. package/dist/assets/App-CPG4WcjO.js +0 -658
  64. package/dist/assets/FileEditorPane-DXXq82aM.js +0 -2
  65. package/dist/assets/IconGlyphs-DrdPjYXr.js +0 -1
  66. package/dist/assets/ProjectFilesSection-CP66XVPl.js +0 -12
  67. package/dist/assets/ReviewPage-w21MEPD6.js +0 -3
  68. package/dist/assets/code-dark-BDjwj7Um.css +0 -1
  69. package/dist/assets/main-BlVUXfxa.css +0 -1
  70. package/dist/assets/workspace-editor-monaco-CFEfFNcA.js +0 -1
  71. package/dist/assets/workspace-view-state-BS_V8JVs.js +0 -7
  72. package/extensions/browser/backend/cdp-browser-runtime.js +0 -648
  73. package/extensions/browser/backend/cdp-client.js +0 -167
  74. /package/dist/acp/{codex-acp-1.1.4.js → codex-acp-1.1.4.mjs} +0 -0
@@ -0,0 +1,759 @@
1
+ const crypto = require('crypto');
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const { execFile, execFileSync } = require('child_process');
5
+ const { pipeline } = require('stream/promises');
6
+ const { Readable, Transform } = require('stream');
7
+ const tar = require('tar');
8
+ const storageLayout = require('./storage-layout');
9
+ const { runtimeExecutableInvocation } = require('./runtime-executable-invocation');
10
+
11
+ const MANIFEST = require('./data/runtime-dependency-manifest.json');
12
+ const SOURCE_CONFIG = require('./data/runtime-dependency-sources.json');
13
+ const MAX_DOWNLOAD_BYTES = 512 * 1024 * 1024;
14
+ const DOWNLOAD_TIMEOUT_MS = 180_000;
15
+ const MIRROR_LOOKUP_TIMEOUT_MS = 3_000;
16
+ const LOCK_TIMEOUT_MS = 180_000;
17
+ const LOCK_STALE_MS = 10 * 60_000;
18
+ const LOCK_POLL_MS = 100;
19
+ const SAFE_SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
20
+ const AUTHORITATIVE_NPM_ORIGIN = new URL(SOURCE_CONFIG.authoritativeNpmRegistry).origin;
21
+
22
+ const DEPENDENCIES = Object.freeze([
23
+ {
24
+ id: 'codex',
25
+ envKeys: ['FARMING_CODEX_BIN', 'CODEX_PATH'],
26
+ commands: ['codex'],
27
+ },
28
+ {
29
+ id: 'claude',
30
+ envKeys: ['FARMING_CLAUDE_BIN', 'CLAUDE_CODE_EXECUTABLE'],
31
+ commands: ['claude'],
32
+ },
33
+ {
34
+ id: 'agentBrowser',
35
+ envKeys: ['FARMING_AGENT_BROWSER_BIN', 'FARMING_AGENT_BROWSER_EXECUTABLE'],
36
+ commands: ['agent-browser'],
37
+ allowSystem: false,
38
+ },
39
+ ]);
40
+
41
+ function delay(ms) {
42
+ return new Promise(resolve => setTimeout(resolve, ms));
43
+ }
44
+
45
+ function safeSegment(value, label) {
46
+ const text = String(value || '').trim();
47
+ if (!SAFE_SEGMENT.test(text) || text === '.' || text === '..') {
48
+ throw new Error(`Invalid runtime dependency ${label}`);
49
+ }
50
+ return text;
51
+ }
52
+
53
+ function safeRelative(value, label = 'entry') {
54
+ const text = String(value || '').replace(/\\/g, '/');
55
+ if (
56
+ !text
57
+ || path.posix.isAbsolute(text)
58
+ || text.split('/').some(part => !part || part === '.' || part === '..')
59
+ ) {
60
+ throw new Error(`Invalid runtime dependency ${label}`);
61
+ }
62
+ return text;
63
+ }
64
+
65
+ function isMuslRuntime() {
66
+ if (process.platform !== 'linux') return false;
67
+ if (process.report?.getReport) {
68
+ const report = process.report.getReport();
69
+ if (report?.header?.glibcVersionRuntime) return false;
70
+ }
71
+ return true;
72
+ }
73
+
74
+ function runtimePlatformKey(options = {}) {
75
+ const platform = safeSegment(options.platform || process.platform, 'platform');
76
+ const arch = safeSegment(options.arch || process.arch, 'architecture');
77
+ if (options.platformKey) return safeSegment(options.platformKey, 'platform key');
78
+ const musl = options.musl ?? (platform === process.platform && isMuslRuntime());
79
+ return platform === 'linux' && musl ? `${platform}-${arch}-musl` : `${platform}-${arch}`;
80
+ }
81
+
82
+ function dependencyCacheDir(configDir, id, version, platformKey) {
83
+ return path.join(
84
+ storageLayout.runtimeDependenciesDir(configDir),
85
+ safeSegment(id, 'id'),
86
+ safeSegment(version, 'version'),
87
+ safeSegment(platformKey, 'platform key'),
88
+ );
89
+ }
90
+
91
+ function fileSha256(filePath) {
92
+ return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
93
+ }
94
+
95
+ function parseIntegrity(integrity) {
96
+ const match = String(integrity || '').match(/^(sha256|sha512)-([A-Za-z0-9+/=]+)$/);
97
+ if (!match) throw new Error('Runtime artifact integrity must use sha256 or sha512 SRI');
98
+ return { algorithm: match[1], digest: Buffer.from(match[2], 'base64') };
99
+ }
100
+
101
+ function which(command, env = process.env) {
102
+ try {
103
+ const program = process.platform === 'win32' ? 'where.exe' : 'which';
104
+ const output = execFileSync(program, [command], {
105
+ encoding: 'utf8',
106
+ timeout: 1_000,
107
+ maxBuffer: 64 * 1024,
108
+ env,
109
+ });
110
+ return String(output).split(/\r?\n/).map(value => value.trim()).find(Boolean) || '';
111
+ } catch {
112
+ return '';
113
+ }
114
+ }
115
+
116
+ function semanticVersion(output) {
117
+ return String(output || '').match(/\b\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?\b/)?.[0] || '';
118
+ }
119
+
120
+ async function verifyExecutable(executablePath, expectedVersion, options = {}) {
121
+ const exec = options.execFile || execFile;
122
+ const args = options.args || ['--version'];
123
+ const invocation = options.useConfiguredLoader
124
+ ? runtimeExecutableInvocation(
125
+ executablePath,
126
+ args,
127
+ options.env || process.env,
128
+ options.platform || process.platform,
129
+ )
130
+ : { command: executablePath, args };
131
+ return new Promise(resolve => {
132
+ exec(invocation.command, invocation.args, {
133
+ encoding: 'utf8',
134
+ timeout: options.timeoutMs || 5_000,
135
+ maxBuffer: 1024 * 1024,
136
+ windowsHide: true,
137
+ env: options.env || process.env,
138
+ }, (error, stdout, stderr) => {
139
+ const output = `${stdout || ''}\n${stderr || ''}`.trim();
140
+ const version = semanticVersion(output);
141
+ resolve({
142
+ valid: !error && version === expectedVersion,
143
+ version,
144
+ output,
145
+ error: error?.message || '',
146
+ });
147
+ });
148
+ });
149
+ }
150
+
151
+ function explicitCandidate(dependency, env) {
152
+ for (const key of dependency.envKeys) {
153
+ const value = String(env[key] || '').trim();
154
+ if (value) return { path: path.resolve(value), key };
155
+ }
156
+ return null;
157
+ }
158
+
159
+ function systemCandidates(dependency, env) {
160
+ const explicit = explicitCandidate(dependency, env);
161
+ if (explicit) return [explicit];
162
+ return dependency.commands
163
+ .map(command => which(command, env))
164
+ .filter(Boolean)
165
+ .map(candidate => ({ path: path.resolve(candidate), key: '' }));
166
+ }
167
+
168
+ function resolutionEnvironment(env) {
169
+ if (
170
+ !env.FARMING_RUNTIME_MANIFEST_ID
171
+ || env.FARMING_RUNTIME_MANIFEST_ID === MANIFEST.manifestId
172
+ ) {
173
+ return env;
174
+ }
175
+ const resolved = { ...env };
176
+ for (const dependency of DEPENDENCIES) {
177
+ for (const key of dependency.envKeys) delete resolved[key];
178
+ }
179
+ delete resolved.FARMING_RUNTIME_MANIFEST_ID;
180
+ return resolved;
181
+ }
182
+
183
+ function managedRuntimeUsesConfiguredLoader(id) {
184
+ return id === 'agentBrowser';
185
+ }
186
+
187
+ function readJson(filePath) {
188
+ try {
189
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
190
+ } catch {
191
+ return null;
192
+ }
193
+ }
194
+
195
+ function writeJsonAtomic(filePath, value) {
196
+ const temporary = `${filePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
197
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
198
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, {
199
+ flag: 'wx',
200
+ mode: 0o600,
201
+ });
202
+ fs.renameSync(temporary, filePath);
203
+ }
204
+
205
+ function processRunning(pid) {
206
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
207
+ try {
208
+ process.kill(pid, 0);
209
+ return true;
210
+ } catch (error) {
211
+ return error?.code === 'EPERM' || error?.code === 'EACCES';
212
+ }
213
+ }
214
+
215
+ async function acquirePrepareLock(configDir, options = {}) {
216
+ const lockDir = storageLayout.runtimeDependenciesLockDir(configDir);
217
+ const startedAt = Date.now();
218
+ while (true) {
219
+ try {
220
+ fs.mkdirSync(lockDir, { recursive: false, mode: 0o700 });
221
+ writeJsonAtomic(path.join(lockDir, 'owner.json'), {
222
+ pid: process.pid,
223
+ token: options.token || crypto.randomUUID(),
224
+ createdAt: new Date().toISOString(),
225
+ });
226
+ return () => fs.rmSync(lockDir, { recursive: true, force: true });
227
+ } catch (error) {
228
+ if (error?.code !== 'EEXIST') {
229
+ if (error?.code === 'ENOENT') {
230
+ fs.mkdirSync(path.dirname(lockDir), { recursive: true });
231
+ continue;
232
+ }
233
+ throw error;
234
+ }
235
+ const owner = readJson(path.join(lockDir, 'owner.json'));
236
+ let ageMs = 0;
237
+ try {
238
+ ageMs = Date.now() - fs.statSync(lockDir).mtimeMs;
239
+ } catch {
240
+ continue;
241
+ }
242
+ if ((owner && !processRunning(Number(owner.pid))) || (!owner && ageMs >= LOCK_STALE_MS)) {
243
+ const stale = `${lockDir}.stale-${Date.now()}-${crypto.randomUUID()}`;
244
+ try {
245
+ fs.renameSync(lockDir, stale);
246
+ fs.rmSync(stale, { recursive: true, force: true });
247
+ continue;
248
+ } catch {
249
+ // Another starter recovered or replaced the lock first.
250
+ }
251
+ }
252
+ if (Date.now() - startedAt >= (options.lockTimeoutMs || LOCK_TIMEOUT_MS)) {
253
+ throw new Error(
254
+ 'Timed out waiting for another Farming startup dependency preparation',
255
+ { cause: error },
256
+ );
257
+ }
258
+ await (options.wait || delay)(options.lockPollMs || LOCK_POLL_MS);
259
+ }
260
+ }
261
+ }
262
+
263
+ function npmArtifactIdentity(artifactUrl) {
264
+ const artifact = new URL(artifactUrl);
265
+ const segments = artifact.pathname.split('/').filter(Boolean).map(decodeURIComponent);
266
+ const separator = segments.indexOf('-');
267
+ if (separator < 1 || separator !== segments.length - 2) {
268
+ throw new Error('Runtime artifact must use a standard npm tarball URL');
269
+ }
270
+ const packageName = segments.slice(0, separator).join('/');
271
+ const packageBase = packageName.split('/').pop();
272
+ const filename = segments[separator + 1];
273
+ const prefix = `${packageBase}-`;
274
+ if (!filename.startsWith(prefix) || !filename.endsWith('.tgz')) {
275
+ throw new Error('Runtime artifact tarball does not match its npm package');
276
+ }
277
+ return {
278
+ packageName,
279
+ version: filename.slice(prefix.length, -'.tgz'.length),
280
+ };
281
+ }
282
+
283
+ function configuredRuntimeNpmMirror(env) {
284
+ if (Object.prototype.hasOwnProperty.call(env, 'FARMING_RUNTIME_NPM_MIRROR')) {
285
+ const configured = String(env.FARMING_RUNTIME_NPM_MIRROR || '').trim();
286
+ if (!configured || /^(0|false|none|off)$/i.test(configured)) return '';
287
+ return configured;
288
+ }
289
+ return String(SOURCE_CONFIG.defaultNpmMirror || '').trim();
290
+ }
291
+
292
+ async function runtimeArtifactDownloadUrls(artifact, options = {}) {
293
+ const authoritative = new URL(artifact.url);
294
+ if (authoritative.origin !== AUTHORITATIVE_NPM_ORIGIN) {
295
+ throw new Error('Runtime artifact must use the authoritative public npm registry');
296
+ }
297
+ const env = options.env || process.env;
298
+ const configuredMirror = configuredRuntimeNpmMirror(env);
299
+ if (!configuredMirror) return [authoritative.href];
300
+ const mirror = new URL(configuredMirror);
301
+ if (
302
+ mirror.protocol !== 'https:'
303
+ || mirror.username
304
+ || mirror.password
305
+ || mirror.search
306
+ || mirror.hash
307
+ || !['', '/'].includes(mirror.pathname)
308
+ ) {
309
+ throw new Error('FARMING_RUNTIME_NPM_MIRROR must be an HTTPS registry origin');
310
+ }
311
+ if (mirror.origin === authoritative.origin) return [authoritative.href];
312
+
313
+ const { packageName, version } = npmArtifactIdentity(authoritative);
314
+ const metadataUrl = new URL(
315
+ `${encodeURIComponent(packageName)}/${encodeURIComponent(version)}`,
316
+ mirror,
317
+ );
318
+ const controller = new globalThis.AbortController();
319
+ const timeout = setTimeout(
320
+ () => controller.abort(),
321
+ options.mirrorLookupTimeoutMs || MIRROR_LOOKUP_TIMEOUT_MS,
322
+ );
323
+ timeout.unref?.();
324
+ try {
325
+ const response = await (options.fetch || fetch)(metadataUrl, {
326
+ headers: { accept: 'application/json' },
327
+ redirect: 'follow',
328
+ signal: controller.signal,
329
+ });
330
+ if (!response.ok) return [authoritative.href];
331
+ const metadata = await response.json();
332
+ if (metadata?.version !== version || metadata?.dist?.integrity !== artifact.integrity) {
333
+ return [authoritative.href];
334
+ }
335
+ const mirrored = new URL(metadata.dist.tarball);
336
+ if (mirrored.protocol !== 'https:' || mirrored.origin !== mirror.origin) {
337
+ return [authoritative.href];
338
+ }
339
+ return [mirrored.href, authoritative.href];
340
+ } catch {
341
+ return [authoritative.href];
342
+ } finally {
343
+ clearTimeout(timeout);
344
+ }
345
+ }
346
+
347
+ async function downloadArtifactFromUrl(artifact, url, destination, options = {}) {
348
+ const { algorithm, digest } = parseIntegrity(artifact.integrity);
349
+ const controller = new globalThis.AbortController();
350
+ const timeout = setTimeout(
351
+ () => controller.abort(),
352
+ options.downloadTimeoutMs || DOWNLOAD_TIMEOUT_MS,
353
+ );
354
+ timeout.unref?.();
355
+ const hash = crypto.createHash(algorithm);
356
+ let received = 0;
357
+ try {
358
+ const response = await (options.fetch || fetch)(url, {
359
+ redirect: 'follow',
360
+ signal: controller.signal,
361
+ });
362
+ if (!response.ok || !response.body) {
363
+ throw new Error(`Runtime download failed with HTTP ${response.status}`);
364
+ }
365
+ const expectedSize = Number(artifact.size) || 0;
366
+ const limit = expectedSize || MAX_DOWNLOAD_BYTES;
367
+ const meter = new Transform({
368
+ transform(chunk, _encoding, callback) {
369
+ received += chunk.length;
370
+ if (received > limit) {
371
+ callback(new Error(`Runtime download exceeded ${limit} bytes`));
372
+ return;
373
+ }
374
+ hash.update(chunk);
375
+ callback(null, chunk);
376
+ },
377
+ });
378
+ await pipeline(
379
+ Readable.fromWeb(response.body),
380
+ meter,
381
+ fs.createWriteStream(destination, { flags: 'wx', mode: 0o600 }),
382
+ );
383
+ if (expectedSize && received !== expectedSize) {
384
+ throw new Error(`Runtime download size mismatch: expected ${expectedSize}, received ${received}`);
385
+ }
386
+ if (!crypto.timingSafeEqual(hash.digest(), digest)) {
387
+ throw new Error('Runtime artifact failed integrity verification');
388
+ }
389
+ } catch (error) {
390
+ fs.rmSync(destination, { force: true });
391
+ if (error?.name === 'AbortError') throw new Error('Runtime download timed out', { cause: error });
392
+ throw error;
393
+ } finally {
394
+ clearTimeout(timeout);
395
+ }
396
+ }
397
+
398
+ async function downloadArtifact(artifact, destination, options = {}) {
399
+ const urls = await runtimeArtifactDownloadUrls(artifact, options);
400
+ for (const [index, url] of urls.entries()) {
401
+ try {
402
+ await downloadArtifactFromUrl(artifact, url, destination, options);
403
+ return;
404
+ } catch (error) {
405
+ if (index === urls.length - 1) throw error;
406
+ console.warn(
407
+ `Runtime npm mirror download failed; retrying the authoritative npm registry: ${error.message}`,
408
+ );
409
+ }
410
+ }
411
+ }
412
+
413
+ async function extractArtifact(artifact, archivePath, stagingDir) {
414
+ const entry = safeRelative(artifact.entry);
415
+ if (artifact.archive === 'file') {
416
+ const destination = path.join(stagingDir, entry);
417
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
418
+ fs.renameSync(archivePath, destination);
419
+ return destination;
420
+ }
421
+ if (artifact.archive !== 'tgz') throw new Error(`Unsupported runtime archive: ${artifact.archive}`);
422
+ if (artifact.archiveEntry) {
423
+ const archiveEntry = safeRelative(artifact.archiveEntry, 'archive entry');
424
+ const extractionDir = path.join(stagingDir, '.artifact');
425
+ const extractedName = path.posix.basename(archiveEntry);
426
+ fs.mkdirSync(extractionDir, { recursive: true });
427
+ await tar.x({
428
+ cwd: extractionDir,
429
+ file: archivePath,
430
+ gzip: true,
431
+ preserveOwner: false,
432
+ strict: true,
433
+ strip: archiveEntry.split('/').length - 1,
434
+ filter: candidate => candidate === archiveEntry,
435
+ });
436
+ const extractedPath = path.join(extractionDir, extractedName);
437
+ const extractedStat = fs.lstatSync(extractedPath);
438
+ if (!extractedStat.isFile() || extractedStat.isSymbolicLink()) {
439
+ throw new Error('Runtime archive entry must be a regular file');
440
+ }
441
+ const destination = path.join(stagingDir, entry);
442
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
443
+ fs.renameSync(extractedPath, destination);
444
+ fs.rmSync(extractionDir, { recursive: true, force: true });
445
+ fs.rmSync(archivePath, { force: true });
446
+ return destination;
447
+ }
448
+ const prefix = safeRelative(artifact.archivePrefix, 'archive prefix');
449
+ const prefixWithSlash = `${prefix}/`;
450
+ await tar.x({
451
+ cwd: stagingDir,
452
+ file: archivePath,
453
+ gzip: true,
454
+ preserveOwner: false,
455
+ strict: true,
456
+ strip: prefix.split('/').length,
457
+ filter: archiveEntry => archiveEntry === prefix || archiveEntry.startsWith(prefixWithSlash),
458
+ });
459
+ fs.rmSync(archivePath, { force: true });
460
+ const executablePath = path.resolve(stagingDir, entry);
461
+ if (!executablePath.startsWith(`${path.resolve(stagingDir)}${path.sep}`)) {
462
+ throw new Error('Runtime executable escaped the staging directory');
463
+ }
464
+ const realExecutablePath = fs.realpathSync(executablePath);
465
+ const executableStat = fs.lstatSync(executablePath);
466
+ if (
467
+ !executableStat.isFile()
468
+ || executableStat.isSymbolicLink()
469
+ || !realExecutablePath.startsWith(`${fs.realpathSync(stagingDir)}${path.sep}`)
470
+ ) {
471
+ throw new Error('Runtime executable must be a regular file inside the staging directory');
472
+ }
473
+ return executablePath;
474
+ }
475
+
476
+ function dependencyManifest(id, platformKey) {
477
+ if (MANIFEST.schemaVersion !== 1 || !MANIFEST.manifestId) {
478
+ throw new Error('Runtime dependency manifest is invalid');
479
+ }
480
+ const dependency = MANIFEST.dependencies?.[id];
481
+ const artifact = dependency?.artifacts?.[platformKey];
482
+ if (!dependency || !artifact) {
483
+ throw new Error(`${id} has no runtime artifact for ${platformKey}`);
484
+ }
485
+ parseIntegrity(artifact.integrity);
486
+ safeRelative(artifact.entry);
487
+ if (artifact.archive === 'tgz') {
488
+ if (artifact.archiveEntry) safeRelative(artifact.archiveEntry, 'archive entry');
489
+ else safeRelative(artifact.archivePrefix, 'archive prefix');
490
+ }
491
+ return { dependency, artifact };
492
+ }
493
+
494
+ async function resolveCachedRuntime(configDir, id, platformKey, options = {}) {
495
+ const { dependency, artifact } = dependencyManifest(id, platformKey);
496
+ const cacheDir = dependencyCacheDir(configDir, id, dependency.version, platformKey);
497
+ const record = readJson(path.join(cacheDir, 'runtime.json'));
498
+ const executablePath = path.resolve(cacheDir, artifact.entry);
499
+ if (
500
+ !record
501
+ || record.schemaVersion !== 1
502
+ || record.manifestId !== MANIFEST.manifestId
503
+ || record.id !== id
504
+ || record.version !== dependency.version
505
+ || record.platformKey !== platformKey
506
+ || record.integrity !== artifact.integrity
507
+ || record.entry !== artifact.entry
508
+ || !fs.existsSync(executablePath)
509
+ || fileSha256(executablePath) !== record.executableSha256
510
+ ) {
511
+ return null;
512
+ }
513
+ if (dependency.managedProbe !== false) {
514
+ const verification = await verifyExecutable(
515
+ executablePath,
516
+ dependency.reportedVersion || dependency.version,
517
+ {
518
+ args: dependency.probe?.args,
519
+ env: options.env,
520
+ useConfiguredLoader: managedRuntimeUsesConfiguredLoader(id),
521
+ },
522
+ );
523
+ if (!verification.valid) return null;
524
+ }
525
+ return { id, version: dependency.version, source: 'managed', executablePath };
526
+ }
527
+
528
+ async function findExactRuntime(configDir, definition, platformKey, env) {
529
+ const { dependency } = dependencyManifest(definition.id, platformKey);
530
+ const expectedVersion = dependency.reportedVersion || dependency.version;
531
+ const candidates = definition.allowSystem === false ? [] : systemCandidates(definition, env);
532
+ for (const candidate of candidates) {
533
+ if (!fs.existsSync(candidate.path)) {
534
+ if (candidate.key) {
535
+ throw new Error(`${candidate.key} points to a missing executable: ${candidate.path}`);
536
+ }
537
+ continue;
538
+ }
539
+ const verification = await verifyExecutable(candidate.path, expectedVersion, {
540
+ args: dependency.probe?.args,
541
+ env,
542
+ });
543
+ if (verification.valid) {
544
+ return {
545
+ id: definition.id,
546
+ version: dependency.version,
547
+ reportedVersion: expectedVersion,
548
+ source: 'system',
549
+ executablePath: candidate.path,
550
+ };
551
+ }
552
+ if (candidate.key) {
553
+ throw new Error(
554
+ `${candidate.key} must provide ${definition.id} ${expectedVersion}; `
555
+ + `found ${verification.version || 'an unverifiable executable'}`,
556
+ );
557
+ }
558
+ }
559
+ return resolveCachedRuntime(configDir, definition.id, platformKey, { env });
560
+ }
561
+
562
+ async function installExactRuntime(configDir, definition, platformKey, options = {}) {
563
+ const { dependency, artifact } = dependencyManifest(definition.id, platformKey);
564
+ const cacheDir = dependencyCacheDir(configDir, definition.id, dependency.version, platformKey);
565
+ const stagingDir = `${cacheDir}.preparing-${process.pid}-${crypto.randomUUID()}`;
566
+ const archivePath = path.join(stagingDir, 'artifact.download');
567
+ const quarantine = `${cacheDir}.invalid-${Date.now()}-${crypto.randomUUID()}`;
568
+ fs.mkdirSync(stagingDir, { recursive: true, mode: 0o700 });
569
+ try {
570
+ await downloadArtifact(artifact, archivePath, options);
571
+ const executablePath = await extractArtifact(artifact, archivePath, stagingDir);
572
+ if (!fs.existsSync(executablePath)) throw new Error(`${definition.id} archive omitted ${artifact.entry}`);
573
+ fs.chmodSync(executablePath, 0o700);
574
+ if (dependency.managedProbe !== false) {
575
+ const verification = await verifyExecutable(
576
+ executablePath,
577
+ dependency.reportedVersion || dependency.version,
578
+ {
579
+ args: dependency.probe?.args,
580
+ env: options.env,
581
+ useConfiguredLoader: managedRuntimeUsesConfiguredLoader(definition.id),
582
+ },
583
+ );
584
+ if (!verification.valid) {
585
+ throw new Error(
586
+ `${definition.id} runtime reported ${verification.version || 'no version'}; `
587
+ + `expected ${dependency.reportedVersion || dependency.version}`,
588
+ );
589
+ }
590
+ }
591
+ writeJsonAtomic(path.join(stagingDir, 'runtime.json'), {
592
+ schemaVersion: 1,
593
+ manifestId: MANIFEST.manifestId,
594
+ id: definition.id,
595
+ version: dependency.version,
596
+ platformKey,
597
+ integrity: artifact.integrity,
598
+ entry: artifact.entry,
599
+ executableSha256: fileSha256(executablePath),
600
+ installedAt: new Date().toISOString(),
601
+ });
602
+ const hadCache = fs.existsSync(cacheDir);
603
+ if (hadCache) fs.renameSync(cacheDir, quarantine);
604
+ try {
605
+ fs.renameSync(stagingDir, cacheDir);
606
+ } catch (error) {
607
+ if (hadCache && !fs.existsSync(cacheDir) && fs.existsSync(quarantine)) {
608
+ fs.renameSync(quarantine, cacheDir);
609
+ }
610
+ throw error;
611
+ }
612
+ fs.rmSync(quarantine, { recursive: true, force: true });
613
+ } catch (error) {
614
+ fs.rmSync(stagingDir, { recursive: true, force: true });
615
+ throw error;
616
+ }
617
+ const resolved = await resolveCachedRuntime(
618
+ configDir,
619
+ definition.id,
620
+ platformKey,
621
+ { env: options.env },
622
+ );
623
+ if (!resolved) throw new Error(`${definition.id} runtime did not pass post-install verification`);
624
+ return resolved;
625
+ }
626
+
627
+ function applyRuntimeEnvironment(env, prepared) {
628
+ const byId = new Map(prepared.map(item => [item.id, item]));
629
+ const codex = byId.get('codex')?.executablePath;
630
+ const claude = byId.get('claude')?.executablePath;
631
+ const agentBrowser = byId.get('agentBrowser')?.executablePath;
632
+ if (codex) {
633
+ env.FARMING_CODEX_BIN = codex;
634
+ env.CODEX_PATH = codex;
635
+ }
636
+ if (claude) {
637
+ env.FARMING_CLAUDE_BIN = claude;
638
+ env.CLAUDE_CODE_EXECUTABLE = claude;
639
+ }
640
+ if (agentBrowser) {
641
+ env.FARMING_AGENT_BROWSER_BIN = agentBrowser;
642
+ env.FARMING_AGENT_BROWSER_EXECUTABLE = agentBrowser;
643
+ }
644
+ env.FARMING_RUNTIME_MANIFEST_ID = MANIFEST.manifestId;
645
+ return env;
646
+ }
647
+
648
+ async function prepareRuntimeDependencies(options = {}) {
649
+ const env = options.env || process.env;
650
+ const candidateEnv = resolutionEnvironment(env);
651
+ const configDir = options.configDir || storageLayout.farmingConfigDir(env);
652
+ const platformKey = runtimePlatformKey(options);
653
+ fs.mkdirSync(storageLayout.runtimeDependenciesDir(configDir), { recursive: true });
654
+ const releaseLock = await acquirePrepareLock(configDir, options);
655
+ const prepared = [];
656
+ try {
657
+ for (const definition of DEPENDENCIES) {
658
+ let runtime = await findExactRuntime(configDir, definition, platformKey, candidateEnv);
659
+ if (!runtime) {
660
+ const installRuntime = options.installRuntime || installExactRuntime;
661
+ runtime = await installRuntime(configDir, definition, platformKey, options);
662
+ }
663
+ prepared.push(runtime);
664
+ }
665
+ applyRuntimeEnvironment(env, prepared);
666
+ writeJsonAtomic(storageLayout.runtimeDependenciesActiveFile(configDir), {
667
+ schemaVersion: 1,
668
+ manifestId: MANIFEST.manifestId,
669
+ platformKey,
670
+ dependencies: Object.fromEntries(prepared.map(item => [item.id, {
671
+ version: item.version,
672
+ source: item.source,
673
+ executablePath: item.executablePath,
674
+ }])),
675
+ preparedAt: new Date().toISOString(),
676
+ });
677
+ return { manifestId: MANIFEST.manifestId, platformKey, dependencies: prepared };
678
+ } finally {
679
+ releaseLock();
680
+ }
681
+ }
682
+
683
+ async function pruneRuntimeDependencies(options = {}) {
684
+ const env = options.env || process.env;
685
+ const configDir = options.configDir || storageLayout.farmingConfigDir(env);
686
+ const active = readJson(storageLayout.runtimeDependenciesActiveFile(configDir));
687
+ if (!active || active.manifestId !== MANIFEST.manifestId) return { removed: [] };
688
+ const platformKey = safeSegment(active.platformKey, 'platform key');
689
+ const releaseLock = await acquirePrepareLock(configDir, options);
690
+ const removed = [];
691
+ try {
692
+ const latest = readJson(storageLayout.runtimeDependenciesActiveFile(configDir));
693
+ if (!latest || latest.manifestId !== MANIFEST.manifestId) return { removed };
694
+ for (const definition of DEPENDENCIES) {
695
+ const dependencyRoot = path.join(
696
+ storageLayout.runtimeDependenciesDir(configDir),
697
+ safeSegment(definition.id, 'id'),
698
+ );
699
+ if (!fs.existsSync(dependencyRoot)) continue;
700
+ const dependencyRootStat = fs.lstatSync(dependencyRoot);
701
+ if (!dependencyRootStat.isDirectory() || dependencyRootStat.isSymbolicLink()) {
702
+ fs.rmSync(dependencyRoot, { recursive: true, force: true });
703
+ removed.push(dependencyRoot);
704
+ continue;
705
+ }
706
+ const activeDependency = latest.dependencies?.[definition.id];
707
+ const keepDir = activeDependency?.source === 'managed'
708
+ ? dependencyCacheDir(
709
+ configDir,
710
+ definition.id,
711
+ MANIFEST.dependencies[definition.id].version,
712
+ platformKey,
713
+ )
714
+ : '';
715
+ const keepVersionDir = keepDir ? path.dirname(keepDir) : '';
716
+ for (const versionEntry of fs.readdirSync(dependencyRoot, { withFileTypes: true })) {
717
+ const versionDir = path.join(dependencyRoot, versionEntry.name);
718
+ if (
719
+ !versionEntry.isDirectory()
720
+ || !keepDir
721
+ || path.resolve(versionDir) !== path.resolve(keepVersionDir)
722
+ ) {
723
+ fs.rmSync(versionDir, { recursive: true, force: true });
724
+ removed.push(versionDir);
725
+ continue;
726
+ }
727
+ for (const platformEntry of fs.readdirSync(versionDir, { withFileTypes: true })) {
728
+ const platformDir = path.join(versionDir, platformEntry.name);
729
+ if (
730
+ platformEntry.isDirectory()
731
+ && path.resolve(platformDir) === path.resolve(keepDir)
732
+ ) continue;
733
+ fs.rmSync(platformDir, { recursive: true, force: true });
734
+ removed.push(platformDir);
735
+ }
736
+ }
737
+ if (fs.readdirSync(dependencyRoot).length === 0) fs.rmdirSync(dependencyRoot);
738
+ }
739
+ return { removed };
740
+ } finally {
741
+ releaseLock();
742
+ }
743
+ }
744
+
745
+ module.exports = {
746
+ DEPENDENCIES,
747
+ MANIFEST,
748
+ SOURCE_CONFIG,
749
+ applyRuntimeEnvironment,
750
+ dependencyCacheDir,
751
+ downloadArtifact,
752
+ extractArtifact,
753
+ managedRuntimeUsesConfiguredLoader,
754
+ prepareRuntimeDependencies,
755
+ pruneRuntimeDependencies,
756
+ runtimeArtifactDownloadUrls,
757
+ runtimePlatformKey,
758
+ verifyExecutable,
759
+ };