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
@@ -8,6 +8,12 @@ const { URLSearchParams } = require('url');
8
8
  const { execFileSync, spawn } = require('child_process');
9
9
  const { run: runControlCli } = require('./farming-cli');
10
10
  const { PACKAGED_CODEX_ACP_ARG, runPackagedCodexAcp } = require('./acp/packaged-codex-acp');
11
+ const { PACKAGED_CLAUDE_ACP_ARG, runPackagedClaudeAcp } = require('./acp/packaged-claude-acp');
12
+ const {
13
+ SERVER_PROCESS_IDENTITY_FORMAT,
14
+ matchingProcessIdentity,
15
+ readServerProcessIdentity,
16
+ } = require('./server-process-identity');
11
17
  const storageLayout = require('./storage-layout');
12
18
 
13
19
  const SERVER_MODE_ARG = '--farming-server';
@@ -20,7 +26,6 @@ const DEFAULT_SERVER_START_TIMEOUT_MS = 30_000;
20
26
  const DEFAULT_SERVER_START_STABILITY_MS = 1_500;
21
27
  const DEFAULT_SERVER_STOP_TIMEOUT_MS = 30_000;
22
28
  const SERVER_STOP_POLL_MS = 100;
23
- const SERVER_PROCESS_IDENTITY_FORMAT = 'ps-lstart-c-utc-v1';
24
29
  const SERVER_COMMANDS = new Set(['start', 'serve', 'daemon', 'stop', 'status', 'logs', 'url', 'help']);
25
30
  const CONTROL_COMMANDS = new Set(['skills', 'capabilities', 'memory', 'report', 'list', 'spawn', 'output', 'send', 'kill']);
26
31
  const SERVER_BACKED_CONTROL_COMMANDS = new Set(['capabilities', 'list', 'spawn', 'output', 'send', 'kill']);
@@ -437,7 +442,9 @@ function childInvocation(env = process.env) {
437
442
  // making daemon ownership impossible to prove on Linux.
438
443
  return {
439
444
  command: '/usr/bin/env',
440
- args: buildCleanEnvExecArgs(env, process.execPath, ['--']),
445
+ // FARMING_RUN_SERVER selects the embedded server entry. Do not append a
446
+ // sentinel argument: pkg may interpret it as an external script path.
447
+ args: buildCleanEnvExecArgs(env, process.execPath),
441
448
  };
442
449
  }
443
450
  const nodePath = env.FARMING_NODE_BIN || process.execPath;
@@ -482,45 +489,20 @@ function canonicalConfigDir(configDir) {
482
489
  }
483
490
  }
484
491
 
485
- async function readServerProcessIdentity(pid) {
486
- const processId = Number(pid);
487
- if (!Number.isSafeInteger(processId) || processId <= 0 || process.platform === 'win32') return null;
488
- let stdout;
489
- try {
490
- stdout = execFileSync(
491
- '/bin/ps',
492
- ['-p', String(processId), '-o', 'pid=', '-o', 'pgid=', '-o', 'lstart='],
493
- {
494
- encoding: 'utf8',
495
- timeout: 1_000,
496
- maxBuffer: 16_384,
497
- env: { ...process.env, LANG: 'C', LC_ALL: 'C', TZ: 'UTC' },
498
- },
499
- );
500
- } catch (error) {
501
- if (error?.status === 1 || error?.code === 'ESRCH') return null;
502
- throw error;
503
- }
504
- const match = String(stdout || '').trim().match(/^(\d+)\s+(\d+)\s+(.+)$/);
505
- if (!match || Number(match[1]) !== processId) return null;
506
- return {
507
- pid: processId,
508
- processGroupId: Number(match[2]),
509
- startedAt: match[3].trim(),
510
- format: SERVER_PROCESS_IDENTITY_FORMAT,
511
- };
512
- }
513
-
514
- function writeServerState(configDir, env, pid, processIdentity) {
492
+ function writeServerState(configDir, env, pid, processIdentity, phase = 'running') {
515
493
  const state = {
516
494
  pid,
517
495
  port: Number(env.PORT || DEFAULT_PORT),
518
496
  basePath: env.FARMING_BASE_PATH || DEFAULT_BASE_PATH,
519
497
  configDir: canonicalConfigDir(configDir),
520
498
  processIdentity,
499
+ phase,
521
500
  updatedAt: new Date().toISOString(),
522
501
  };
523
- fs.writeFileSync(serverStateFile(configDir), `${JSON.stringify(state, null, 2)}\n`);
502
+ const target = serverStateFile(configDir);
503
+ const temporary = `${target}.${process.pid}.tmp`;
504
+ fs.writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
505
+ fs.renameSync(temporary, target);
524
506
  }
525
507
 
526
508
  function processLooksLikeFarmingServer(pid) {
@@ -664,15 +646,6 @@ function processOwnsListeningPort(pid, port) {
664
646
  }
665
647
  }
666
648
 
667
- function matchingProcessIdentity(expected, current) {
668
- return Boolean(
669
- current
670
- && current.pid === Number(expected?.pid)
671
- && current.processGroupId === Number(expected?.processGroupId)
672
- && current.startedAt === String(expected?.startedAt || '')
673
- );
674
- }
675
-
676
649
  async function assertServerProcessIdentity(configDir, pid, state) {
677
650
  const expected = state?.processIdentity;
678
651
  if (
@@ -694,7 +667,7 @@ async function assertServerProcessIdentity(configDir, pid, state) {
694
667
  `Refusing to stop Farming PID ${pid}: the live process identity does not match the server control metadata`,
695
668
  );
696
669
  }
697
- if (!processOwnsListeningPort(pid, Number(state.port))) {
670
+ if (state.phase !== 'starting' && !processOwnsListeningPort(pid, Number(state.port))) {
698
671
  throw new Error(`Refusing to stop Farming PID ${pid}: the process does not own listening port ${state.port}`);
699
672
  }
700
673
  return current;
@@ -752,7 +725,8 @@ function isRunning(pid) {
752
725
  try {
753
726
  process.kill(pid, 0);
754
727
  return true;
755
- } catch {
728
+ } catch (error) {
729
+ if (error?.code === 'EPERM' || error?.code === 'EACCES') return true;
756
730
  return false;
757
731
  }
758
732
  }
@@ -840,12 +814,31 @@ function waitForProcessStability(pid, durationMs = DEFAULT_SERVER_START_STABILIT
840
814
  });
841
815
  }
842
816
 
843
- function cleanupFailedDaemonStart(configDir, childPid) {
817
+ async function cleanupFailedDaemonStart(configDir, childPid, expectedIdentity = null) {
844
818
  if (isRunning(childPid)) {
819
+ const expected = expectedIdentity || readServerState(configDir).processIdentity;
820
+ const current = readServerProcessIdentity(childPid);
821
+ if (!matchingProcessIdentity(expected, current)) {
822
+ throw new Error(`Failed Farming startup left live PID ${childPid} with an unproved identity; refusing to signal it`);
823
+ }
845
824
  try {
846
- process.kill(childPid, 'SIGTERM');
847
- } catch {
848
- // The child may exit between the liveness check and the signal.
825
+ process.kill(childPid, 'SIGKILL');
826
+ } catch (error) {
827
+ if (error?.code === 'EPERM' || error?.code === 'EACCES') {
828
+ throw new Error(
829
+ `Failed Farming startup left Server PID ${childPid} running because cleanup lacks permission. `
830
+ + 'Stop it as the operating-system user that owns the process, then retry.',
831
+ { cause: error },
832
+ );
833
+ }
834
+ if (error?.code !== 'ESRCH') throw error;
835
+ }
836
+ const startedAt = Date.now();
837
+ while (matchingProcessIdentity(expected, readServerProcessIdentity(childPid))) {
838
+ if (Date.now() - startedAt >= 5_000) {
839
+ throw new Error(`Failed Farming startup left Server PID ${childPid} running after SIGKILL`);
840
+ }
841
+ await new Promise(resolve => setTimeout(resolve, SERVER_STOP_POLL_MS));
849
842
  }
850
843
  }
851
844
  if (readPid(configDir) !== childPid) return;
@@ -910,10 +903,31 @@ function waitForServer(env, timeoutMs = serverStartTimeoutMs(env), childPid = 0)
910
903
  });
911
904
  }
912
905
 
913
- function runServerInCurrentProcess() {
906
+ async function runServerInCurrentProcess() {
914
907
  process.env = buildServerEnv();
908
+ ensureConfigDir(process.env.FARMING_CONFIG_DIR);
909
+ fs.writeFileSync(pidFile(process.env.FARMING_CONFIG_DIR), String(process.pid), { mode: 0o600 });
910
+ const processIdentity = await readServerProcessIdentity(process.pid);
911
+ if (!processIdentity) throw new Error('server process identity could not be committed before startup');
912
+ writeServerState(process.env.FARMING_CONFIG_DIR, process.env, process.pid, processIdentity, 'starting');
915
913
  const { startServer } = require('./server');
916
- startServer();
914
+ const server = startServer();
915
+ server.once('listening', () => {
916
+ writeServerState(
917
+ process.env.FARMING_CONFIG_DIR,
918
+ process.env,
919
+ process.pid,
920
+ processIdentity,
921
+ 'running',
922
+ );
923
+ const { pruneRuntimeDependencies } = require('./runtime-dependency-manager');
924
+ void pruneRuntimeDependencies({
925
+ configDir: process.env.FARMING_CONFIG_DIR,
926
+ env: process.env,
927
+ }).catch(error => {
928
+ console.warn(`Startup dependency cache cleanup failed: ${error?.message || error}`);
929
+ });
930
+ });
917
931
  }
918
932
 
919
933
  function runNativePtyHostInCurrentProcess() {
@@ -921,8 +935,24 @@ function runNativePtyHostInCurrentProcess() {
921
935
  startNativePtyHostProcess();
922
936
  }
923
937
 
938
+ async function prepareStartupDependencies(env, options = {}) {
939
+ if (
940
+ options.force !== true
941
+ && (env.FARMING_SKIP_RUNTIME_PREPARE === '1' || env.NODE_ENV === 'test')
942
+ ) {
943
+ return { skipped: true };
944
+ }
945
+ const { prepareRuntimeDependencies } = require('./runtime-dependency-manager');
946
+ return prepareRuntimeDependencies({
947
+ configDir: env.FARMING_CONFIG_DIR,
948
+ env,
949
+ });
950
+ }
951
+
924
952
  async function startForeground(parsed) {
925
- const env = await adaptServerPort(buildServerEnv(parsed.env), parsed);
953
+ const env = buildServerEnv(parsed.env);
954
+ await prepareStartupDependencies(env);
955
+ await adaptServerPort(env, parsed);
926
956
  env[SERVER_MODE_ENV] = '1';
927
957
  ensureConfigDir(env.FARMING_CONFIG_DIR);
928
958
  const invocation = childInvocation(env);
@@ -952,13 +982,33 @@ async function startDaemon(parsed) {
952
982
  const existingPid = readPid(configDir);
953
983
  if (isRunning(existingPid)) {
954
984
  const state = readServerState(configDir);
955
- if (state.port) env.PORT = String(state.port);
956
- if (state.basePath) env.FARMING_BASE_PATH = state.basePath;
957
- console.log(`Farming is already running (PID ${existingPid})`);
958
- console.log(entryUrl(env));
959
- return 0;
985
+ try {
986
+ if (state.processIdentity?.format === SERVER_PROCESS_IDENTITY_FORMAT) {
987
+ await assertServerProcessIdentity(configDir, existingPid, state);
988
+ } else {
989
+ await migrateLegacyServerIdentity(configDir, existingPid, state);
990
+ }
991
+ } catch (error) {
992
+ console.error(
993
+ `Farming PID ${existingPid} is live, but this config directory does not prove that it owns the Server: `
994
+ + `${error.message || error}`,
995
+ );
996
+ return 1;
997
+ }
998
+ if (state.phase === 'starting') {
999
+ console.warn(`Previous Farming startup (PID ${existingPid}) did not complete; replacing it.`);
1000
+ const stopCode = await stopDaemon({ env });
1001
+ if (stopCode !== 0) return stopCode;
1002
+ } else {
1003
+ if (state.port) env.PORT = String(state.port);
1004
+ if (state.basePath) env.FARMING_BASE_PATH = state.basePath;
1005
+ console.log(`Farming is already running (PID ${existingPid})`);
1006
+ console.log(entryUrl(env));
1007
+ return 0;
1008
+ }
960
1009
  }
961
1010
 
1011
+ await prepareStartupDependencies(env);
962
1012
  const out = fs.openSync(logFile(configDir), 'a');
963
1013
  const invocation = childInvocation(env);
964
1014
  if (env.FARMING_DEBUG_CLI === '1') {
@@ -979,9 +1029,11 @@ async function startDaemon(parsed) {
979
1029
  child.unref();
980
1030
  fs.writeFileSync(pidFile(configDir), String(child.pid));
981
1031
 
1032
+ let processIdentity = null;
982
1033
  try {
983
- const processIdentity = await readServerProcessIdentity(child.pid);
1034
+ processIdentity = await readServerProcessIdentity(child.pid);
984
1035
  if (!processIdentity) throw new Error('server process identity could not be verified after launch');
1036
+ writeServerState(configDir, env, child.pid, processIdentity, 'starting');
985
1037
  await waitForServer(env, serverStartTimeoutMs(env), child.pid);
986
1038
  await waitForProcessStability(child.pid, serverStartStabilityMs(env));
987
1039
  await waitForServer(env, Math.min(serverStartTimeoutMs(env), 5_000), child.pid);
@@ -993,9 +1045,14 @@ async function startDaemon(parsed) {
993
1045
  ) {
994
1046
  throw new Error('server process identity changed during startup');
995
1047
  }
996
- writeServerState(configDir, env, child.pid, stableIdentity);
1048
+ writeServerState(configDir, env, child.pid, stableIdentity, 'running');
997
1049
  } catch (error) {
998
- cleanupFailedDaemonStart(configDir, child.pid);
1050
+ try {
1051
+ await cleanupFailedDaemonStart(configDir, child.pid, processIdentity);
1052
+ } catch (cleanupError) {
1053
+ console.error(`${error.message}; cleanup failed: ${cleanupError.message || cleanupError}`);
1054
+ return 1;
1055
+ }
999
1056
  console.error(error.message);
1000
1057
  const logs = tailFile(logFile(configDir), 80);
1001
1058
  if (logs) console.error(logs);
@@ -1031,8 +1088,15 @@ async function stopDaemon(parsed) {
1031
1088
  await migrateLegacyServerIdentity(configDir, pid, state);
1032
1089
  }
1033
1090
  try {
1034
- process.kill(pid, 'SIGTERM');
1091
+ process.kill(pid, 'SIGKILL');
1035
1092
  } catch (error) {
1093
+ if (error?.code === 'EPERM' || error?.code === 'EACCES') {
1094
+ throw new Error(
1095
+ `Farming cannot stop server ${pid} because this command lacks permission. `
1096
+ + 'Run it as the operating-system user that owns the process (or as an administrator), then start Farming again.',
1097
+ { cause: error },
1098
+ );
1099
+ }
1036
1100
  if (error?.code !== 'ESRCH') throw error;
1037
1101
  }
1038
1102
  await waitForDaemonStop(pid, port, { timeoutMs: serverStopTimeoutMs(env) });
@@ -1042,7 +1106,7 @@ async function stopDaemon(parsed) {
1042
1106
  return 0;
1043
1107
  }
1044
1108
 
1045
- function statusDaemon(parsed) {
1109
+ async function statusDaemon(parsed) {
1046
1110
  const env = buildServerEnv(parsed.env);
1047
1111
  const configDir = env.FARMING_CONFIG_DIR;
1048
1112
  const pid = readPid(configDir);
@@ -1050,6 +1114,24 @@ function statusDaemon(parsed) {
1050
1114
  console.log('Farming is not running.');
1051
1115
  return 0;
1052
1116
  }
1117
+ const state = readServerState(configDir);
1118
+ try {
1119
+ if (state.processIdentity?.format === SERVER_PROCESS_IDENTITY_FORMAT) {
1120
+ await assertServerProcessIdentity(configDir, pid, state);
1121
+ } else {
1122
+ await migrateLegacyServerIdentity(configDir, pid, state);
1123
+ }
1124
+ } catch (error) {
1125
+ console.error(
1126
+ `Farming PID ${pid} is live, but this config directory does not prove that it owns the Server: `
1127
+ + `${error.message || error}`,
1128
+ );
1129
+ return 1;
1130
+ }
1131
+ if (state.phase === 'starting') {
1132
+ console.log(`Farming is starting (PID ${pid}). Run 'farming start' to replace an interrupted startup.`);
1133
+ return 1;
1134
+ }
1053
1135
  console.log(`Farming is running (PID ${pid})`);
1054
1136
  const logs = tailFile(logFile(configDir), 30);
1055
1137
  if (logs) console.log(logs);
@@ -1082,12 +1164,13 @@ function usage() {
1082
1164
  farming stop
1083
1165
  farming logs
1084
1166
  farming url
1167
+ farming runtime prepare [--config-dir ~/.farming]
1085
1168
  farming review <git-dir> <old-revision> <new-revision|now> [--branch <branch>] [--no-open]
1086
1169
 
1087
1170
  Agent control commands are also available:
1088
1171
  farming skills
1089
1172
  farming capabilities [--json]
1090
- farming browser <capability|create|list|start|stop|snapshot|navigate|click|fill|type|press|scroll|screenshot> ...
1173
+ farming browser ...
1091
1174
  farming list [--json] [--parent <agentId>]
1092
1175
  farming spawn --workspace <repo> -- <command...>
1093
1176
  farming output <agentId> [--tail <chars>]
@@ -1106,7 +1189,12 @@ async function run(argv = process.argv.slice(2)) {
1106
1189
  }
1107
1190
 
1108
1191
  if (argv[0] === PACKAGED_CODEX_ACP_ARG) {
1109
- runPackagedCodexAcp();
1192
+ await runPackagedCodexAcp();
1193
+ return 0;
1194
+ }
1195
+
1196
+ if (argv[0] === PACKAGED_CLAUDE_ACP_ARG) {
1197
+ await runPackagedClaudeAcp();
1110
1198
  return 0;
1111
1199
  }
1112
1200
 
@@ -1123,7 +1211,7 @@ async function run(argv = process.argv.slice(2)) {
1123
1211
  }
1124
1212
 
1125
1213
  if (process.env[SERVER_MODE_ENV] === '1' || argv[0] === SERVER_MODE_ARG) {
1126
- runServerInCurrentProcess();
1214
+ await runServerInCurrentProcess();
1127
1215
  return 0;
1128
1216
  }
1129
1217
 
@@ -1132,6 +1220,14 @@ async function run(argv = process.argv.slice(2)) {
1132
1220
  return runBrowserCli(argv.slice(1));
1133
1221
  }
1134
1222
 
1223
+ if (argv[0] === 'runtime' && argv[1] === 'prepare') {
1224
+ const parsed = parseServerArgs(['start', ...argv.slice(2)]);
1225
+ const env = buildServerEnv(parsed.env);
1226
+ const result = await prepareStartupDependencies(env, { force: true });
1227
+ console.log(JSON.stringify(result, null, 2));
1228
+ return 0;
1229
+ }
1230
+
1135
1231
  if (SERVER_BACKED_CONTROL_COMMANDS.has(argv[0])) {
1136
1232
  return runServerBackedControlCli(argv);
1137
1233
  }
@@ -314,13 +314,15 @@ function farmingCapabilities(browser) {
314
314
  id: 'browser',
315
315
  state,
316
316
  summary: state === 'available'
317
- ? 'An installed system Chromium Browser can be created or attached in Farming on demand.'
318
- : (browser?.message || 'System Browser integration is unavailable in Farming.'),
317
+ ? (browser?.browser?.kind === 'external-cdp'
318
+ ? 'Default browser path for web tasks. An externally managed CDP Browser can be created or attached as a shared, user-visible Farming Resource.'
319
+ : 'Default browser path for web tasks. An installed system Chromium Browser can be created or attached as a shared, user-visible Farming Resource.')
320
+ : (browser?.message || 'Browser integration is unavailable in Farming.'),
319
321
  commands: state === 'available'
320
322
  ? {
321
323
  list: 'farming browser list',
322
324
  create: 'farming browser create',
323
- help: 'farming browser --help',
325
+ workflow: 'farming browser help workflow',
324
326
  }
325
327
  : {},
326
328
  }],
@@ -41,7 +41,20 @@ function appendIndexHtmlAssetToken(html, token) {
41
41
  });
42
42
  }
43
43
 
44
+ function applyIndexHtmlAppearance(html, appearance) {
45
+ const normalizedAppearance = ['light', 'dark'].includes(appearance) ? appearance : 'system';
46
+ const source = String(html || '');
47
+ if (/\bdata-appearance-preference="[^"]*"/i.test(source)) {
48
+ return source.replace(
49
+ /\bdata-appearance-preference="[^"]*"/i,
50
+ `data-appearance-preference="${normalizedAppearance}"`
51
+ );
52
+ }
53
+ return source.replace(/<html\b/i, `<html data-appearance-preference="${normalizedAppearance}"`);
54
+ }
55
+
44
56
  module.exports = {
57
+ applyIndexHtmlAppearance,
45
58
  normalizeBasePath,
46
59
  routePath,
47
60
  rewriteIndexHtmlForBasePath,
@@ -61,16 +61,12 @@ const MAIN_AGENT_SKILLS = [
61
61
  id: 'browser-resource',
62
62
  name: '系统浏览器操作',
63
63
  trigger: '用户要求打开、查看或操作 Farming Project 下的 Browser Resource,或者需要绕过静态 HTML Viewer 限制验证真实网页时',
64
- summary: '通过 Farming Browser ID 操作用户当前看到的同一个 Headless 系统浏览器;先 Snapshot 获取当前 Ref,再进行点击或输入,页面变化后重新 Snapshot。',
64
+ summary: '通过 Farming Browser ID 操作用户当前看到的同一个系统浏览器;先走 Browser 的渐进式帮助和标准 Workflow,只在需要时展开具体问题域与原子命令。',
65
65
  commands: [
66
- 'farming browser list --workspace <repo>',
67
- 'farming browser start <browser-id>',
68
- 'farming browser snapshot <browser-id>',
69
- 'farming browser navigate <browser-id> <url>',
70
- 'farming browser click <browser-id> <ref-or-css=selector>',
71
- 'farming browser fill <browser-id> <ref-or-css=selector> <text>',
72
- 'farming browser screenshot <browser-id> <output.png>',
73
- 'farming browser stop <browser-id>',
66
+ 'farming capabilities',
67
+ 'farming browser list',
68
+ 'farming browser help workflow',
69
+ 'farming browser help <lifecycle|navigation|interaction|inspection|debugging|state|files>',
74
70
  ],
75
71
  },
76
72
  {
@@ -153,7 +149,7 @@ function renderMainAgentSkills() {
153
149
  });
154
150
 
155
151
  lines.push('Rules:');
156
- lines.push('- Use `farming browser` only for Browser Resources already in the user-selected Project scope; take a new snapshot after navigation or DOM-changing actions.');
152
+ lines.push('- Use `farming browser` only for Browser Resources already in the user-selected Project scope; follow `farming browser help workflow`, and reveal only the help topic or command needed for the current step.');
157
153
  lines.push('- Use `farming memory report` when you need recent context from local agent memories.');
158
154
  lines.push('- Use “牧场除虫计划” when the user asks for systematic bug hunting across a directory or module tree.');
159
155
  lines.push('- Before spawning child agents for pest control, map modules and module protocols first; do not send overlapping or vague tasks.');
@@ -1,6 +1,10 @@
1
1
  const fs = require('fs');
2
2
  const path = require('path');
3
3
  const { spawn } = require('child_process');
4
+ const {
5
+ matchingProcessIdentity,
6
+ readServerProcessIdentity,
7
+ } = require('./server-process-identity');
4
8
 
5
9
  function writeJsonAtomic(filePath, value) {
6
10
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
@@ -42,18 +46,37 @@ function isProcessRunning(pid) {
42
46
  try {
43
47
  process.kill(pid, 0);
44
48
  return true;
45
- } catch {
49
+ } catch (error) {
50
+ if (error?.code === 'EPERM' || error?.code === 'EACCES') return true;
46
51
  return false;
47
52
  }
48
53
  }
49
54
 
50
- async function stopProcess(pid, timeoutMs = 15_000) {
55
+ async function stopProcess(pid, expectedIdentity, timeoutMs = 15_000) {
51
56
  if (!isProcessRunning(pid)) return;
52
- process.kill(pid, 'SIGTERM');
57
+ const currentIdentity = await readServerProcessIdentity(pid);
58
+ if (!matchingProcessIdentity(expectedIdentity, currentIdentity)) {
59
+ throw new Error(`Refusing to stop Farming server ${pid}: process identity changed`);
60
+ }
61
+ try {
62
+ process.kill(pid, 'SIGKILL');
63
+ } catch (error) {
64
+ if (error?.code === 'EPERM' || error?.code === 'EACCES') {
65
+ throw new Error(
66
+ `Farming cannot stop server ${pid} because the update helper lacks permission. `
67
+ + 'Use the operating-system user that owns this process (or an administrator) to stop and restart Farming, then retry the update.',
68
+ { cause: error },
69
+ );
70
+ }
71
+ if (error?.code !== 'ESRCH') throw error;
72
+ }
53
73
  const startedAt = Date.now();
54
- while (isProcessRunning(pid)) {
74
+ while (matchingProcessIdentity(expectedIdentity, await readServerProcessIdentity(pid))) {
55
75
  if (Date.now() - startedAt >= timeoutMs) {
56
- throw new Error(`Farming server ${pid} did not stop before timeout`);
76
+ throw new Error(
77
+ `Farming server ${pid} did not exit after SIGKILL. `
78
+ + 'Stop and restart Farming manually, then retry the update.',
79
+ );
57
80
  }
58
81
  await new Promise(resolve => setTimeout(resolve, 100));
59
82
  }
@@ -200,9 +223,23 @@ async function prepareNpmUpdate(payload) {
200
223
  fs.mkdirSync(payload.stagingPrefix, { recursive: true });
201
224
  await installPackage(payload, payload.targetVersion, payload.stagingPrefix);
202
225
  verifyInstalledVersion(payload, payload.targetVersion, payload.stagingPackageRoot);
226
+ writeJsonAtomic(payload.stateFile, stateFor(payload, 'preparing-runtimes'));
227
+ appendLog(payload.logPath, `Preparing Farming ${payload.targetVersion} startup dependencies`);
228
+ await runCommand(payload.nodePath, [
229
+ path.join(payload.stagingPackageRoot, 'bin', 'farming'),
230
+ 'runtime',
231
+ 'prepare',
232
+ '--config-dir',
233
+ payload.configDir,
234
+ ], {
235
+ cwd: payload.configDir,
236
+ env: commandEnvironment(),
237
+ logPath: payload.logPath,
238
+ });
203
239
  const preparedAt = new Date().toISOString();
204
240
  writeJsonAtomic(payload.stateFile, stateFor(payload, 'ready-to-restart', {
205
241
  preparedAt,
242
+ runtimePreparedAt: preparedAt,
206
243
  }));
207
244
  appendLog(payload.logPath, `Farming ${payload.targetVersion} is ready to restart`);
208
245
  } catch (error) {
@@ -237,7 +274,7 @@ async function applyNpmUpdate(payload) {
237
274
  preparedAt: payload.preparedAt,
238
275
  }));
239
276
  await new Promise(resolve => setTimeout(resolve, 1_000));
240
- await stopProcess(Number(payload.serverPid));
277
+ await stopProcess(Number(payload.serverPid), payload.serverProcessIdentity);
241
278
  stoppedOldServer = true;
242
279
  fs.renameSync(payload.packageRoot, backupRoot);
243
280
  movedOldPackage = true;
@@ -213,6 +213,14 @@ function codexAcpEnvironment(options = {}) {
213
213
  return env;
214
214
  }
215
215
 
216
+ function claudeAcpEnvironment(options = {}) {
217
+ const env = { ...(options.env || process.env) };
218
+ if (options.executable && !env.CLAUDE_CODE_EXECUTABLE) {
219
+ env.CLAUDE_CODE_EXECUTABLE = options.executable;
220
+ }
221
+ return env;
222
+ }
223
+
216
224
  const PROVIDER_ADAPTERS = Object.freeze([
217
225
  {
218
226
  id: 'codex',
@@ -250,6 +258,7 @@ const PROVIDER_ADAPTERS = Object.freeze([
250
258
  version: '0.59.0',
251
259
  forkMode: 'target-process',
252
260
  },
261
+ prepareAcpEnvironment: claudeAcpEnvironment,
253
262
  capabilities: {
254
263
  runtimeSwitch: true,
255
264
  terminalProfile: false,
@@ -378,6 +387,7 @@ function isFreshAcpSessionSource(provider, source) {
378
387
  }
379
388
 
380
389
  module.exports = {
390
+ claudeAcpEnvironment,
381
391
  getProviderAdapter,
382
392
  applyProviderHomeEnvironment,
383
393
  isFreshAcpSessionSource,