mc-tester: QA harness for AI agents on Minecraft 26.3 Paper servers
Drives real Minecraft 26.3 clients (Fabric + QA Bridge mod) against a local Paper test server so QA agents can test plugins the way players use them. - qa-bridge: Fabric client mod exposing a localhost HTTP API (screen/GUI as JSON, container clicks via handleContainerInput, real mouse/keyboard injection, chat, entity/block interaction, screenshots, toast hiding, server resource pack auto-accept) - harness: launcher (Mojang/Fabric metadata, hash-verified cache), Paper server management with RCON and world snapshots, shared daemon, MCP server (38 tools), CLI, YAML scenario runner with failure screenshots and reports - plugin jars resolved per plugin name (newest build wins); agents can view and change them with plugins_list / plugins_set - fixtures/demo-shop: NPC chest-GUI shop used to self-test the harness - scenarios/demo-shop.yaml: purchase + GUI exploit regression test Co-Authored-By: Claude Opus 5.5 <[email protected]>
- 작성자
- LeeJunyoung
- 작성 시각
- 커밋
dfc82482d8390afd891f444e5172c19968defd1f- 부모
- 없음 (첫 커밋)
변경된 파일 56개
+2,618-0변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.
| @@ -0,0 +1,3 @@ | ||
| 1 | 추가: node_modules/ | |
| 2 | 추가: .mct/ | |
| 3 | 추가: *.log |
| @@ -0,0 +1,8 @@ | ||
| 1 | 추가: { | |
| 2 | 추가: "mcpServers": { | |
| 3 | 추가: "mc-tester": { | |
| 4 | 추가: "command": "node", | |
| 5 | 추가: "args": ["harness/mcp.ts"] | |
| 6 | 추가: } | |
| 7 | 추가: } | |
| 8 | 추가: } |
| @@ -0,0 +1,44 @@ | ||
| 1 | 추가: # QA 에이전트 역할 지침 (초안) | |
| 2 | 추가: | |
| 3 | 추가: 이 문서를 QA 역할 에이전트의 시스템 프롬프트나 역할 설명에 넣어 쓰세요. mc-tester MCP 서버(`mc-tester`)가 연결되어 있다고 가정합니다. | |
| 4 | 추가: | |
| 5 | 추가: --- | |
| 6 | 추가: | |
| 7 | 추가: 너는 마인크래프트 야생 서버(Paper 26.3 + 팀이 만든 플러그인)의 QA 담당이다. `mc-tester` 도구로 **실제 마인크래프트 클라이언트**를 조작해서 기능을 검증하고, 버그를 재현 가능한 형태로 보고한다. | |
| 8 | 추가: | |
| 9 | 추가: ## 작업 순서 | |
| 10 | 추가: 1. `server_status`와 `plugins_list`로 상태와 로드될 플러그인 jar를 확인한다. 테스트할 플러그인이 목록에 없거나 경로가 틀렸으면 `plugins_set`(add/remove)으로 고친다. 플러그인이 새로 빌드됐으면 `server_restart`를 해서 최신 jar를 반영한다. | |
| 11 | 추가: 2. 테스트 플레이어는 `client_launch {name: "Bot1"}`로 띄운다. 플레이어가 여럿 필요한 기능(거래, 수표 양도, 송금)은 Bot2, Bot3을 추가한다. | |
| 12 | 추가: 3. 상태는 `rcon`으로 준비한다(`give`, `tp`, 플러그인 관리 명령). 결정적인 테스트가 필요하면 `world_reset base`부터 한다. | |
| 13 | 추가: 4. 사람처럼 조작한다. | |
| 14 | 추가: - NPC: `teleport`로 2~3블록 앞까지 간 뒤 `interact_entity` | |
| 15 | 추가: - GUI: `screen`으로 읽고 `click_item`/`click_slot`으로 클릭 | |
| 16 | 추가: - 입력창: `type_text` 다음 `key enter` | |
| 17 | 추가: - 아이템 사용: `hotbar`로 고른 뒤 `use` | |
| 18 | 추가: 5. 매 단계 결과를 두 쪽에서 확인한다. | |
| 19 | 추가: - **서버의 진실**: `rcon`(플러그인 조회 명령, `data get entity`, `clear <player> <item> 0`으로 개수 세기) | |
| 20 | 추가: - **클라이언트의 체감**: `screen`, `state`, `chat_log`/`wait_for {chat}`, 필요하면 `screenshot` | |
| 21 | 추가: 6. 끝나면 `server_log {errors_only: true}`로 예외가 없는지 확인한다. | |
| 22 | 추가: | |
| 23 | 추가: ## 반드시 시도할 것 (GUI/경제 기능) | |
| 24 | 추가: - 정상 흐름, 잔액이나 재료가 부족할 때, 인벤토리가 가득 찼을 때 | |
| 25 | 추가: - 악용 클릭: | |
| 26 | 추가: - QUICK_MOVE(쉬프트) | |
| 27 | 추가: - SWAP(숫자키, button 0-8과 40) | |
| 28 | 추가: - PICKUP button 1(우클릭) | |
| 29 | 추가: - PICKUP_ALL(더블클릭) | |
| 30 | 추가: - THROW | |
| 31 | 추가: - slot -999(창 밖) | |
| 32 | 추가: - 빠른 연타(같은 클릭 여러 번) | |
| 33 | 추가: - 거래 도중 `close_screen`이나 `client_disconnect` 후 재접속했을 때 상태가 일관적인지 | |
| 34 | 추가: - 두 클라이언트가 같은 자원(재고, 주식, 계좌)에 동시에 접근할 때 | |
| 35 | 추가: - 각 시도 후 **불변식**: 아이템 총량과 화폐 총량이 의도한 만큼만 바뀌었는지 | |
| 36 | 추가: | |
| 37 | 추가: ## 보고 형식 | |
| 38 | 추가: - 버그마다: 재현 단계(도구 호출 순서), 기대 결과, 실제 결과(RCON 출력, 화면 JSON), 스크린샷 경로, 관련 서버 로그 | |
| 39 | 추가: - 재현이 확인된 버그와 중요한 정상 흐름은 `scenarios/<기능>.yaml` 회귀 테스트로 남기고 `run_scenario`로 통과/실패를 확인한다. 고친 뒤에는 같은 시나리오로 다시 검증한다. | |
| 40 | 추가: | |
| 41 | 추가: ## 주의 | |
| 42 | 추가: - 클라이언트 화면은 서버보다 한두 틱 늦을 수 있다. 판정은 서버 쪽 값으로 하고, `wait_for`나 짧은 `sleep`으로 동기화한다. | |
| 43 | 추가: - 클라이언트 실행은 수십 초 걸리고 무겁다. 필요한 만큼만 띄우고 다 쓰면 `client_stop`한다. | |
| 44 | 추가: - 정품 계정(`account: "microsoft"`)은 사람이 미리 로그인해 둔 경우에만 쓸 수 있다. 로그인이 필요하다는 에러가 나면 사람에게 요청한다. |
| @@ -0,0 +1,149 @@ | ||
| 1 | 추가: # mc-tester | |
| 2 | 추가: | |
| 3 | 추가: QA 역할의 AI 에이전트가 **실제 Minecraft 26.3 클라이언트**로 Paper 야생 서버(직접 만든 플러그인 포함)를 테스트하는 하네스입니다. | |
| 4 | 추가: | |
| 5 | 추가: - 진짜 클라이언트를 씁니다(Fabric + **QA Bridge** 모드). 그래서 상자 GUI 상점, NPC 클릭, 표지판·모루 입력, 서버 리소스팩까지 사람이 하는 것과 같은 패킷과 화면으로 테스트됩니다. | |
| 6 | 추가: - 에이전트는 **MCP 도구 38개**로 조작합니다. GUI는 JSON(슬롯, 아이템 이름, lore, 툴팁)으로 읽고, 필요하면 **스크린샷 이미지**를 받습니다. | |
| 7 | 추가: - 서버 쪽 진실은 **RCON**과 서버 로그로 확인합니다(잔액, 인벤토리, 예외). | |
| 8 | 추가: - 재현 가능한 검사는 **YAML 시나리오**로 남겨 회귀 테스트로 돌립니다. | |
| 9 | 추가: | |
| 10 | 추가: ``` | |
| 11 | 추가: QA 에이전트 ──MCP(stdio)──▶ harness/mcp.ts ─┐ | |
| 12 | 추가: CLI / CI ───────────────▶ harness/cli.ts ──┼─HTTP─▶ harness/daemon.ts (서버·클라이언트 소유, 여러 에이전트가 공유) | |
| 13 | 추가: │ ├─ Paper 26.3 테스트 서버 (127.0.0.1:25565, RCON 25575) | |
| 14 | 추가: │ └─ 클라이언트 N개 (Xvfb 가상 화면 또는 데스크톱 창) | |
| 15 | 추가: │ └─ QA Bridge 모드: 127.0.0.1:7800+ HTTP API | |
| 16 | 추가: ``` | |
| 17 | 추가: | |
| 18 | 추가: ## 요구 사항 | |
| 19 | 추가: | |
| 20 | 추가: - Linux, Java 25, Node 24 이상, `Xvfb`(`sudo apt install xvfb`). 이 PC에서는 모두 확인했습니다. | |
| 21 | 추가: - 첫 실행 때 Mojang/Fabric/PaperMC 공식 저장소에서 클라이언트, 라이브러리, 에셋(약 5천 개), Paper jar를 받아 `.mct/cache/`에 캐시합니다. 모든 파일은 해시로 검증합니다. | |
| 22 | 추가: | |
| 23 | 추가: ## 빠른 시작 | |
| 24 | 추가: | |
| 25 | 추가: ```bash | |
| 26 | 추가: npm install | |
| 27 | 추가: npm run build:mods # qa-bridge 모드 + 데모 상점 플러그인 빌드 | |
| 28 | 추가: npm run mct -- scenario scenarios/demo-shop.yaml # 서버 실행 → 클라이언트 접속 → 상점 테스트 (약 20~30초) | |
| 29 | 추가: ``` | |
| 30 | 추가: | |
| 31 | 추가: 수동으로 조작할 때: | |
| 32 | 추가: | |
| 33 | 추가: ```bash | |
| 34 | 추가: npm run mct -- server_start | |
| 35 | 추가: npm run mct -- client_launch name=Bot1 | |
| 36 | 추가: npm run mct -- rcon command='give Bot1 emerald 10' | |
| 37 | 추가: npm run mct -- interact_entity name=상점 screenshot=true | |
| 38 | 추가: npm run mct -- screen | |
| 39 | 추가: npm run mct -- click_item name=다이아몬드 | |
| 40 | 추가: npm run mct -- daemon-stop # 클라이언트·서버·데몬 모두 종료 | |
| 41 | 추가: ``` | |
| 42 | 추가: | |
| 43 | 추가: 결과물: | |
| 44 | 추가: - 스크린샷: `.mct/artifacts/<플레이어>/` | |
| 45 | 추가: - 시나리오 리포트(JSON): `.mct/reports/` | |
| 46 | 추가: - 클라이언트 로그: `.mct/clients/<플레이어>/mct-client.log` | |
| 47 | 추가: - 데몬 로그: `.mct/run/daemon.log` | |
| 48 | 추가: | |
| 49 | 추가: ## 에이전트에 연결하기 (MCP) | |
| 50 | 추가: | |
| 51 | 추가: 이 저장소 안에서 실행하는 에이전트는 루트의 `.mcp.json`이 자동으로 잡힙니다. 다른 저장소에서 일하는 QA 에이전트에는 이 저장소를 clone한 위치의 절대 경로로 등록하세요. | |
| 52 | 추가: | |
| 53 | 추가: ```json | |
| 54 | 추가: { | |
| 55 | 추가: "mcpServers": { | |
| 56 | 추가: "mc-tester": { | |
| 57 | 추가: "command": "node", | |
| 58 | 추가: "args": ["/absolute/path/to/mc-tester/harness/mcp.ts"] | |
| 59 | 추가: } | |
| 60 | 추가: } | |
| 61 | 추가: } | |
| 62 | 추가: ``` | |
| 63 | 추가: | |
| 64 | 추가: QA 에이전트의 역할 지침(시스템 프롬프트) 초안은 [QA_AGENT.md](QA_AGENT.md)에 있습니다. | |
| 65 | 추가: | |
| 66 | 추가: MCP 서버들은 하나의 데몬을 공유합니다. 처음 호출할 때 데몬이 자동으로 뜨고, 여러 에이전트가 같은 서버와 클라이언트를 함께 봅니다. | |
| 67 | 추가: | |
| 68 | 추가: ## 직접 만든 플러그인 연결 | |
| 69 | 추가: | |
| 70 | 추가: 플러그인 jar 경로는 `mct.config.json`의 `server.plugins`에 들어가고, **처음 한 번만 정하면 됩니다.** 파일 이름에 `*`를 쓸 수 있어서 버전이 바뀌어도 그대로 동작해요. `server_start`/`server_restart` 때마다 패턴으로 jar를 다시 찾아 복사하므로, **플러그인을 다시 빌드하고 `server_restart`만 하면 새 코드가 테스트됩니다.** | |
| 71 | 추가: | |
| 72 | 추가: 경로는 AI 에이전트가 직접 설정할 수 있습니다. | |
| 73 | 추가: - `plugins_list`: 설정된 패턴, 실제로 로드될 jar(플러그인 이름, 버전, 빌드 시각), 건너뛴 jar, 아무것도 못 찾은 패턴을 보여줌 | |
| 74 | 추가: - `plugins_set`: 목록 전체 교체(`plugins`) 또는 `add`/`remove`. `mct.config.json`에 저장되고, `restart: true`면 바로 재시작해 반영함. 존재하지 않는 경로는 저장을 거부함(아직 빌드 전이면 `allow_unmatched: true`) | |
| 75 | 추가: | |
| 76 | 추가: ```bash | |
| 77 | 추가: npm run mct -- plugins_set add='["../my-survival-server/build/libs/MySurvival-*.jar"]' restart=true | |
| 78 | 추가: ``` | |
| 79 | 추가: | |
| 80 | 추가: 직접 편집해도 됩니다(`mct.config.example.json` 참고). | |
| 81 | 추가: | |
| 82 | 추가: ```json | |
| 83 | 추가: { | |
| 84 | 추가: "server": { | |
| 85 | 추가: "plugins": [ | |
| 86 | 추가: "../my-survival-server/build/libs/MySurvival-*.jar", | |
| 87 | 추가: "../libs/*.jar" | |
| 88 | 추가: ] | |
| 89 | 추가: } | |
| 90 | 추가: } | |
| 91 | 추가: ``` | |
| 92 | 추가: | |
| 93 | 추가: **같은 플러그인의 jar가 여러 개 잡히면** 가장 최근에 빌드된 하나만 설치합니다. `build/libs`에 남은 예전 버전이나, shadow 플러그인의 `-all.jar`와 일반 jar가 같이 있는 경우가 그래요. 같은 플러그인인지는 jar 안의 `plugin.yml`/`paper-plugin.yml`의 `name`으로 판단하므로, `../libs/*.jar`처럼 서로 다른 플러그인 여러 개를 한 패턴으로 넣는 것도 됩니다. 건너뛴 jar는 `server_start` 결과의 `skippedJars`와 `plugins_list`에 나옵니다. | |
| 94 | 추가: | |
| 95 | 추가: 설정 항목 전체는 [harness/config.ts](harness/config.ts)에 기본값과 함께 있습니다. 주요 기본값: | |
| 96 | 추가: - 평지 월드, peaceful, 시간·날씨 고정, 몹 스폰 끔 | |
| 97 | 추가: - 127.0.0.1에만 바인드, offline-mode | |
| 98 | 추가: - 클라이언트 언어 `ko_kr`, 1280x720, GUI 배율 2 | |
| 99 | 추가: - 토스트 숨김, 서버 리소스팩 자동 수락 | |
| 100 | 추가: | |
| 101 | 추가: ## 도구 목록 | |
| 102 | 추가: | |
| 103 | 추가: | 분류 | 도구 | | |
| 104 | 추가: |---|---| | |
| 105 | 추가: | 서버 | `server_start` `server_stop` `server_restart` `server_status` `rcon` `server_log` `world_snapshot` `world_reset` | | |
| 106 | 추가: | 플러그인 | `plugins_list` `plugins_set` | | |
| 107 | 추가: | 클라이언트 | `client_launch` `client_stop` `client_list` `client_connect` `client_disconnect` | | |
| 108 | 추가: | 관찰 | `state` `screen` `screenshot` `chat_log` `entities` `wait_for` | | |
| 109 | 추가: | GUI 입력 | `click_slot` `click_item` `mouse` `click_widget` `key` `type_text` `close_screen` | | |
| 110 | 추가: | 월드 입력 | `chat` `teleport` `look` `interact_entity` `use_on_block` `use` `attack` `hold_keys` `hotbar` | | |
| 111 | 추가: | 회귀 | `run_scenario` | | |
| 112 | 추가: | |
| 113 | 추가: - `click_slot`과 `click_item`은 클라이언트의 `MultiPlayerGameMode.handleContainerInput`(GUI가 실제로 호출하는 함수)을 거칩니다. PICKUP, QUICK_MOVE(쉬프트), SWAP(숫자키), CLONE, THROW, QUICK_CRAFT(드래그), PICKUP_ALL(더블클릭)을 모두 보낼 수 있습니다. | |
| 114 | 추가: - `mouse`, `key`, `type_text`는 SDL 이벤트 핸들러가 호출하는 `MouseHandler`/`KeyboardHandler`에 그대로 주입되므로 실제 입력과 같은 경로입니다. | |
| 115 | 추가: - 행동 도구에 `screenshot: true`를 주면 결과 직후의 화면 이미지가 함께 돌아옵니다. | |
| 116 | 추가: | |
| 117 | 추가: ## 시나리오 | |
| 118 | 추가: | |
| 119 | 추가: [scenarios/README.md](scenarios/README.md)를 보세요. 예제는 [scenarios/demo-shop.yaml](scenarios/demo-shop.yaml)입니다. NPC 상점 구매에 더해 쉬프트, 숫자키, 우클릭 악용 시도를 하고, RCON으로 아이템이 보존되는지 확인합니다. | |
| 120 | 추가: | |
| 121 | 추가: `fixtures/demo-shop/`은 하네스 자체를 검증하기 위한 작은 Paper 플러그인입니다. `/demoshop bug on`으로 일부러 복사 버그를 켜면 위 시나리오가 `diamond = 2, expected 1`로 실패하고, 실패 순간 스크린샷이 남습니다. | |
| 122 | 추가: | |
| 123 | 추가: ## 정품(Microsoft) 계정 | |
| 124 | 추가: | |
| 125 | 추가: offline 테스트 플레이어로 대부분 테스트할 수 있습니다. 실제 인증, UUID, 스킨이 필요한 테스트에만 정품 계정을 씁니다. | |
| 126 | 추가: | |
| 127 | 추가: ```bash | |
| 128 | 추가: npm run mct -- login # 표시된 URL을 브라우저로 열고 코드를 입력 (사람이 해야 함) | |
| 129 | 추가: npm run mct -- client_launch name=me account=microsoft | |
| 130 | 추가: ``` | |
| 131 | 추가: | |
| 132 | 추가: - 토큰은 `.mct/auth/`에 캐시됩니다(권한 700, git 제외). 하네스는 토큰을 출력하지 않습니다. | |
| 133 | 추가: - 같은 계정으로 동시에 접속할 수 있는 클라이언트는 하나뿐입니다. 테스트 중에 그 계정으로 직접 플레이하면 둘 중 하나가 튕깁니다. | |
| 134 | 추가: - 실제 인증 서버로 테스트하려면 `mct.config.json`에 `"server": {"onlineMode": true}`를 넣으세요. 이 모드에서는 offline 플레이어가 접속할 수 없습니다. | |
| 135 | 추가: | |
| 136 | 추가: ## 디렉터리 | |
| 137 | 추가: | |
| 138 | 추가: - `qa-bridge/`: Fabric 26.3 클라이언트 모드(Java). 127.0.0.1 HTTP API를 제공합니다. | |
| 139 | 추가: - `harness/`: TypeScript(Node가 직접 실행). 런처, Paper 관리, RCON, 데몬, MCP, CLI, 시나리오 러너가 들어 있습니다. | |
| 140 | 추가: - `fixtures/demo-shop/`: 검증용 Paper 플러그인 | |
| 141 | 추가: - `scenarios/`: YAML 회귀 테스트 | |
| 142 | 추가: - `tests/mcp-smoke.ts`: MCP 연결 스모크 테스트 | |
| 143 | 추가: - `.mct/`: 런타임 데이터(캐시, 서버, 클라이언트, 스크린샷, 리포트). git에서 제외됩니다. | |
| 144 | 추가: | |
| 145 | 추가: ## 알려진 한계 | |
| 146 | 추가: | |
| 147 | 추가: - 클라이언트 하나에 RAM 약 2~3GB가 들고, Xvfb에서는 CPU 렌더링(llvmpipe, 약 10fps)이라 무겁습니다. 동시에 여러 명이 필요한 테스트(거래, 수표 양도, 동시 구매)는 몇 개 정도가 적당하고, 수십 명 부하 테스트에는 맞지 않습니다. | |
| 148 | 추가: - 긴 거리 이동은 `teleport`(RCON)로 합니다. 경로 탐색은 없습니다. | |
| 149 | 추가: - Minecraft 버전을 올리면 QA Bridge가 쓰는 클라이언트 내부 API가 바뀔 수 있습니다. `qa-bridge/gradle.properties`의 버전을 올리고 다시 빌드한 다음 `scenarios/demo-shop.yaml`로 확인하세요. |
| @@ -0,0 +1,7 @@ | ||
| 1 | 추가: #!/usr/bin/env node | |
| 2 | 추가: // Wrapper so `npx mct ...` / a global link works: runs the TypeScript CLI with Node's type stripping. | |
| 3 | 추가: import { spawnSync } from 'node:child_process'; | |
| 4 | 추가: import path from 'node:path'; | |
| 5 | 추가: const cli = path.join(import.meta.dirname, '..', 'harness', 'cli.ts'); | |
| 6 | 추가: const r = spawnSync(process.execPath, [cli, ...process.argv.slice(2)], { stdio: 'inherit' }); | |
| 7 | 추가: process.exit(r.status ?? 1); |
| @@ -0,0 +1,6 @@ | ||
| 1 | 추가: .gradle/ | |
| 2 | 추가: build/ | |
| 3 | 추가: run/ | |
| 4 | 추가: out/ | |
| 5 | 추가: *.iml | |
| 6 | 추가: .idea/ |
| @@ -0,0 +1,21 @@ | ||
| 1 | 추가: plugins { id 'java' } | |
| 2 | 추가: | |
| 3 | 추가: group = 'dev.mctester' | |
| 4 | 추가: version = '0.1.0' | |
| 5 | 추가: | |
| 6 | 추가: repositories { | |
| 7 | 추가: maven { url = 'https://repo.papermc.io/repository/maven-public/' } | |
| 8 | 추가: mavenCentral() | |
| 9 | 추가: } | |
| 10 | 추가: | |
| 11 | 추가: dependencies { | |
| 12 | 추가: compileOnly 'io.papermc.paper:paper-api:26.3.build.262-stable' | |
| 13 | 추가: } | |
| 14 | 추가: | |
| 15 | 추가: java { toolchain { languageVersion = JavaLanguageVersion.of(25) } } | |
| 16 | 추가: tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8'; options.release = 25 } | |
| 17 | 추가: processResources { | |
| 18 | 추가: def v = project.version | |
| 19 | 추가: inputs.property 'version', v | |
| 20 | 추가: filesMatching('plugin.yml') { expand version: v } | |
| 21 | 추가: } |
| @@ -0,0 +1,2 @@ | ||
| 1 | 추가: org.gradle.jvmargs=-Xmx1G | |
| 2 | 추가: org.gradle.configuration-cache=true |
바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기| @@ -0,0 +1,9 @@ | ||
| 1 | 추가: distributionBase=GRADLE_USER_HOME | |
| 2 | 추가: distributionPath=wrapper/dists | |
| 3 | 추가: distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip | |
| 4 | 추가: networkTimeout=10000 | |
| 5 | 추가: retries=0 | |
| 6 | 추가: retryBackOffMs=500 | |
| 7 | 추가: validateDistributionUrl=true | |
| 8 | 추가: zipStoreBase=GRADLE_USER_HOME | |
| 9 | 추가: zipStorePath=wrapper/dists |
| @@ -0,0 +1,248 @@ | ||
| 1 | 추가: #!/bin/sh | |
| 2 | 추가: | |
| 3 | 추가: # | |
| 4 | 추가: # Copyright © 2015 the original authors. | |
| 5 | 추가: # | |
| 6 | 추가: # Licensed under the Apache License, Version 2.0 (the "License"); | |
| 7 | 추가: # you may not use this file except in compliance with the License. | |
| 8 | 추가: # You may obtain a copy of the License at | |
| 9 | 추가: # | |
| 10 | 추가: # https://www.apache.org/licenses/LICENSE-2.0 | |
| 11 | 추가: # | |
| 12 | 추가: # Unless required by applicable law or agreed to in writing, software | |
| 13 | 추가: # distributed under the License is distributed on an "AS IS" BASIS, | |
| 14 | 추가: # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 15 | 추가: # See the License for the specific language governing permissions and | |
| 16 | 추가: # limitations under the License. | |
| 17 | 추가: # | |
| 18 | 추가: # SPDX-License-Identifier: Apache-2.0 | |
| 19 | 추가: # | |
| 20 | 추가: | |
| 21 | 추가: ############################################################################## | |
| 22 | 추가: # | |
| 23 | 추가: # gradlew start up script for POSIX generated by Gradle. | |
| 24 | 추가: # | |
| 25 | 추가: # Important for running: | |
| 26 | 추가: # | |
| 27 | 추가: # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is | |
| 28 | 추가: # noncompliant, but you have some other compliant shell such as ksh or | |
| 29 | 추가: # bash, then to run this script, type that shell name before the whole | |
| 30 | 추가: # command line, like: | |
| 31 | 추가: # | |
| 32 | 추가: # ksh gradlew | |
| 33 | 추가: # | |
| 34 | 추가: # Busybox and similar reduced shells will NOT work, because this script | |
| 35 | 추가: # requires all of these POSIX shell features: | |
| 36 | 추가: # * functions; | |
| 37 | 추가: # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», | |
| 38 | 추가: # «${var#prefix}», «${var%suffix}», and «$( cmd )»; | |
| 39 | 추가: # * compound commands having a testable exit status, especially «case»; | |
| 40 | 추가: # * various built-in commands including «command», «set», and «ulimit». | |
| 41 | 추가: # | |
| 42 | 추가: # Important for patching: | |
| 43 | 추가: # | |
| 44 | 추가: # (2) This script targets any POSIX shell, so it avoids extensions provided | |
| 45 | 추가: # by Bash, Ksh, etc; in particular arrays are avoided. | |
| 46 | 추가: # | |
| 47 | 추가: # The "traditional" practice of packing multiple parameters into a | |
| 48 | 추가: # space-separated string is a well documented source of bugs and security | |
| 49 | 추가: # problems, so this is (mostly) avoided, by progressively accumulating | |
| 50 | 추가: # options in "$@", and eventually passing that to Java. | |
| 51 | 추가: # | |
| 52 | 추가: # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, | |
| 53 | 추가: # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; | |
| 54 | 추가: # see the in-line comments for details. | |
| 55 | 추가: # | |
| 56 | 추가: # There are tweaks for specific operating systems such as AIX, CygWin, | |
| 57 | 추가: # Darwin, MinGW, and NonStop. | |
| 58 | 추가: # | |
| 59 | 추가: # (3) This script is generated from the Groovy template | |
| 60 | 추가: # https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt | |
| 61 | 추가: # within the Gradle project. | |
| 62 | 추가: # | |
| 63 | 추가: # You can find Gradle at https://github.com/gradle/gradle/. | |
| 64 | 추가: # | |
| 65 | 추가: ############################################################################## | |
| 66 | 추가: | |
| 67 | 추가: # Attempt to set APP_HOME | |
| 68 | 추가: | |
| 69 | 추가: # Resolve links: $0 may be a link | |
| 70 | 추가: app_path=$0 | |
| 71 | 추가: | |
| 72 | 추가: # Need this for daisy-chained symlinks. | |
| 73 | 추가: while | |
| 74 | 추가: APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path | |
| 75 | 추가: [ -h "$app_path" ] | |
| 76 | 추가: do | |
| 77 | 추가: ls=$( ls -ld "$app_path" ) | |
| 78 | 추가: link=${ls#*' -> '} | |
| 79 | 추가: case $link in #( | |
| 80 | 추가: /*) app_path=$link ;; #( | |
| 81 | 추가: *) app_path=$APP_HOME$link ;; | |
| 82 | 추가: esac | |
| 83 | 추가: done | |
| 84 | 추가: | |
| 85 | 추가: # This is normally unused | |
| 86 | 추가: # shellcheck disable=SC2034 | |
| 87 | 추가: APP_BASE_NAME=${0##*/} | |
| 88 | 추가: # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) | |
| 89 | 추가: APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit | |
| 90 | 추가: | |
| 91 | 추가: # Use the maximum available, or set MAX_FD != -1 to use that value. | |
| 92 | 추가: MAX_FD=maximum | |
| 93 | 추가: | |
| 94 | 추가: warn () { | |
| 95 | 추가: echo "$*" | |
| 96 | 추가: } >&2 | |
| 97 | 추가: | |
| 98 | 추가: die () { | |
| 99 | 추가: echo | |
| 100 | 추가: echo "$*" | |
| 101 | 추가: echo | |
| 102 | 추가: exit 1 | |
| 103 | 추가: } >&2 | |
| 104 | 추가: | |
| 105 | 추가: # OS specific support (must be 'true' or 'false'). | |
| 106 | 추가: cygwin=false | |
| 107 | 추가: msys=false | |
| 108 | 추가: darwin=false | |
| 109 | 추가: nonstop=false | |
| 110 | 추가: case "$( uname )" in #( | |
| 111 | 추가: CYGWIN* ) cygwin=true ;; #( | |
| 112 | 추가: Darwin* ) darwin=true ;; #( | |
| 113 | 추가: MSYS* | MINGW* ) msys=true ;; #( | |
| 114 | 추가: NONSTOP* ) nonstop=true ;; | |
| 115 | 추가: esac | |
| 116 | 추가: | |
| 117 | 추가: | |
| 118 | 추가: | |
| 119 | 추가: # Determine the Java command to use to start the JVM. | |
| 120 | 추가: if [ -n "$JAVA_HOME" ] ; then | |
| 121 | 추가: if [ -x "$JAVA_HOME/jre/sh/java" ] ; then | |
| 122 | 추가: # IBM's JDK on AIX uses strange locations for the executables | |
| 123 | 추가: JAVACMD=$JAVA_HOME/jre/sh/java | |
| 124 | 추가: else | |
| 125 | 추가: JAVACMD=$JAVA_HOME/bin/java | |
| 126 | 추가: fi | |
| 127 | 추가: if [ ! -x "$JAVACMD" ] ; then | |
| 128 | 추가: die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME | |
| 129 | 추가: | |
| 130 | 추가: Please set the JAVA_HOME variable in your environment to match the | |
| 131 | 추가: location of your Java installation." | |
| 132 | 추가: fi | |
| 133 | 추가: else | |
| 134 | 추가: JAVACMD=java | |
| 135 | 추가: if ! command -v java >/dev/null 2>&1 | |
| 136 | 추가: then | |
| 137 | 추가: die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. | |
| 138 | 추가: | |
| 139 | 추가: Please set the JAVA_HOME variable in your environment to match the | |
| 140 | 추가: location of your Java installation." | |
| 141 | 추가: fi | |
| 142 | 추가: fi | |
| 143 | 추가: | |
| 144 | 추가: # Increase the maximum file descriptors if we can. | |
| 145 | 추가: if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then | |
| 146 | 추가: case $MAX_FD in #( | |
| 147 | 추가: max*) | |
| 148 | 추가: # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. | |
| 149 | 추가: # shellcheck disable=SC2039,SC3045 | |
| 150 | 추가: MAX_FD=$( ulimit -H -n ) || | |
| 151 | 추가: warn "Could not query maximum file descriptor limit" | |
| 152 | 추가: esac | |
| 153 | 추가: case $MAX_FD in #( | |
| 154 | 추가: '' | soft) :;; #( | |
| 155 | 추가: *) | |
| 156 | 추가: # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. | |
| 157 | 추가: # shellcheck disable=SC2039,SC3045 | |
| 158 | 추가: ulimit -n "$MAX_FD" || | |
| 159 | 추가: warn "Could not set maximum file descriptor limit to $MAX_FD" | |
| 160 | 추가: esac | |
| 161 | 추가: fi | |
| 162 | 추가: | |
| 163 | 추가: # Collect all arguments for the java command, stacking in reverse order: | |
| 164 | 추가: # * args from the command line | |
| 165 | 추가: # * the main class name | |
| 166 | 추가: # * -classpath | |
| 167 | 추가: # * -D...appname settings | |
| 168 | 추가: # * --module-path (only if needed) | |
| 169 | 추가: # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. | |
| 170 | 추가: | |
| 171 | 추가: # For Cygwin or MSYS, switch paths to Windows format before running java | |
| 172 | 추가: if "$cygwin" || "$msys" ; then | |
| 173 | 추가: APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) | |
| 174 | 추가: | |
| 175 | 추가: JAVACMD=$( cygpath --unix "$JAVACMD" ) | |
| 176 | 추가: | |
| 177 | 추가: # Now convert the arguments - kludge to limit ourselves to /bin/sh | |
| 178 | 추가: for arg do | |
| 179 | 추가: if | |
| 180 | 추가: case $arg in #( | |
| 181 | 추가: -*) false ;; # don't mess with options #( | |
| 182 | 추가: /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath | |
| 183 | 추가: [ -e "$t" ] ;; #( | |
| 184 | 추가: *) false ;; | |
| 185 | 추가: esac | |
| 186 | 추가: then | |
| 187 | 추가: arg=$( cygpath --path --ignore --mixed "$arg" ) | |
| 188 | 추가: fi | |
| 189 | 추가: # Roll the args list around exactly as many times as the number of | |
| 190 | 추가: # args, so each arg winds up back in the position where it started, but | |
| 191 | 추가: # possibly modified. | |
| 192 | 추가: # | |
| 193 | 추가: # NB: a `for` loop captures its iteration list before it begins, so | |
| 194 | 추가: # changing the positional parameters here affects neither the number of | |
| 195 | 추가: # iterations, nor the values presented in `arg`. | |
| 196 | 추가: shift # remove old arg | |
| 197 | 추가: set -- "$@" "$arg" # push replacement arg | |
| 198 | 추가: done | |
| 199 | 추가: fi | |
| 200 | 추가: | |
| 201 | 추가: | |
| 202 | 추가: # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. | |
| 203 | 추가: DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' | |
| 204 | 추가: | |
| 205 | 추가: # Collect all arguments for the java command: | |
| 206 | 추가: # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, | |
| 207 | 추가: # and any embedded shellness will be escaped. | |
| 208 | 추가: # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be | |
| 209 | 추가: # treated as '${Hostname}' itself on the command line. | |
| 210 | 추가: | |
| 211 | 추가: set -- \ | |
| 212 | 추가: "-Dorg.gradle.appname=$APP_BASE_NAME" \ | |
| 213 | 추가: -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ | |
| 214 | 추가: "$@" | |
| 215 | 추가: | |
| 216 | 추가: # Stop when "xargs" is not available. | |
| 217 | 추가: if ! command -v xargs >/dev/null 2>&1 | |
| 218 | 추가: then | |
| 219 | 추가: die "xargs is not available" | |
| 220 | 추가: fi | |
| 221 | 추가: | |
| 222 | 추가: # Use "xargs" to parse quoted args. | |
| 223 | 추가: # | |
| 224 | 추가: # With -n1 it outputs one arg per line, with the quotes and backslashes removed. | |
| 225 | 추가: # | |
| 226 | 추가: # In Bash we could simply go: | |
| 227 | 추가: # | |
| 228 | 추가: # readarray ARGS < <( xargs -n1 <<<"$var" ) && | |
| 229 | 추가: # set -- "${ARGS[@]}" "$@" | |
| 230 | 추가: # | |
| 231 | 추가: # but POSIX shell has neither arrays nor command substitution, so instead we | |
| 232 | 추가: # post-process each arg (as a line of input to sed) to backslash-escape any | |
| 233 | 추가: # character that might be a shell metacharacter, then use eval to reverse | |
| 234 | 추가: # that process (while maintaining the separation between arguments), and wrap | |
| 235 | 추가: # the whole thing up as a single "set" statement. | |
| 236 | 추가: # | |
| 237 | 추가: # This will of course break if any of these variables contains a newline or | |
| 238 | 추가: # an unmatched quote. | |
| 239 | 추가: # | |
| 240 | 추가: | |
| 241 | 추가: eval "set -- $( | |
| 242 | 추가: printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | | |
| 243 | 추가: xargs -n1 | | |
| 244 | 추가: sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | | |
| 245 | 추가: tr '\n' ' ' | |
| 246 | 추가: )" '"$@"' | |
| 247 | 추가: | |
| 248 | 추가: exec "$JAVACMD" "$@" |
| @@ -0,0 +1 @@ | ||
| 1 | 추가: rootProject.name = 'demo-shop' |
| @@ -0,0 +1,166 @@ | ||
| 1 | 추가: package dev.mctester.demoshop; | |
| 2 | 추가: | |
| 3 | 추가: import net.kyori.adventure.text.Component; | |
| 4 | 추가: import net.kyori.adventure.text.format.NamedTextColor; | |
| 5 | 추가: import net.kyori.adventure.text.format.TextDecoration; | |
| 6 | 추가: import org.bukkit.Bukkit; | |
| 7 | 추가: import org.bukkit.Location; | |
| 8 | 추가: import org.bukkit.Material; | |
| 9 | 추가: import org.bukkit.NamespacedKey; | |
| 10 | 추가: import org.bukkit.command.Command; | |
| 11 | 추가: import org.bukkit.command.CommandSender; | |
| 12 | 추가: import org.bukkit.entity.Entity; | |
| 13 | 추가: import org.bukkit.entity.Player; | |
| 14 | 추가: import org.bukkit.entity.Villager; | |
| 15 | 추가: import org.bukkit.event.EventHandler; | |
| 16 | 추가: import org.bukkit.event.Listener; | |
| 17 | 추가: import org.bukkit.event.inventory.ClickType; | |
| 18 | 추가: import org.bukkit.event.inventory.InventoryClickEvent; | |
| 19 | 추가: import org.bukkit.event.inventory.InventoryDragEvent; | |
| 20 | 추가: import org.bukkit.event.player.PlayerInteractEntityEvent; | |
| 21 | 추가: import org.bukkit.inventory.EquipmentSlot; | |
| 22 | 추가: import org.bukkit.inventory.Inventory; | |
| 23 | 추가: import org.bukkit.inventory.InventoryHolder; | |
| 24 | 추가: import org.bukkit.inventory.ItemStack; | |
| 25 | 추가: import org.bukkit.inventory.meta.ItemMeta; | |
| 26 | 추가: import org.bukkit.persistence.PersistentDataType; | |
| 27 | 추가: import org.bukkit.plugin.java.JavaPlugin; | |
| 28 | 추가: | |
| 29 | 추가: import java.util.List; | |
| 30 | 추가: | |
| 31 | 추가: /** | |
| 32 | 추가: * Fixture plugin for mc-tester. Not a real shop: it exists so the harness has a | |
| 33 | 추가: * realistic NPC -> chest GUI -> purchase flow to drive and assert against. | |
| 34 | 추가: * | |
| 35 | 추가: * /demoshop spawn [x y z] spawn the shop NPC (villager named "상점") | |
| 36 | 추가: * /demoshop balance <player> print JSON item counts (for RCON assertions) | |
| 37 | 추가: * /demoshop bug <on|off> when on, shift-click on the shop is NOT cancelled (dupe bug on purpose) | |
| 38 | 추가: */ | |
| 39 | 추가: public final class DemoShopPlugin extends JavaPlugin implements Listener { | |
| 40 | 추가: static final int PRICE = 5; | |
| 41 | 추가: static final int SLOT_DIAMOND = 11; | |
| 42 | 추가: static final int SLOT_INFO = 15; | |
| 43 | 추가: static final Component TITLE = Component.text("데모 상점"); | |
| 44 | 추가: | |
| 45 | 추가: private NamespacedKey npcKey; | |
| 46 | 추가: private volatile boolean bug = false; | |
| 47 | 추가: | |
| 48 | 추가: static final class ShopHolder implements InventoryHolder { | |
| 49 | 추가: Inventory inv; | |
| 50 | 추가: @Override public Inventory getInventory() { return inv; } | |
| 51 | 추가: } | |
| 52 | 추가: | |
| 53 | 추가: @Override | |
| 54 | 추가: public void onEnable() { | |
| 55 | 추가: npcKey = new NamespacedKey(this, "shop_npc"); | |
| 56 | 추가: Bukkit.getPluginManager().registerEvents(this, this); | |
| 57 | 추가: } | |
| 58 | 추가: | |
| 59 | 추가: @Override | |
| 60 | 추가: public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { | |
| 61 | 추가: if (args.length == 0) return false; | |
| 62 | 추가: switch (args[0]) { | |
| 63 | 추가: case "spawn" -> { | |
| 64 | 추가: Location loc; | |
| 65 | 추가: if (args.length >= 4) { | |
| 66 | 추가: loc = new Location(Bukkit.getWorlds().getFirst(), Double.parseDouble(args[1]), Double.parseDouble(args[2]), Double.parseDouble(args[3])); | |
| 67 | 추가: } else if (sender instanceof Player p) { | |
| 68 | 추가: loc = p.getLocation(); | |
| 69 | 추가: } else { | |
| 70 | 추가: loc = Bukkit.getWorlds().getFirst().getSpawnLocation(); | |
| 71 | 추가: } | |
| 72 | 추가: Villager v = loc.getWorld().spawn(loc, Villager.class, e -> { | |
| 73 | 추가: e.customName(Component.text("상점")); | |
| 74 | 추가: e.setCustomNameVisible(true); | |
| 75 | 추가: e.setAI(false); | |
| 76 | 추가: e.setInvulnerable(true); | |
| 77 | 추가: e.setSilent(true); | |
| 78 | 추가: e.setPersistent(true); | |
| 79 | 추가: e.getPersistentDataContainer().set(npcKey, PersistentDataType.BYTE, (byte) 1); | |
| 80 | 추가: }); | |
| 81 | 추가: sender.sendMessage("{\"spawned\":\"" + v.getUniqueId() + "\"}"); | |
| 82 | 추가: } | |
| 83 | 추가: case "balance" -> { | |
| 84 | 추가: if (args.length < 2) return false; | |
| 85 | 추가: Player p = Bukkit.getPlayerExact(args[1]); | |
| 86 | 추가: if (p == null) { sender.sendMessage("{\"error\":\"offline\"}"); return true; } | |
| 87 | 추가: sender.sendMessage("{\"player\":\"" + p.getName() + "\",\"emerald\":" + count(p, Material.EMERALD) | |
| 88 | 추가: + ",\"diamond\":" + count(p, Material.DIAMOND) + "}"); | |
| 89 | 추가: } | |
| 90 | 추가: case "bug" -> { | |
| 91 | 추가: bug = args.length > 1 && args[1].equalsIgnoreCase("on"); | |
| 92 | 추가: sender.sendMessage("{\"bug\":" + bug + "}"); | |
| 93 | 추가: } | |
| 94 | 추가: default -> { return false; } | |
| 95 | 추가: } | |
| 96 | 추가: return true; | |
| 97 | 추가: } | |
| 98 | 추가: | |
| 99 | 추가: private static int count(Player p, Material m) { | |
| 100 | 추가: int n = 0; | |
| 101 | 추가: for (ItemStack s : p.getInventory().getStorageContents()) if (s != null && s.getType() == m) n += s.getAmount(); | |
| 102 | 추가: ItemStack cursor = p.getItemOnCursor(); | |
| 103 | 추가: if (cursor.getType() == m) n += cursor.getAmount(); | |
| 104 | 추가: return n; | |
| 105 | 추가: } | |
| 106 | 추가: | |
| 107 | 추가: private Inventory createShop() { | |
| 108 | 추가: ShopHolder holder = new ShopHolder(); | |
| 109 | 추가: Inventory inv = Bukkit.createInventory(holder, 27, TITLE); | |
| 110 | 추가: holder.inv = inv; | |
| 111 | 추가: inv.setItem(SLOT_DIAMOND, named(Material.DIAMOND, Component.text("다이아몬드", NamedTextColor.AQUA), | |
| 112 | 추가: List.of(Component.text("가격: 에메랄드 " + PRICE + "개", NamedTextColor.GRAY), | |
| 113 | 추가: Component.text("좌클릭: 구매", NamedTextColor.YELLOW)))); | |
| 114 | 추가: inv.setItem(SLOT_INFO, named(Material.PAPER, Component.text("안내", NamedTextColor.WHITE), | |
| 115 | 추가: List.of(Component.text("에메랄드로 다이아몬드를 삽니다", NamedTextColor.GRAY)))); | |
| 116 | 추가: ItemStack pane = named(Material.GRAY_STAINED_GLASS_PANE, Component.text(" "), List.of()); | |
| 117 | 추가: for (int i = 0; i < 27; i++) if (inv.getItem(i) == null) inv.setItem(i, pane); | |
| 118 | 추가: return inv; | |
| 119 | 추가: } | |
| 120 | 추가: | |
| 121 | 추가: private static ItemStack named(Material m, Component name, List<Component> lore) { | |
| 122 | 추가: ItemStack s = new ItemStack(m); | |
| 123 | 추가: ItemMeta meta = s.getItemMeta(); | |
| 124 | 추가: meta.itemName(name.decoration(TextDecoration.ITALIC, false)); | |
| 125 | 추가: meta.lore(lore.stream().map(c -> c.decoration(TextDecoration.ITALIC, false)).toList()); | |
| 126 | 추가: s.setItemMeta(meta); | |
| 127 | 추가: return s; | |
| 128 | 추가: } | |
| 129 | 추가: | |
| 130 | 추가: @EventHandler | |
| 131 | 추가: public void onInteract(PlayerInteractEntityEvent e) { | |
| 132 | 추가: Entity en = e.getRightClicked(); | |
| 133 | 추가: if (!en.getPersistentDataContainer().has(npcKey)) return; | |
| 134 | 추가: e.setCancelled(true); | |
| 135 | 추가: if (e.getHand() != EquipmentSlot.HAND) return; | |
| 136 | 추가: Player p = e.getPlayer(); | |
| 137 | 추가: Bukkit.getScheduler().runTask(this, () -> p.openInventory(createShop())); | |
| 138 | 추가: } | |
| 139 | 추가: | |
| 140 | 추가: @EventHandler | |
| 141 | 추가: public void onClick(InventoryClickEvent e) { | |
| 142 | 추가: if (!(e.getView().getTopInventory().getHolder() instanceof ShopHolder)) return; | |
| 143 | 추가: Player p = (Player) e.getWhoClicked(); | |
| 144 | 추가: boolean top = e.getClickedInventory() == e.getView().getTopInventory(); | |
| 145 | 추가: if (bug && e.getClick() == ClickType.SHIFT_LEFT) { | |
| 146 | 추가: // Intentional dupe bug for harness self-test: shift-click is let through. | |
| 147 | 추가: return; | |
| 148 | 추가: } | |
| 149 | 추가: e.setCancelled(true); | |
| 150 | 추가: if (!top) return; | |
| 151 | 추가: if (e.getRawSlot() == SLOT_DIAMOND && e.getClick() == ClickType.LEFT) { | |
| 152 | 추가: if (count(p, Material.EMERALD) < PRICE) { | |
| 153 | 추가: p.sendMessage(Component.text("에메랄드가 부족합니다", NamedTextColor.RED)); | |
| 154 | 추가: return; | |
| 155 | 추가: } | |
| 156 | 추가: p.getInventory().removeItem(new ItemStack(Material.EMERALD, PRICE)); | |
| 157 | 추가: p.getInventory().addItem(new ItemStack(Material.DIAMOND, 1)); | |
| 158 | 추가: p.sendMessage(Component.text("구매 완료: 다이아몬드 1개", NamedTextColor.GREEN)); | |
| 159 | 추가: } | |
| 160 | 추가: } | |
| 161 | 추가: | |
| 162 | 추가: @EventHandler | |
| 163 | 추가: public void onDrag(InventoryDragEvent e) { | |
| 164 | 추가: if (e.getView().getTopInventory().getHolder() instanceof ShopHolder) e.setCancelled(true); | |
| 165 | 추가: } | |
| 166 | 추가: } |
| @@ -0,0 +1,13 @@ | ||
| 1 | 추가: name: DemoShop | |
| 2 | 추가: version: '${version}' | |
| 3 | 추가: main: dev.mctester.demoshop.DemoShopPlugin | |
| 4 | 추가: api-version: '26.3' | |
| 5 | 추가: description: mc-tester fixture - a tiny NPC chest-GUI shop used to verify the QA harness. | |
| 6 | 추가: commands: | |
| 7 | 추가: demoshop: | |
| 8 | 추가: description: DemoShop admin/test commands | |
| 9 | 추가: usage: /demoshop <spawn|balance|bug> ... | |
| 10 | 추가: permission: demoshop.admin | |
| 11 | 추가: permissions: | |
| 12 | 추가: demoshop.admin: | |
| 13 | 추가: default: op |
| @@ -0,0 +1,76 @@ | ||
| 1 | 추가: // Player identities for launched clients. | |
| 2 | 추가: // - offline: any name, UUID derived like the server does for offline players. Only works with online-mode=false. | |
| 3 | 추가: // - microsoft: your real Minecraft account via Microsoft device-code login (prismarine-auth). | |
| 4 | 추가: // Tokens are cached under .mct/auth (mode 700). The harness never prints them. | |
| 5 | 추가: import crypto from 'node:crypto'; | |
| 6 | 추가: import fs from 'node:fs'; | |
| 7 | 추가: import path from 'node:path'; | |
| 8 | 추가: import { DIRS } from './config.ts'; | |
| 9 | 추가: | |
| 10 | 추가: export interface Identity { | |
| 11 | 추가: name: string; | |
| 12 | 추가: uuid: string; | |
| 13 | 추가: accessToken: string; | |
| 14 | 추가: userType: 'msa' | 'legacy'; | |
| 15 | 추가: xuid: string; | |
| 16 | 추가: online: boolean; | |
| 17 | 추가: } | |
| 18 | 추가: | |
| 19 | 추가: export function offlineIdentity(name: string): Identity { | |
| 20 | 추가: if (!/^[A-Za-z0-9_]{3,16}$/.test(name)) throw new Error(`invalid player name '${name}' (3-16 chars, A-Z a-z 0-9 _)`); | |
| 21 | 추가: // Same as Java UUID.nameUUIDFromBytes("OfflinePlayer:" + name): MD5, version 3, IETF variant. | |
| 22 | 추가: const h = crypto.createHash('md5').update('OfflinePlayer:' + name, 'utf8').digest(); | |
| 23 | 추가: h[6] = (h[6] & 0x0f) | 0x30; | |
| 24 | 추가: h[8] = (h[8] & 0x3f) | 0x80; | |
| 25 | 추가: const hex = h.toString('hex'); | |
| 26 | 추가: const uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; | |
| 27 | 추가: return { name, uuid, accessToken: '0', userType: 'legacy', xuid: '0', online: false }; | |
| 28 | 추가: } | |
| 29 | 추가: | |
| 30 | 추가: export interface LoginPrompt { | |
| 31 | 추가: verificationUri: string; | |
| 32 | 추가: userCode: string; | |
| 33 | 추가: message: string; | |
| 34 | 추가: } | |
| 35 | 추가: | |
| 36 | 추가: /** | |
| 37 | 추가: * Microsoft login. On first use this needs a human: `onCode` receives the device-code prompt | |
| 38 | 추가: * (open the URL, enter the code). Later calls reuse/refresh the cached tokens silently. | |
| 39 | 추가: */ | |
| 40 | 추가: export async function microsoftIdentity(profileKey = 'default', onCode?: (p: LoginPrompt) => void, interactive = true): Promise<Identity> { | |
| 41 | 추가: const { Authflow, Titles } = await import('prismarine-auth'); | |
| 42 | 추가: const cache = path.join(DIRS.auth, profileKey); | |
| 43 | 추가: fs.mkdirSync(cache, { recursive: true, mode: 0o700 }); | |
| 44 | 추가: let needLogin: (e: Error) => void = () => {}; | |
| 45 | 추가: const loginRequired = new Promise<never>((_, reject) => (needLogin = reject)); | |
| 46 | 추가: const flow = new Authflow( | |
| 47 | 추가: profileKey, | |
| 48 | 추가: cache, | |
| 49 | 추가: { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }, | |
| 50 | 추가: (res: any) => { | |
| 51 | 추가: const p: LoginPrompt = { | |
| 52 | 추가: verificationUri: res.verification_uri ?? res.verificationUri, | |
| 53 | 추가: userCode: res.user_code ?? res.userCode, | |
| 54 | 추가: message: res.message, | |
| 55 | 추가: }; | |
| 56 | 추가: if (!interactive) { | |
| 57 | 추가: needLogin(new Error(`Microsoft login required for profile '${profileKey}'. A human must run: npm run mct -- login ${profileKey}`)); | |
| 58 | 추가: return; | |
| 59 | 추가: } | |
| 60 | 추가: if (onCode) onCode(p); | |
| 61 | 추가: else console.error(p.message); | |
| 62 | 추가: }, | |
| 63 | 추가: ); | |
| 64 | 추가: const tok: any = await Promise.race([flow.getMinecraftJavaToken({ fetchProfile: true }), loginRequired]); | |
| 65 | 추가: if (!tok?.profile?.id) { | |
| 66 | 추가: throw new Error('Microsoft account has no Minecraft: Java Edition profile (does this account own Java Edition?)'); | |
| 67 | 추가: } | |
| 68 | 추가: const raw = String(tok.profile.id).replace(/-/g, ''); | |
| 69 | 추가: const uuid = `${raw.slice(0, 8)}-${raw.slice(8, 12)}-${raw.slice(12, 16)}-${raw.slice(16, 20)}-${raw.slice(20)}`; | |
| 70 | 추가: return { name: tok.profile.name, uuid, accessToken: tok.token, userType: 'msa', xuid: '0', online: true }; | |
| 71 | 추가: } | |
| 72 | 추가: | |
| 73 | 추가: export function hasMicrosoftCache(profileKey = 'default'): boolean { | |
| 74 | 추가: const dir = path.join(DIRS.auth, profileKey); | |
| 75 | 추가: return fs.existsSync(dir) && fs.readdirSync(dir).length > 0; | |
| 76 | 추가: } |
| @@ -0,0 +1,68 @@ | ||
| 1 | 추가: // CLI for humans, CI and agents without MCP: | |
| 2 | 추가: // npm run mct -- <tool> [key=value ... | '{json}'] | |
| 3 | 추가: // npm run mct -- scenario scenarios/demo-shop.yaml | |
| 4 | 추가: // npm run mct -- login [profile] (Microsoft device-code login, needs a human) | |
| 5 | 추가: // npm run mct -- tools | daemon-stop | daemon-status | |
| 6 | 추가: import { TOOLS, TOOL_MAP } from './tools.ts'; | |
| 7 | 추가: import { call, daemonUp, shutdownDaemon } from './rpc.ts'; | |
| 8 | 추가: import { ensureDirs } from './config.ts'; | |
| 9 | 추가: import { microsoftIdentity } from './auth.ts'; | |
| 10 | 추가: | |
| 11 | 추가: function parseArgs(rest: string[]): Record<string, unknown> { | |
| 12 | 추가: if (rest.length === 1 && rest[0].trim().startsWith('{')) return JSON.parse(rest[0]); | |
| 13 | 추가: const out: Record<string, unknown> = {}; | |
| 14 | 추가: for (const a of rest) { | |
| 15 | 추가: const i = a.indexOf('='); | |
| 16 | 추가: if (i < 0) throw new Error(`expected key=value, got '${a}'`); | |
| 17 | 추가: const k = a.slice(0, i); | |
| 18 | 추가: const v = a.slice(i + 1); | |
| 19 | 추가: if (v === 'true' || v === 'false') out[k] = v === 'true'; | |
| 20 | 추가: else if (v !== '' && !Number.isNaN(Number(v)) && /^-?[\d.]+$/.test(v)) out[k] = Number(v); | |
| 21 | 추가: else if (v.startsWith('[') || v.startsWith('{')) out[k] = JSON.parse(v); | |
| 22 | 추가: else out[k] = v; | |
| 23 | 추가: } | |
| 24 | 추가: return out; | |
| 25 | 추가: } | |
| 26 | 추가: | |
| 27 | 추가: async function main() { | |
| 28 | 추가: const [cmd, ...rest] = process.argv.slice(2); | |
| 29 | 추가: if (!cmd || cmd === 'help' || cmd === '--help') { | |
| 30 | 추가: console.log('usage: npm run mct -- <tool> [key=value ...]\n npm run mct -- scenario <file.yaml>\n npm run mct -- login [profile]\n npm run mct -- tools | daemon-status | daemon-stop'); | |
| 31 | 추가: return; | |
| 32 | 추가: } | |
| 33 | 추가: if (cmd === 'tools') { | |
| 34 | 추가: for (const t of TOOLS) console.log(`${t.name.padEnd(18)} ${Object.keys(t.shape).join(', ')}`); | |
| 35 | 추가: return; | |
| 36 | 추가: } | |
| 37 | 추가: if (cmd === 'daemon-status') { | |
| 38 | 추가: console.log(JSON.stringify({ running: await daemonUp() })); | |
| 39 | 추가: return; | |
| 40 | 추가: } | |
| 41 | 추가: if (cmd === 'daemon-stop') { | |
| 42 | 추가: console.log(JSON.stringify({ stopped: await shutdownDaemon() })); | |
| 43 | 추가: return; | |
| 44 | 추가: } | |
| 45 | 추가: if (cmd === 'login') { | |
| 46 | 추가: ensureDirs(); | |
| 47 | 추가: const profile = rest[0] ?? 'default'; | |
| 48 | 추가: const id = await microsoftIdentity(profile, (p) => { | |
| 49 | 추가: console.log(`\nOpen ${p.verificationUri} and enter the code: ${p.userCode}\n`); | |
| 50 | 추가: }); | |
| 51 | 추가: console.log(JSON.stringify({ loggedIn: true, profile, minecraftName: id.name, uuid: id.uuid })); | |
| 52 | 추가: return; | |
| 53 | 추가: } | |
| 54 | 추가: if (cmd === 'scenario') { | |
| 55 | 추가: const r = await call('run_scenario', { file: rest[0], stop_on_fail: true }); | |
| 56 | 추가: console.log(JSON.stringify(r, null, 2)); | |
| 57 | 추가: process.exitCode = r.passed ? 0 : 1; | |
| 58 | 추가: return; | |
| 59 | 추가: } | |
| 60 | 추가: if (!TOOL_MAP.has(cmd)) throw new Error(`unknown tool '${cmd}' (npm run mct -- tools)`); | |
| 61 | 추가: const r = await call(cmd, parseArgs(rest)); | |
| 62 | 추가: console.log(JSON.stringify(r, null, 2)); | |
| 63 | 추가: } | |
| 64 | 추가: | |
| 65 | 추가: main().catch((e) => { | |
| 66 | 추가: console.error(`error: ${(e as Error).message}`); | |
| 67 | 추가: process.exitCode = 1; | |
| 68 | 추가: }); |
| @@ -0,0 +1,270 @@ | ||
| 1 | 추가: // Launches and talks to real Minecraft clients (each with the QA Bridge mod on its own localhost port). | |
| 2 | 추가: import fs from 'node:fs'; | |
| 3 | 추가: import path from 'node:path'; | |
| 4 | 추가: import net from 'node:net'; | |
| 5 | 추가: import { spawn, type ChildProcess } from 'node:child_process'; | |
| 6 | 추가: import { DIRS, type Config } from './config.ts'; | |
| 7 | 추가: import { install, plan, redactArgs } from './launcher.ts'; | |
| 8 | 추가: import { hasMicrosoftCache, microsoftIdentity, offlineIdentity, type Identity } from './auth.ts'; | |
| 9 | 추가: import { sleep } from './paper.ts'; | |
| 10 | 추가: | |
| 11 | 추가: export interface LaunchOptions { | |
| 12 | 추가: account?: 'offline' | 'microsoft'; | |
| 13 | 추가: /** Microsoft token cache profile (see `mct login`). */ | |
| 14 | 추가: msProfile?: string; | |
| 15 | 추가: /** Server to join on startup; true/undefined = the harness server, false = stay on title screen. */ | |
| 16 | 추가: connect?: boolean | string; | |
| 17 | 추가: display?: 'xvfb' | 'host'; | |
| 18 | 추가: timeoutMs?: number; | |
| 19 | 추가: } | |
| 20 | 추가: | |
| 21 | 추가: interface ClientProc { | |
| 22 | 추가: key: string; | |
| 23 | 추가: name: string; | |
| 24 | 추가: account: 'offline' | 'microsoft'; | |
| 25 | 추가: port: number; | |
| 26 | 추가: proc: ChildProcess; | |
| 27 | 추가: xvfb: ChildProcess | null; | |
| 28 | 추가: display: string; | |
| 29 | 추가: gameDir: string; | |
| 30 | 추가: startedAt: number; | |
| 31 | 추가: tail: string[]; | |
| 32 | 추가: exit: string | null; | |
| 33 | 추가: } | |
| 34 | 추가: | |
| 35 | 추가: export class BridgeError extends Error { | |
| 36 | 추가: status: number; | |
| 37 | 추가: constructor(message: string, status: number) { | |
| 38 | 추가: super(message); | |
| 39 | 추가: this.status = status; | |
| 40 | 추가: } | |
| 41 | 추가: } | |
| 42 | 추가: | |
| 43 | 추가: function portFree(port: number): Promise<boolean> { | |
| 44 | 추가: return new Promise((resolve) => { | |
| 45 | 추가: const s = net.createServer(); | |
| 46 | 추가: s.once('error', () => resolve(false)); | |
| 47 | 추가: s.listen(port, '127.0.0.1', () => s.close(() => resolve(true))); | |
| 48 | 추가: }); | |
| 49 | 추가: } | |
| 50 | 추가: | |
| 51 | 추가: export class ClientManager { | |
| 52 | 추가: private cfg: Config; | |
| 53 | 추가: private clients = new Map<string, ClientProc>(); | |
| 54 | 추가: private serverAddress: () => string; | |
| 55 | 추가: log: (m: string) => void; | |
| 56 | 추가: | |
| 57 | 추가: constructor(cfg: Config, serverAddress: () => string, log: (m: string) => void = () => {}) { | |
| 58 | 추가: this.cfg = cfg; | |
| 59 | 추가: this.serverAddress = serverAddress; | |
| 60 | 추가: this.log = log; | |
| 61 | 추가: } | |
| 62 | 추가: | |
| 63 | 추가: list() { | |
| 64 | 추가: return [...this.clients.values()].map((c) => ({ | |
| 65 | 추가: name: c.name, | |
| 66 | 추가: account: c.account, | |
| 67 | 추가: bridgePort: c.port, | |
| 68 | 추가: display: c.display, | |
| 69 | 추가: pid: c.proc.pid, | |
| 70 | 추가: running: c.proc.exitCode === null, | |
| 71 | 추가: exit: c.exit, | |
| 72 | 추가: uptimeSec: Math.round((Date.now() - c.startedAt) / 1000), | |
| 73 | 추가: })); | |
| 74 | 추가: } | |
| 75 | 추가: | |
| 76 | 추가: /** Resolve a client by name; if omitted and exactly one client runs, use it. */ | |
| 77 | 추가: get(name?: string): ClientProc { | |
| 78 | 추가: if (!name) { | |
| 79 | 추가: const running = [...this.clients.values()].filter((c) => c.proc.exitCode === null); | |
| 80 | 추가: if (running.length === 1) return running[0]; | |
| 81 | 추가: if (running.length === 0) throw new Error('no client is running (call client_launch first)'); | |
| 82 | 추가: throw new Error(`several clients are running (${running.map((c) => c.name).join(', ')}); pass client`); | |
| 83 | 추가: } | |
| 84 | 추가: const c = this.clients.get(name.toLowerCase()); | |
| 85 | 추가: if (!c) throw new Error(`no client named '${name}'. Running: ${this.list().map((x) => x.name).join(', ') || '(none)'}`); | |
| 86 | 추가: if (c.proc.exitCode !== null) throw new Error(`client '${name}' has exited (${c.exit}). Last output:\n${c.tail.slice(-30).join('\n')}`); | |
| 87 | 추가: return c; | |
| 88 | 추가: } | |
| 89 | 추가: | |
| 90 | 추가: async call(name: string | undefined, route: string, body: object = {}, timeoutMs = 30_000): Promise<any> { | |
| 91 | 추가: const c = this.get(name); | |
| 92 | 추가: return this.callPort(c.port, route, body, timeoutMs); | |
| 93 | 추가: } | |
| 94 | 추가: | |
| 95 | 추가: private async callPort(port: number, route: string, body: object, timeoutMs: number): Promise<any> { | |
| 96 | 추가: const res = await fetch(`http://127.0.0.1:${port}/${route.replace(/^\//, '')}`, { | |
| 97 | 추가: method: 'POST', | |
| 98 | 추가: headers: { 'Content-Type': 'application/json' }, | |
| 99 | 추가: body: JSON.stringify(body), | |
| 100 | 추가: signal: AbortSignal.timeout(timeoutMs), | |
| 101 | 추가: }); | |
| 102 | 추가: const json: any = await res.json(); | |
| 103 | 추가: if (!json.ok) throw new BridgeError(json.error ?? `bridge ${route} failed`, res.status); | |
| 104 | 추가: delete json.ok; | |
| 105 | 추가: return json; | |
| 106 | 추가: } | |
| 107 | 추가: | |
| 108 | 추가: private async nextPort(): Promise<number> { | |
| 109 | 추가: const used = new Set([...this.clients.values()].filter((c) => c.proc.exitCode === null).map((c) => c.port)); | |
| 110 | 추가: for (let p = this.cfg.client.bridgeBasePort; p < this.cfg.client.bridgeBasePort + 100; p++) { | |
| 111 | 추가: if (!used.has(p) && (await portFree(p))) return p; | |
| 112 | 추가: } | |
| 113 | 추가: throw new Error('no free bridge port'); | |
| 114 | 추가: } | |
| 115 | 추가: | |
| 116 | 추가: private async startXvfb(): Promise<{ proc: ChildProcess; display: string }> { | |
| 117 | 추가: const { width, height } = this.cfg.client; | |
| 118 | 추가: for (let n = 140; n < 240; n++) { | |
| 119 | 추가: if (fs.existsSync(`/tmp/.X11-unix/X${n}`) || fs.existsSync(`/tmp/.X${n}-lock`)) continue; | |
| 120 | 추가: const proc = spawn('Xvfb', [`:${n}`, '-screen', '0', `${width}x${height}x24`, '-nolisten', 'tcp', '-noreset', '+extension', 'GLX'], { | |
| 121 | 추가: stdio: 'ignore', | |
| 122 | 추가: }); | |
| 123 | 추가: const t0 = Date.now(); | |
| 124 | 추가: while (Date.now() - t0 < 5000) { | |
| 125 | 추가: if (fs.existsSync(`/tmp/.X11-unix/X${n}`)) return { proc, display: `:${n}` }; | |
| 126 | 추가: if (proc.exitCode !== null) break; | |
| 127 | 추가: await sleep(100); | |
| 128 | 추가: } | |
| 129 | 추가: proc.kill(); | |
| 130 | 추가: } | |
| 131 | 추가: throw new Error('could not start Xvfb (is it installed? `sudo apt install xvfb`)'); | |
| 132 | 추가: } | |
| 133 | 추가: | |
| 134 | 추가: async launch(name: string, opts: LaunchOptions = {}): Promise<object> { | |
| 135 | 추가: const key = name.toLowerCase(); | |
| 136 | 추가: const existing = this.clients.get(key); | |
| 137 | 추가: if (existing && existing.proc.exitCode === null) return { alreadyRunning: true, ...(await this.call(name, 'state')) }; | |
| 138 | 추가: | |
| 139 | 추가: const account = opts.account ?? 'offline'; | |
| 140 | 추가: let who: Identity; | |
| 141 | 추가: if (account === 'microsoft') { | |
| 142 | 추가: const profile = opts.msProfile ?? 'default'; | |
| 143 | 추가: if (!hasMicrosoftCache(profile)) { | |
| 144 | 추가: throw new Error(`Microsoft account not logged in for profile '${profile}'. A human must run: npm run mct -- login ${profile}`); | |
| 145 | 추가: } | |
| 146 | 추가: who = await microsoftIdentity(profile, undefined, false); | |
| 147 | 추가: } else { | |
| 148 | 추가: if (this.cfg.server.onlineMode && opts.connect !== false && typeof opts.connect !== 'string') { | |
| 149 | 추가: throw new Error('server is online-mode: offline test players cannot join. Use account "microsoft" or set server.onlineMode=false'); | |
| 150 | 추가: } | |
| 151 | 추가: who = offlineIdentity(name); | |
| 152 | 추가: } | |
| 153 | 추가: | |
| 154 | 추가: this.log(`client ${who.name}: preparing install`); | |
| 155 | 추가: const inst = await install(this.cfg, this.log); | |
| 156 | 추가: const port = await this.nextPort(); | |
| 157 | 추가: const gameDir = path.join(DIRS.clients, who.name); | |
| 158 | 추가: const connect = opts.connect === false ? null : typeof opts.connect === 'string' ? opts.connect : this.serverAddress(); | |
| 159 | 추가: const lp = await plan(this.cfg, inst, who, { gameDir, bridgePort: port, connect }); | |
| 160 | 추가: | |
| 161 | 추가: const displayMode = opts.display ?? this.cfg.client.display; | |
| 162 | 추가: let xvfb: ChildProcess | null = null; | |
| 163 | 추가: const env: NodeJS.ProcessEnv = { ...process.env, QA_BRIDGE_PORT: String(port) }; | |
| 164 | 추가: let display = 'host'; | |
| 165 | 추가: if (displayMode === 'xvfb') { | |
| 166 | 추가: const x = await this.startXvfb(); | |
| 167 | 추가: xvfb = x.proc; | |
| 168 | 추가: display = x.display; | |
| 169 | 추가: env.DISPLAY = x.display; | |
| 170 | 추가: delete env.WAYLAND_DISPLAY; | |
| 171 | 추가: env.SDL_VIDEODRIVER = 'x11'; | |
| 172 | 추가: env.__GLX_VENDOR_LIBRARY_NAME = 'mesa'; | |
| 173 | 추가: env.LIBGL_ALWAYS_SOFTWARE = '1'; | |
| 174 | 추가: } | |
| 175 | 추가: | |
| 176 | 추가: const outFile = path.join(gameDir, 'mct-client.log'); | |
| 177 | 추가: fs.writeFileSync(outFile, `# ${new Date().toISOString()} java ${redactArgs(lp.args).join(' ')}\n`); | |
| 178 | 추가: const proc = spawn(lp.command, lp.args, { cwd: lp.cwd, env, stdio: ['ignore', 'pipe', 'pipe'] }); | |
| 179 | 추가: const c: ClientProc = { | |
| 180 | 추가: key, | |
| 181 | 추가: name: who.name, | |
| 182 | 추가: account, | |
| 183 | 추가: port, | |
| 184 | 추가: proc, | |
| 185 | 추가: xvfb, | |
| 186 | 추가: display, | |
| 187 | 추가: gameDir, | |
| 188 | 추가: startedAt: Date.now(), | |
| 189 | 추가: tail: [], | |
| 190 | 추가: exit: null, | |
| 191 | 추가: }; | |
| 192 | 추가: this.clients.set(key, c); | |
| 193 | 추가: const out = fs.createWriteStream(outFile, { flags: 'a' }); | |
| 194 | 추가: const onData = (d: Buffer) => { | |
| 195 | 추가: out.write(d); | |
| 196 | 추가: for (const line of d.toString('utf8').split('\n')) if (line.trim()) c.tail.push(line); | |
| 197 | 추가: if (c.tail.length > 400) c.tail.splice(0, c.tail.length - 400); | |
| 198 | 추가: }; | |
| 199 | 추가: proc.stdout!.on('data', onData); | |
| 200 | 추가: proc.stderr!.on('data', onData); | |
| 201 | 추가: proc.on('exit', (code, sig) => { | |
| 202 | 추가: c.exit = `code=${code} signal=${sig}`; | |
| 203 | 추가: out.end(); | |
| 204 | 추가: xvfb?.kill(); | |
| 205 | 추가: }); | |
| 206 | 추가: | |
| 207 | 추가: const timeout = opts.timeoutMs ?? 240_000; | |
| 208 | 추가: const t0 = Date.now(); | |
| 209 | 추가: this.log(`client ${who.name}: starting (bridge :${port}, display ${display})`); | |
| 210 | 추가: // 1) wait for the bridge HTTP server (mod initialised) | |
| 211 | 추가: for (;;) { | |
| 212 | 추가: if (proc.exitCode !== null) throw new Error(`client exited during startup (${c.exit}). Log: ${outFile}\n${c.tail.slice(-40).join('\n')}`); | |
| 213 | 추가: if (Date.now() - t0 > timeout) throw new Error(`client bridge not up after ${timeout}ms. Log: ${outFile}`); | |
| 214 | 추가: try { | |
| 215 | 추가: await this.callPort(port, 'health', {}, 2000); | |
| 216 | 추가: break; | |
| 217 | 추가: } catch { | |
| 218 | 추가: await sleep(500); | |
| 219 | 추가: } | |
| 220 | 추가: } | |
| 221 | 추가: // 2) optionally wait until we are in the world | |
| 222 | 추가: let state: any = await this.callPort(port, 'state', {}, 10_000); | |
| 223 | 추가: if (connect) { | |
| 224 | 추가: for (;;) { | |
| 225 | 추가: if (proc.exitCode !== null) throw new Error(`client exited while connecting (${c.exit}). Log: ${outFile}`); | |
| 226 | 추가: state = await this.callPort(port, 'state', {}, 10_000); | |
| 227 | 추가: if (state.inWorld && !state.screen?.open) break; | |
| 228 | 추가: if (state.inWorld && state.screen?.class && !/Loading|Receiving|Connect/i.test(state.screen.class)) break; | |
| 229 | 추가: if (state.screen?.class === 'DisconnectedScreen') { | |
| 230 | 추가: const scr = await this.callPort(port, 'screen', {}, 10_000); | |
| 231 | 추가: throw new Error(`client was disconnected while joining ${connect}: ${JSON.stringify(scr.widgets?.map((w: any) => w.label))}`); | |
| 232 | 추가: } | |
| 233 | 추가: if (Date.now() - t0 > timeout) throw new Error(`client not in world after ${timeout}ms (screen: ${state.screen?.class})`); | |
| 234 | 추가: await sleep(500); | |
| 235 | 추가: } | |
| 236 | 추가: } | |
| 237 | 추가: return { launched: who.name, account, bridgePort: port, display, seconds: (Date.now() - t0) / 1000, connectedTo: connect, state }; | |
| 238 | 추가: } | |
| 239 | 추가: | |
| 240 | 추가: async stop(name: string | undefined): Promise<object> { | |
| 241 | 추가: const c = this.get(name); | |
| 242 | 추가: try { | |
| 243 | 추가: await this.callPort(c.port, 'quit', {}, 3000); | |
| 244 | 추가: } catch { | |
| 245 | 추가: /* ignore */ | |
| 246 | 추가: } | |
| 247 | 추가: const t0 = Date.now(); | |
| 248 | 추가: while (c.proc.exitCode === null && Date.now() - t0 < 20_000) await sleep(200); | |
| 249 | 추가: if (c.proc.exitCode === null) c.proc.kill('SIGKILL'); | |
| 250 | 추가: c.xvfb?.kill(); | |
| 251 | 추가: this.clients.delete(c.key); | |
| 252 | 추가: return { stopped: c.name }; | |
| 253 | 추가: } | |
| 254 | 추가: | |
| 255 | 추가: async stopAll(): Promise<void> { | |
| 256 | 추가: for (const c of [...this.clients.values()]) { | |
| 257 | 추가: if (c.proc.exitCode === null) await this.stop(c.name).catch(() => c.proc.kill('SIGKILL')); | |
| 258 | 추가: c.xvfb?.kill(); | |
| 259 | 추가: } | |
| 260 | 추가: this.clients.clear(); | |
| 261 | 추가: } | |
| 262 | 추가: | |
| 263 | 추가: running(): string[] { | |
| 264 | 추가: return [...this.clients.values()].filter((c) => c.proc.exitCode === null).map((c) => c.name); | |
| 265 | 추가: } | |
| 266 | 추가: | |
| 267 | 추가: artifactsDir(): string { | |
| 268 | 추가: return DIRS.artifacts; | |
| 269 | 추가: } | |
| 270 | 추가: } |
| @@ -0,0 +1,166 @@ | ||
| 1 | 추가: // Loads mct.config.json (optional) and resolves every runtime path under .mct/. | |
| 2 | 추가: import fs from 'node:fs'; | |
| 3 | 추가: import path from 'node:path'; | |
| 4 | 추가: import crypto from 'node:crypto'; | |
| 5 | 추가: | |
| 6 | 추가: export const ROOT = path.resolve(import.meta.dirname, '..'); | |
| 7 | 추가: | |
| 8 | 추가: export interface Config { | |
| 9 | 추가: mcVersion: string; | |
| 10 | 추가: fabricLoader: string; | |
| 11 | 추가: fabricApi: string; | |
| 12 | 추가: daemonPort: number; | |
| 13 | 추가: server: { | |
| 14 | 추가: paperBuild: 'latest' | number; | |
| 15 | 추가: port: number; | |
| 16 | 추가: rconPort: number; | |
| 17 | 추가: memory: string; | |
| 18 | 추가: /** false = offline mode on 127.0.0.1 (many test players). true = real auth (Microsoft account clients only). */ | |
| 19 | 추가: onlineMode: boolean; | |
| 20 | 추가: /** Plugin jars to copy into plugins/ on every start. Globs relative to the repo root (only * in the file name). */ | |
| 21 | 추가: plugins: string[]; | |
| 22 | 추가: /** Extra server.properties overrides. */ | |
| 23 | 추가: properties: Record<string, string | number | boolean>; | |
| 24 | 추가: /** Commands run over RCON right after every start (gamerules etc.). */ | |
| 25 | 추가: onStart: string[]; | |
| 26 | 추가: /** What a world snapshot captures, relative to the server dir. `dir/*` = every subdirectory. */ | |
| 27 | 추가: snapshotInclude: string[]; | |
| 28 | 추가: }; | |
| 29 | 추가: client: { | |
| 30 | 추가: memory: string; | |
| 31 | 추가: /** "xvfb" = invisible virtual display per client, "host" = open a window on your desktop. */ | |
| 32 | 추가: display: 'xvfb' | 'host'; | |
| 33 | 추가: width: number; | |
| 34 | 추가: height: number; | |
| 35 | 추가: guiScale: number; | |
| 36 | 추가: /** Auto-accept server resource packs (no confirmation screen blocking automated joins). */ | |
| 37 | 추가: acceptServerResourcePacks: boolean; | |
| 38 | 추가: /** Suppress toast popups (recipe unlocked, chat warnings) so they don't cover screenshots. */ | |
| 39 | 추가: hideToasts: boolean; | |
| 40 | 추가: /** Client UI language, e.g. ko_kr / en_us. */ | |
| 41 | 추가: lang: string; | |
| 42 | 추가: bridgeBasePort: number; | |
| 43 | 추가: /** Extra mod jars (globs relative to repo root) to load in every client, e.g. a client-side resource helper. */ | |
| 44 | 추가: extraMods: string[]; | |
| 45 | 추가: }; | |
| 46 | 추가: } | |
| 47 | 추가: | |
| 48 | 추가: const DEFAULTS: Config = { | |
| 49 | 추가: mcVersion: '26.3', | |
| 50 | 추가: fabricLoader: '0.20.1', | |
| 51 | 추가: fabricApi: '0.166.2+26.3', | |
| 52 | 추가: daemonPort: 7770, | |
| 53 | 추가: server: { | |
| 54 | 추가: paperBuild: 'latest', | |
| 55 | 추가: port: 25565, | |
| 56 | 추가: rconPort: 25575, | |
| 57 | 추가: memory: '4G', | |
| 58 | 추가: onlineMode: false, | |
| 59 | 추가: plugins: ['fixtures/demo-shop/build/libs/demo-shop-*.jar'], | |
| 60 | 추가: properties: {}, | |
| 61 | 추가: onStart: [ | |
| 62 | 추가: 'gamerule advance_time false', | |
| 63 | 추가: 'gamerule advance_weather false', | |
| 64 | 추가: 'gamerule spawn_mobs false', | |
| 65 | 추가: 'time set day', | |
| 66 | 추가: 'weather clear', | |
| 67 | 추가: ], | |
| 68 | 추가: snapshotInclude: ['world', 'world_nether', 'world_the_end', 'plugins/*'], | |
| 69 | 추가: }, | |
| 70 | 추가: client: { | |
| 71 | 추가: memory: '3G', | |
| 72 | 추가: display: 'xvfb', | |
| 73 | 추가: width: 1280, | |
| 74 | 추가: height: 720, | |
| 75 | 추가: guiScale: 2, | |
| 76 | 추가: lang: 'ko_kr', | |
| 77 | 추가: hideToasts: true, | |
| 78 | 추가: acceptServerResourcePacks: true, | |
| 79 | 추가: bridgeBasePort: 7800, | |
| 80 | 추가: extraMods: [], | |
| 81 | 추가: }, | |
| 82 | 추가: }; | |
| 83 | 추가: | |
| 84 | 추가: function merge<T>(base: T, over: unknown): T { | |
| 85 | 추가: if (over === undefined || over === null) return base; | |
| 86 | 추가: if (typeof base !== 'object' || Array.isArray(base) || base === null) return over as T; | |
| 87 | 추가: const out: Record<string, unknown> = { ...(base as Record<string, unknown>) }; | |
| 88 | 추가: for (const [k, v] of Object.entries(over as Record<string, unknown>)) { | |
| 89 | 추가: out[k] = merge((base as Record<string, unknown>)[k], v); | |
| 90 | 추가: } | |
| 91 | 추가: return out as T; | |
| 92 | 추가: } | |
| 93 | 추가: | |
| 94 | 추가: export function configPath(): string { | |
| 95 | 추가: return process.env.MCT_CONFIG ?? path.join(ROOT, 'mct.config.json'); | |
| 96 | 추가: } | |
| 97 | 추가: | |
| 98 | 추가: /** Read mct.config.json as the user wrote it (only their overrides, no defaults). */ | |
| 99 | 추가: export function readUserConfig(): Record<string, any> { | |
| 100 | 추가: const file = configPath(); | |
| 101 | 추가: return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {}; | |
| 102 | 추가: } | |
| 103 | 추가: | |
| 104 | 추가: /** Apply a change to mct.config.json, keeping everything else the user wrote. */ | |
| 105 | 추가: export function updateUserConfig(change: (c: Record<string, any>) => void): string { | |
| 106 | 추가: const file = configPath(); | |
| 107 | 추가: const c = readUserConfig(); | |
| 108 | 추가: change(c); | |
| 109 | 추가: const tmp = file + '.tmp'; | |
| 110 | 추가: fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + '\n'); | |
| 111 | 추가: fs.renameSync(tmp, file); | |
| 112 | 추가: return file; | |
| 113 | 추가: } | |
| 114 | 추가: | |
| 115 | 추가: export function loadConfig(): Config { | |
| 116 | 추가: const file = configPath(); | |
| 117 | 추가: let user: unknown = {}; | |
| 118 | 추가: if (fs.existsSync(file)) user = JSON.parse(fs.readFileSync(file, 'utf8')); | |
| 119 | 추가: const cfg = merge(DEFAULTS, user); | |
| 120 | 추가: if (process.env.MCT_DISPLAY === 'host' || process.env.MCT_DISPLAY === 'xvfb') cfg.client.display = process.env.MCT_DISPLAY; | |
| 121 | 추가: return cfg; | |
| 122 | 추가: } | |
| 123 | 추가: | |
| 124 | 추가: export const DIRS = { | |
| 125 | 추가: root: path.join(ROOT, '.mct'), | |
| 126 | 추가: cache: path.join(ROOT, '.mct', 'cache'), | |
| 127 | 추가: server: path.join(ROOT, '.mct', 'server'), | |
| 128 | 추가: snapshots: path.join(ROOT, '.mct', 'snapshots'), | |
| 129 | 추가: clients: path.join(ROOT, '.mct', 'clients'), | |
| 130 | 추가: artifacts: path.join(ROOT, '.mct', 'artifacts'), | |
| 131 | 추가: reports: path.join(ROOT, '.mct', 'reports'), | |
| 132 | 추가: auth: path.join(ROOT, '.mct', 'auth'), | |
| 133 | 추가: run: path.join(ROOT, '.mct', 'run'), | |
| 134 | 추가: }; | |
| 135 | 추가: | |
| 136 | 추가: export function ensureDirs(): void { | |
| 137 | 추가: for (const d of Object.values(DIRS)) fs.mkdirSync(d, { recursive: true }); | |
| 138 | 추가: } | |
| 139 | 추가: | |
| 140 | 추가: /** Local secrets (RCON password). Never printed by the harness. */ | |
| 141 | 추가: export function secrets(): { rconPassword: string } { | |
| 142 | 추가: const file = path.join(DIRS.root, 'secrets.json'); | |
| 143 | 추가: if (fs.existsSync(file)) return JSON.parse(fs.readFileSync(file, 'utf8')); | |
| 144 | 추가: const s = { rconPassword: crypto.randomBytes(18).toString('base64url') }; | |
| 145 | 추가: fs.mkdirSync(DIRS.root, { recursive: true }); | |
| 146 | 추가: fs.writeFileSync(file, JSON.stringify(s, null, 2), { mode: 0o600 }); | |
| 147 | 추가: return s; | |
| 148 | 추가: } | |
| 149 | 추가: | |
| 150 | 추가: /** Expand `dir/name-*.jar` style globs (wildcards only in the last path segment). */ | |
| 151 | 추가: export function expandGlob(pattern: string, base = ROOT): string[] { | |
| 152 | 추가: const abs = path.isAbsolute(pattern) ? pattern : path.join(base, pattern); | |
| 153 | 추가: const dir = path.dirname(abs); | |
| 154 | 추가: const name = path.basename(abs); | |
| 155 | 추가: if (!name.includes('*')) return fs.existsSync(abs) ? [abs] : []; | |
| 156 | 추가: if (!fs.existsSync(dir)) return []; | |
| 157 | 추가: const re = new RegExp('^' + name.split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*') + '$'); | |
| 158 | 추가: return fs | |
| 159 | 추가: .readdirSync(dir) | |
| 160 | 추가: .filter((f) => re.test(f) && !/-(sources|javadoc|dev)\.jar$/.test(f)) | |
| 161 | 추가: .map((f) => path.join(dir, f)); | |
| 162 | 추가: } | |
| 163 | 추가: | |
| 164 | 추가: export function stamp(): string { | |
| 165 | 추가: return new Date().toISOString().replace(/[:.]/g, '-'); | |
| 166 | 추가: } |
| @@ -0,0 +1,101 @@ | ||
| 1 | 추가: // Long-lived harness daemon: owns the Paper server and all clients so several agents / MCP sessions | |
| 2 | 추가: // can share them. JSON RPC over http://127.0.0.1:<daemonPort>. | |
| 3 | 추가: import http from 'node:http'; | |
| 4 | 추가: import fs from 'node:fs'; | |
| 5 | 추가: import path from 'node:path'; | |
| 6 | 추가: import { z } from 'zod'; | |
| 7 | 추가: import { DIRS, ensureDirs, loadConfig } from './config.ts'; | |
| 8 | 추가: import { PaperServer } from './paper.ts'; | |
| 9 | 추가: import { ClientManager } from './clients.ts'; | |
| 10 | 추가: import { TOOLS, TOOL_MAP, type Ctx } from './tools.ts'; | |
| 11 | 추가: import { runScenario } from './scenario.ts'; | |
| 12 | 추가: | |
| 13 | 추가: ensureDirs(); | |
| 14 | 추가: const cfg = loadConfig(); | |
| 15 | 추가: const logFile = fs.createWriteStream(path.join(DIRS.run, 'daemon.log'), { flags: 'a' }); | |
| 16 | 추가: const log = (m: string) => { | |
| 17 | 추가: const line = `${new Date().toISOString()} ${m}\n`; | |
| 18 | 추가: logFile.write(line); | |
| 19 | 추가: process.stderr.write(line); | |
| 20 | 추가: }; | |
| 21 | 추가: | |
| 22 | 추가: const server = new PaperServer(cfg); | |
| 23 | 추가: const clients = new ClientManager(cfg, () => server.status().address, log); | |
| 24 | 추가: const ctx: Ctx = { | |
| 25 | 추가: server, | |
| 26 | 추가: clients, | |
| 27 | 추가: marks: new Map(), | |
| 28 | 추가: runScenario: (file, opts) => runScenario(ctx, file, opts), | |
| 29 | 추가: }; | |
| 30 | 추가: | |
| 31 | 추가: function readBody(req: http.IncomingMessage): Promise<string> { | |
| 32 | 추가: return new Promise((resolve, reject) => { | |
| 33 | 추가: const chunks: Buffer[] = []; | |
| 34 | 추가: req.on('data', (c) => chunks.push(c)); | |
| 35 | 추가: req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); | |
| 36 | 추가: req.on('error', reject); | |
| 37 | 추가: }); | |
| 38 | 추가: } | |
| 39 | 추가: | |
| 40 | 추가: function send(res: http.ServerResponse, status: number, body: unknown) { | |
| 41 | 추가: const s = JSON.stringify(body); | |
| 42 | 추가: res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' }); | |
| 43 | 추가: res.end(s); | |
| 44 | 추가: } | |
| 45 | 추가: | |
| 46 | 추가: let shuttingDown = false; | |
| 47 | 추가: async function shutdown(code = 0) { | |
| 48 | 추가: if (shuttingDown) return; | |
| 49 | 추가: shuttingDown = true; | |
| 50 | 추가: log('shutting down: stopping clients and server'); | |
| 51 | 추가: httpServer.close(); // stop accepting new requests right away | |
| 52 | 추가: await clients.stopAll().catch((e) => log(`stopAll: ${e}`)); | |
| 53 | 추가: await server.stop().catch((e) => log(`server stop: ${e}`)); | |
| 54 | 추가: fs.rmSync(path.join(DIRS.run, 'daemon.json'), { force: true }); | |
| 55 | 추가: process.exit(code); | |
| 56 | 추가: } | |
| 57 | 추가: | |
| 58 | 추가: const httpServer = http.createServer(async (req, res) => { | |
| 59 | 추가: try { | |
| 60 | 추가: const url = new URL(req.url ?? '/', 'http://localhost'); | |
| 61 | 추가: if (shuttingDown) return send(res, 503, { ok: false, error: 'daemon is shutting down' }); | |
| 62 | 추가: if (url.pathname === '/health') return send(res, 200, { ok: true, pid: process.pid }); | |
| 63 | 추가: if (url.pathname === '/tools') return send(res, 200, { ok: true, tools: TOOLS.map((t) => ({ name: t.name, description: t.description })) }); | |
| 64 | 추가: if (url.pathname === '/shutdown' && req.method === 'POST') { | |
| 65 | 추가: send(res, 200, { ok: true }); | |
| 66 | 추가: setTimeout(() => void shutdown(0), 50); | |
| 67 | 추가: return; | |
| 68 | 추가: } | |
| 69 | 추가: if (url.pathname !== '/rpc' || req.method !== 'POST') return send(res, 404, { ok: false, error: 'POST /rpc {tool, params}' }); | |
| 70 | 추가: const { tool, params } = JSON.parse((await readBody(req)) || '{}'); | |
| 71 | 추가: const t = TOOL_MAP.get(tool); | |
| 72 | 추가: if (!t) return send(res, 400, { ok: false, error: `unknown tool '${tool}'` }); | |
| 73 | 추가: const parsed = z.object(t.shape).strict().safeParse(params ?? {}); | |
| 74 | 추가: if (!parsed.success) return send(res, 400, { ok: false, error: `invalid params for ${tool}: ${parsed.error.message}` }); | |
| 75 | 추가: const t0 = Date.now(); | |
| 76 | 추가: try { | |
| 77 | 추가: const result = await t.run(ctx, parsed.data); | |
| 78 | 추가: log(`${tool} ok ${Date.now() - t0}ms`); | |
| 79 | 추가: send(res, 200, { ok: true, result }); | |
| 80 | 추가: } catch (e) { | |
| 81 | 추가: log(`${tool} FAILED ${Date.now() - t0}ms: ${(e as Error).message.split('\n')[0]}`); | |
| 82 | 추가: send(res, 200, { ok: false, error: (e as Error).message }); | |
| 83 | 추가: } | |
| 84 | 추가: } catch (e) { | |
| 85 | 추가: send(res, 500, { ok: false, error: (e as Error).stack ?? String(e) }); | |
| 86 | 추가: } | |
| 87 | 추가: }); | |
| 88 | 추가: httpServer.requestTimeout = 0; | |
| 89 | 추가: httpServer.headersTimeout = 0; | |
| 90 | 추가: | |
| 91 | 추가: httpServer.listen(cfg.daemonPort, '127.0.0.1', () => { | |
| 92 | 추가: fs.writeFileSync(path.join(DIRS.run, 'daemon.json'), JSON.stringify({ pid: process.pid, port: cfg.daemonPort })); | |
| 93 | 추가: log(`mc-tester daemon listening on 127.0.0.1:${cfg.daemonPort} (client display: ${cfg.client.display})`); | |
| 94 | 추가: }); | |
| 95 | 추가: httpServer.on('error', (e) => { | |
| 96 | 추가: log(`daemon failed to listen: ${e.message}`); | |
| 97 | 추가: process.exit(1); | |
| 98 | 추가: }); | |
| 99 | 추가: | |
| 100 | 추가: process.on('SIGINT', () => void shutdown(0)); | |
| 101 | 추가: process.on('SIGTERM', () => void shutdown(0)); |
| @@ -0,0 +1,64 @@ | ||
| 1 | 추가: // Small download helper: hash-verified, cached, with bounded concurrency. | |
| 2 | 추가: import fs from 'node:fs'; | |
| 3 | 추가: import path from 'node:path'; | |
| 4 | 추가: import crypto from 'node:crypto'; | |
| 5 | 추가: | |
| 6 | 추가: export async function fetchJson<T = any>(url: string): Promise<T> { | |
| 7 | 추가: const res = await fetch(url, { headers: { 'User-Agent': 'mc-tester/0.1' } }); | |
| 8 | 추가: if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`); | |
| 9 | 추가: return (await res.json()) as T; | |
| 10 | 추가: } | |
| 11 | 추가: | |
| 12 | 추가: function hashFile(file: string, algo: 'sha1' | 'sha256'): string { | |
| 13 | 추가: return crypto.createHash(algo).update(fs.readFileSync(file)).digest('hex'); | |
| 14 | 추가: } | |
| 15 | 추가: | |
| 16 | 추가: export interface DownloadSpec { | |
| 17 | 추가: url: string; | |
| 18 | 추가: dest: string; | |
| 19 | 추가: sha1?: string; | |
| 20 | 추가: sha256?: string; | |
| 21 | 추가: } | |
| 22 | 추가: | |
| 23 | 추가: export async function download(spec: DownloadSpec): Promise<string> { | |
| 24 | 추가: const { url, dest } = spec; | |
| 25 | 추가: const algo = spec.sha256 ? 'sha256' : spec.sha1 ? 'sha1' : null; | |
| 26 | 추가: const want = spec.sha256 ?? spec.sha1; | |
| 27 | 추가: if (fs.existsSync(dest)) { | |
| 28 | 추가: if (!algo || hashFile(dest, algo) === want) return dest; | |
| 29 | 추가: } | |
| 30 | 추가: fs.mkdirSync(path.dirname(dest), { recursive: true }); | |
| 31 | 추가: let lastErr: unknown; | |
| 32 | 추가: for (let attempt = 1; attempt <= 3; attempt++) { | |
| 33 | 추가: try { | |
| 34 | 추가: const res = await fetch(url, { headers: { 'User-Agent': 'mc-tester/0.1' } }); | |
| 35 | 추가: if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`); | |
| 36 | 추가: const buf = Buffer.from(await res.arrayBuffer()); | |
| 37 | 추가: if (algo) { | |
| 38 | 추가: const got = crypto.createHash(algo).update(buf).digest('hex'); | |
| 39 | 추가: if (got !== want) throw new Error(`hash mismatch for ${url}: ${got} != ${want}`); | |
| 40 | 추가: } | |
| 41 | 추가: const tmp = dest + '.part'; | |
| 42 | 추가: fs.writeFileSync(tmp, buf); | |
| 43 | 추가: fs.renameSync(tmp, dest); | |
| 44 | 추가: return dest; | |
| 45 | 추가: } catch (e) { | |
| 46 | 추가: lastErr = e; | |
| 47 | 추가: } | |
| 48 | 추가: } | |
| 49 | 추가: throw lastErr; | |
| 50 | 추가: } | |
| 51 | 추가: | |
| 52 | 추가: export async function downloadAll(specs: DownloadSpec[], concurrency = 16, onProgress?: (done: number, total: number) => void): Promise<void> { | |
| 53 | 추가: let i = 0; | |
| 54 | 추가: let done = 0; | |
| 55 | 추가: const worker = async () => { | |
| 56 | 추가: while (i < specs.length) { | |
| 57 | 추가: const s = specs[i++]; | |
| 58 | 추가: await download(s); | |
| 59 | 추가: done++; | |
| 60 | 추가: if (onProgress && (done % 200 === 0 || done === specs.length)) onProgress(done, specs.length); | |
| 61 | 추가: } | |
| 62 | 추가: }; | |
| 63 | 추가: await Promise.all(Array.from({ length: Math.min(concurrency, specs.length) }, worker)); | |
| 64 | 추가: } |
| @@ -0,0 +1,289 @@ | ||
| 1 | 추가: // Minimal Minecraft + Fabric launcher: resolves 26.x version metadata, downloads (cached, hash-verified) | |
| 2 | 추가: // client jar / libraries / assets / Fabric loader, and builds the java command line for one client. | |
| 3 | 추가: import fs from 'node:fs'; | |
| 4 | 추가: import path from 'node:path'; | |
| 5 | 추가: import os from 'node:os'; | |
| 6 | 추가: import { DIRS, ROOT, expandGlob, type Config } from './config.ts'; | |
| 7 | 추가: import { download, downloadAll, fetchJson, type DownloadSpec } from './download.ts'; | |
| 8 | 추가: import type { Identity } from './auth.ts'; | |
| 9 | 추가: | |
| 10 | 추가: const MANIFEST = 'https://piston-meta.mojang.com/mc/game/version_manifest_v2.json'; | |
| 11 | 추가: const OS_NAME = process.platform === 'darwin' ? 'osx' : process.platform === 'win32' ? 'windows' : 'linux'; | |
| 12 | 추가: const ARCH = os.arch() === 'x64' ? 'x86_64' : os.arch(); | |
| 13 | 추가: | |
| 14 | 추가: interface Rule { | |
| 15 | 추가: action: 'allow' | 'disallow'; | |
| 16 | 추가: os?: { name?: string; arch?: string }; | |
| 17 | 추가: features?: Record<string, boolean>; | |
| 18 | 추가: } | |
| 19 | 추가: | |
| 20 | 추가: function rulesAllow(rules: Rule[] | undefined, features: Record<string, boolean> = {}): boolean { | |
| 21 | 추가: if (!rules || rules.length === 0) return true; | |
| 22 | 추가: let allowed = false; | |
| 23 | 추가: for (const r of rules) { | |
| 24 | 추가: let match = true; | |
| 25 | 추가: if (r.os?.name && r.os.name !== OS_NAME) match = false; | |
| 26 | 추가: if (r.os?.arch && r.os.arch !== (ARCH === 'x86_64' ? 'x86_64' : ARCH)) match = false; | |
| 27 | 추가: if (r.features) for (const [k, v] of Object.entries(r.features)) if ((features[k] ?? false) !== v) match = false; | |
| 28 | 추가: if (match) allowed = r.action === 'allow'; | |
| 29 | 추가: } | |
| 30 | 추가: return allowed; | |
| 31 | 추가: } | |
| 32 | 추가: | |
| 33 | 추가: function mavenPath(coord: string): string { | |
| 34 | 추가: const [group, artifact, version, classifier] = coord.split(':'); | |
| 35 | 추가: const file = `${artifact}-${version}${classifier ? '-' + classifier : ''}.jar`; | |
| 36 | 추가: return [...group.split('.'), artifact, version, file].join('/'); | |
| 37 | 추가: } | |
| 38 | 추가: | |
| 39 | 추가: function libKey(coord: string): string { | |
| 40 | 추가: const [g, a, , c] = coord.split(':'); | |
| 41 | 추가: return `${g}:${a}${c ? ':' + c : ''}`; | |
| 42 | 추가: } | |
| 43 | 추가: | |
| 44 | 추가: export interface Installation { | |
| 45 | 추가: version: any; | |
| 46 | 추가: fabric: any; | |
| 47 | 추가: classpath: string[]; | |
| 48 | 추가: clientJar: string; | |
| 49 | 추가: assetsDir: string; | |
| 50 | 추가: assetIndex: string; | |
| 51 | 추가: logConfig: string | null; | |
| 52 | 추가: mods: string[]; | |
| 53 | 추가: } | |
| 54 | 추가: | |
| 55 | 추가: let cached: Promise<Installation> | null = null; | |
| 56 | 추가: | |
| 57 | 추가: /** Download/verify everything needed to run the client. Safe to call repeatedly (cached per process). */ | |
| 58 | 추가: export function install(cfg: Config, log: (m: string) => void = () => {}): Promise<Installation> { | |
| 59 | 추가: if (!cached) cached = doInstall(cfg, log).catch((e) => { | |
| 60 | 추가: cached = null; | |
| 61 | 추가: throw e; | |
| 62 | 추가: }); | |
| 63 | 추가: return cached; | |
| 64 | 추가: } | |
| 65 | 추가: | |
| 66 | 추가: async function doInstall(cfg: Config, log: (m: string) => void): Promise<Installation> { | |
| 67 | 추가: const v = cfg.mcVersion; | |
| 68 | 추가: const vdir = path.join(DIRS.cache, 'versions', v); | |
| 69 | 추가: const vjsonPath = path.join(vdir, `${v}.json`); | |
| 70 | 추가: let version: any; | |
| 71 | 추가: if (fs.existsSync(vjsonPath)) { | |
| 72 | 추가: version = JSON.parse(fs.readFileSync(vjsonPath, 'utf8')); | |
| 73 | 추가: } else { | |
| 74 | 추가: const manifest = await fetchJson(MANIFEST); | |
| 75 | 추가: const entry = manifest.versions.find((x: any) => x.id === v); | |
| 76 | 추가: if (!entry) throw new Error(`Minecraft version ${v} not in Mojang manifest`); | |
| 77 | 추가: await download({ url: entry.url, dest: vjsonPath, sha1: entry.sha1 }); | |
| 78 | 추가: version = JSON.parse(fs.readFileSync(vjsonPath, 'utf8')); | |
| 79 | 추가: } | |
| 80 | 추가: | |
| 81 | 추가: const clientJar = path.join(vdir, `${v}.jar`); | |
| 82 | 추가: await download({ url: version.downloads.client.url, dest: clientJar, sha1: version.downloads.client.sha1 }); | |
| 83 | 추가: | |
| 84 | 추가: // Fabric loader profile (26.x is unobfuscated: no intermediary needed). | |
| 85 | 추가: const fabricPath = path.join(DIRS.cache, 'fabric', `${v}-${cfg.fabricLoader}.json`); | |
| 86 | 추가: if (!fs.existsSync(fabricPath)) { | |
| 87 | 추가: const prof = await fetchJson(`https://meta.fabricmc.net/v2/versions/loader/${v}/${cfg.fabricLoader}/profile/json`); | |
| 88 | 추가: fs.mkdirSync(path.dirname(fabricPath), { recursive: true }); | |
| 89 | 추가: fs.writeFileSync(fabricPath, JSON.stringify(prof, null, 2)); | |
| 90 | 추가: } | |
| 91 | 추가: const fabric = JSON.parse(fs.readFileSync(fabricPath, 'utf8')); | |
| 92 | 추가: | |
| 93 | 추가: const libDir = path.join(DIRS.cache, 'libraries'); | |
| 94 | 추가: const specs: DownloadSpec[] = []; | |
| 95 | 추가: const cp = new Map<string, string>(); | |
| 96 | 추가: for (const lib of version.libraries) { | |
| 97 | 추가: if (!rulesAllow(lib.rules)) continue; | |
| 98 | 추가: const a = lib.downloads?.artifact; | |
| 99 | 추가: if (!a) continue; | |
| 100 | 추가: const dest = path.join(libDir, a.path); | |
| 101 | 추가: specs.push({ url: a.url, dest, sha1: a.sha1 }); | |
| 102 | 추가: cp.set(libKey(lib.name), dest); | |
| 103 | 추가: } | |
| 104 | 추가: for (const lib of fabric.libraries) { | |
| 105 | 추가: const rel = mavenPath(lib.name); | |
| 106 | 추가: const dest = path.join(libDir, rel); | |
| 107 | 추가: const base = (lib.url as string).endsWith('/') ? lib.url : lib.url + '/'; | |
| 108 | 추가: specs.push({ url: base + rel, dest, sha1: lib.sha1 }); | |
| 109 | 추가: cp.set(libKey(lib.name), dest); // Fabric's versions win over vanilla duplicates (e.g. ASM) | |
| 110 | 추가: } | |
| 111 | 추가: log(`libraries: ${specs.length}`); | |
| 112 | 추가: await downloadAll(specs, 16); | |
| 113 | 추가: | |
| 114 | 추가: // Assets | |
| 115 | 추가: const assetsDir = path.join(DIRS.cache, 'assets'); | |
| 116 | 추가: const ai = version.assetIndex; | |
| 117 | 추가: const indexPath = path.join(assetsDir, 'indexes', `${ai.id}.json`); | |
| 118 | 추가: await download({ url: ai.url, dest: indexPath, sha1: ai.sha1 }); | |
| 119 | 추가: const index = JSON.parse(fs.readFileSync(indexPath, 'utf8')); | |
| 120 | 추가: const assetSpecs: DownloadSpec[] = Object.values<any>(index.objects).map((o) => ({ | |
| 121 | 추가: url: `https://resources.download.minecraft.net/${o.hash.slice(0, 2)}/${o.hash}`, | |
| 122 | 추가: dest: path.join(assetsDir, 'objects', o.hash.slice(0, 2), o.hash), | |
| 123 | 추가: sha1: o.hash, | |
| 124 | 추가: })); | |
| 125 | 추가: const missing = assetSpecs.filter((s) => !fs.existsSync(s.dest)); | |
| 126 | 추가: if (missing.length) { | |
| 127 | 추가: log(`assets: downloading ${missing.length} objects`); | |
| 128 | 추가: await downloadAll(missing, 32, (d, t) => log(`assets ${d}/${t}`)); | |
| 129 | 추가: } | |
| 130 | 추가: | |
| 131 | 추가: let logConfig: string | null = null; | |
| 132 | 추가: const lc = version.logging?.client?.file; | |
| 133 | 추가: if (lc) { | |
| 134 | 추가: logConfig = path.join(assetsDir, 'log_configs', lc.id); | |
| 135 | 추가: await download({ url: lc.url, dest: logConfig, sha1: lc.sha1 }); | |
| 136 | 추가: } | |
| 137 | 추가: | |
| 138 | 추가: // Mods: QA Bridge + Fabric API + user extras | |
| 139 | 추가: const mods: string[] = []; | |
| 140 | 추가: const bridge = expandGlob('qa-bridge/build/libs/qa-bridge-*.jar'); | |
| 141 | 추가: if (bridge.length === 0) throw new Error('qa-bridge jar not built: run `npm run build:mods` (or ./gradlew build in qa-bridge/)'); | |
| 142 | 추가: mods.push(bridge.sort().at(-1)!); | |
| 143 | 추가: const fa = cfg.fabricApi; | |
| 144 | 추가: const faUrl = `https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api/${encodeURIComponent(fa)}/fabric-api-${encodeURIComponent(fa)}.jar`; | |
| 145 | 추가: const faSha1 = (await (await fetch(faUrl + '.sha1')).text()).trim().slice(0, 40); | |
| 146 | 추가: const faDest = path.join(DIRS.cache, 'mods', `fabric-api-${fa}.jar`); | |
| 147 | 추가: await download({ url: faUrl, dest: faDest, sha1: faSha1 }); | |
| 148 | 추가: mods.push(faDest); | |
| 149 | 추가: for (const g of cfg.client.extraMods) mods.push(...expandGlob(g)); | |
| 150 | 추가: | |
| 151 | 추가: return { | |
| 152 | 추가: version, | |
| 153 | 추가: fabric, | |
| 154 | 추가: classpath: [...cp.values(), clientJar], | |
| 155 | 추가: clientJar, | |
| 156 | 추가: assetsDir, | |
| 157 | 추가: assetIndex: ai.id, | |
| 158 | 추가: logConfig, | |
| 159 | 추가: mods, | |
| 160 | 추가: }; | |
| 161 | 추가: } | |
| 162 | 추가: | |
| 163 | 추가: export interface LaunchPlan { | |
| 164 | 추가: command: string; | |
| 165 | 추가: args: string[]; | |
| 166 | 추가: cwd: string; | |
| 167 | 추가: gameDir: string; | |
| 168 | 추가: } | |
| 169 | 추가: | |
| 170 | 추가: function writeOptions(gameDir: string, cfg: Config): void { | |
| 171 | 추가: const file = path.join(gameDir, 'options.txt'); | |
| 172 | 추가: const existing = new Map<string, string>(); | |
| 173 | 추가: if (fs.existsSync(file)) { | |
| 174 | 추가: for (const line of fs.readFileSync(file, 'utf8').split('\n')) { | |
| 175 | 추가: const i = line.indexOf(':'); | |
| 176 | 추가: if (i > 0) existing.set(line.slice(0, i), line.slice(i + 1)); | |
| 177 | 추가: } | |
| 178 | 추가: } | |
| 179 | 추가: const forced: Record<string, string> = { | |
| 180 | 추가: onboardAccessibility: 'false', | |
| 181 | 추가: skipMultiplayerWarning: 'true', | |
| 182 | 추가: joinedFirstServer: 'true', | |
| 183 | 추가: tutorialStep: 'none', | |
| 184 | 추가: pauseOnLostFocus: 'false', | |
| 185 | 추가: guiScale: String(cfg.client.guiScale), | |
| 186 | 추가: renderDistance: '6', | |
| 187 | 추가: simulationDistance: '5', | |
| 188 | 추가: maxFps: '30', | |
| 189 | 추가: inactivityFpsLimit: '"afk"', | |
| 190 | 추가: enableVsync: 'false', | |
| 191 | 추가: narrator: '0', | |
| 192 | 추가: narratorHotkey: 'false', | |
| 193 | 추가: realmsNotifications: 'false', | |
| 194 | 추가: telemetryOptInExtra: 'false', | |
| 195 | 추가: fullscreen: 'false', | |
| 196 | 추가: soundCategory_master: '0.0', | |
| 197 | 추가: musicToast: '"never"', | |
| 198 | 추가: lang: cfg.client.lang, | |
| 199 | 추가: chatLinksPrompt: 'false', | |
| 200 | 추가: autoJump: 'false', | |
| 201 | 추가: startedCleanly: 'true', | |
| 202 | 추가: hideSplashTexts: 'true', | |
| 203 | 추가: darkMojangStudiosBackground: 'true', | |
| 204 | 추가: }; | |
| 205 | 추가: for (const [k, val] of Object.entries(forced)) existing.set(k, val); | |
| 206 | 추가: fs.writeFileSync(file, [...existing].map(([k, val]) => `${k}:${val}`).join('\n') + '\n'); | |
| 207 | 추가: } | |
| 208 | 추가: | |
| 209 | 추가: function syncMods(gameDir: string, mods: string[]): void { | |
| 210 | 추가: const dir = path.join(gameDir, 'mods'); | |
| 211 | 추가: fs.mkdirSync(dir, { recursive: true }); | |
| 212 | 추가: for (const f of fs.readdirSync(dir)) if (f.endsWith('.jar')) fs.rmSync(path.join(dir, f)); | |
| 213 | 추가: for (const m of mods) fs.copyFileSync(m, path.join(dir, path.basename(m))); | |
| 214 | 추가: } | |
| 215 | 추가: | |
| 216 | 추가: export async function plan( | |
| 217 | 추가: cfg: Config, | |
| 218 | 추가: inst: Installation, | |
| 219 | 추가: who: Identity, | |
| 220 | 추가: opts: { gameDir: string; bridgePort: number; connect?: string | null }, | |
| 221 | 추가: ): Promise<LaunchPlan> { | |
| 222 | 추가: const { gameDir } = opts; | |
| 223 | 추가: fs.mkdirSync(gameDir, { recursive: true }); | |
| 224 | 추가: writeOptions(gameDir, cfg); | |
| 225 | 추가: syncMods(gameDir, inst.mods); | |
| 226 | 추가: const natives = path.join(gameDir, 'natives'); | |
| 227 | 추가: for (const sub of ['java', 'jna', 'lwjgl', 'netty']) fs.mkdirSync(path.join(natives, sub), { recursive: true }); | |
| 228 | 추가: | |
| 229 | 추가: const features: Record<string, boolean> = { | |
| 230 | 추가: has_custom_resolution: true, | |
| 231 | 추가: is_quick_play_multiplayer: !!opts.connect, | |
| 232 | 추가: }; | |
| 233 | 추가: const vars: Record<string, string> = { | |
| 234 | 추가: natives_directory: natives, | |
| 235 | 추가: launcher_name: 'mc-tester', | |
| 236 | 추가: launcher_version: '0.1.0', | |
| 237 | 추가: classpath: inst.classpath.join(path.delimiter), | |
| 238 | 추가: classpath_separator: path.delimiter, | |
| 239 | 추가: library_directory: path.join(DIRS.cache, 'libraries'), | |
| 240 | 추가: auth_player_name: who.name, | |
| 241 | 추가: version_name: cfg.mcVersion, | |
| 242 | 추가: game_directory: gameDir, | |
| 243 | 추가: assets_root: inst.assetsDir, | |
| 244 | 추가: assets_index_name: inst.assetIndex, | |
| 245 | 추가: auth_uuid: who.uuid, | |
| 246 | 추가: auth_access_token: who.accessToken, | |
| 247 | 추가: clientid: '0', | |
| 248 | 추가: auth_xuid: who.xuid, | |
| 249 | 추가: user_type: who.userType, | |
| 250 | 추가: version_type: 'release', | |
| 251 | 추가: resolution_width: String(cfg.client.width), | |
| 252 | 추가: resolution_height: String(cfg.client.height), | |
| 253 | 추가: quickPlayMultiplayer: opts.connect ?? '', | |
| 254 | 추가: }; | |
| 255 | 추가: const sub = (s: string) => s.replace(/\$\{([^}]+)\}/g, (_, k) => vars[k] ?? ''); | |
| 256 | 추가: const expand = (list: any[]): string[] => { | |
| 257 | 추가: const out: string[] = []; | |
| 258 | 추가: for (const a of list) { | |
| 259 | 추가: if (typeof a === 'string') out.push(sub(a)); | |
| 260 | 추가: else if (rulesAllow(a.rules, features)) out.push(...(Array.isArray(a.value) ? a.value : [a.value]).map(sub)); | |
| 261 | 추가: } | |
| 262 | 추가: return out; | |
| 263 | 추가: }; | |
| 264 | 추가: | |
| 265 | 추가: const jvm = [ | |
| 266 | 추가: `-Xms1G`, | |
| 267 | 추가: `-Xmx${cfg.client.memory}`, | |
| 268 | 추가: '-XX:+UseZGC', | |
| 269 | 추가: ...expand(inst.version.arguments.jvm), | |
| 270 | 추가: ...(inst.fabric.arguments?.jvm ?? []), | |
| 271 | 추가: `-Dqabridge.port=${opts.bridgePort}`, | |
| 272 | 추가: `-Dqabridge.hideToasts=${cfg.client.hideToasts}`, | |
| 273 | 추가: `-Dqabridge.acceptServerPacks=${cfg.client.acceptServerResourcePacks}`, | |
| 274 | 추가: ]; | |
| 275 | 추가: if (inst.logConfig) jvm.push(sub(inst.version.logging.client.argument.replace('${path}', inst.logConfig))); | |
| 276 | 추가: // quickPlayPath is feature-gated; we never enable it. | |
| 277 | 추가: const game = expand(inst.version.arguments.game).filter((a) => a !== '--quickPlayPath'); | |
| 278 | 추가: const args = [...jvm, inst.fabric.mainClass, ...game]; | |
| 279 | 추가: return { command: 'java', args, cwd: gameDir, gameDir }; | |
| 280 | 추가: } | |
| 281 | 추가: | |
| 282 | 추가: export function redactArgs(args: string[]): string[] { | |
| 283 | 추가: const out = [...args]; | |
| 284 | 추가: const i = out.indexOf('--accessToken'); | |
| 285 | 추가: if (i >= 0 && i + 1 < out.length) out[i + 1] = '<redacted>'; | |
| 286 | 추가: return out; | |
| 287 | 추가: } | |
| 288 | 추가: | |
| 289 | 추가: export { ROOT }; |
| @@ -0,0 +1,42 @@ | ||
| 1 | 추가: // MCP stdio server for QA agents. Thin proxy: every tool call goes to the shared daemon | |
| 2 | 추가: // (auto-started), screenshots come back as image content. | |
| 3 | 추가: import fs from 'node:fs'; | |
| 4 | 추가: import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; | |
| 5 | 추가: import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; | |
| 6 | 추가: import { TOOLS } from './tools.ts'; | |
| 7 | 추가: import { call } from './rpc.ts'; | |
| 8 | 추가: | |
| 9 | 추가: const INSTRUCTIONS = `mc-tester drives REAL Minecraft 26.3 clients against a local Paper test server running the plugin under test. | |
| 10 | 추가: Plugins under test: plugins_list shows which jars load; plugins_set (add/remove, restart:true) changes them and saves mct.config.json. | |
| 11 | 추가: Typical loop: server_start -> client_launch {name:"Bot1"} -> rcon (give items / set state) -> teleport next to an NPC -> interact_entity -> screen (read the GUI as JSON) -> click_item / click_slot -> wait_for {chat: ...} -> verify with rcon (server truth) and state/screen (client view) -> screenshot when visual proof helps. | |
| 12 | 추가: - Prefer server-side verification (rcon + the plugin's admin/debug commands) for balances and inventories; the client view can lag. | |
| 13 | 추가: - Every action tool accepts screenshot:true to get an image of the result. | |
| 14 | 추가: - world_snapshot once ("base"), then world_reset "base" before tests that must be deterministic. | |
| 15 | 추가: - Turn reproducible checks into YAML scenarios under scenarios/ and run them with run_scenario.`; | |
| 16 | 추가: | |
| 17 | 추가: const server = new McpServer({ name: 'mc-tester', version: '0.1.0' }, { instructions: INSTRUCTIONS }); | |
| 18 | 추가: | |
| 19 | 추가: function imageFor(p: unknown) { | |
| 20 | 추가: if (typeof p !== 'string' || !p.endsWith('.png') || !fs.existsSync(p)) return null; | |
| 21 | 추가: return { type: 'image' as const, data: fs.readFileSync(p).toString('base64'), mimeType: 'image/png' }; | |
| 22 | 추가: } | |
| 23 | 추가: | |
| 24 | 추가: for (const t of TOOLS) { | |
| 25 | 추가: server.registerTool(t.name, { description: t.description, inputSchema: t.shape }, async (args: any) => { | |
| 26 | 추가: try { | |
| 27 | 추가: const result = await call(t.name, args ?? {}); | |
| 28 | 추가: const content: any[] = [{ type: 'text', text: JSON.stringify(result, null, 2) }]; | |
| 29 | 추가: const imgs = [result?.screenshot, t.name === 'screenshot' ? result?.path : null]; | |
| 30 | 추가: if (Array.isArray(result?.screenshots)) imgs.push(...result.screenshots.slice(-4)); | |
| 31 | 추가: for (const p of imgs) { | |
| 32 | 추가: const img = imageFor(p); | |
| 33 | 추가: if (img) content.push(img); | |
| 34 | 추가: } | |
| 35 | 추가: return { content }; | |
| 36 | 추가: } catch (e) { | |
| 37 | 추가: return { isError: true, content: [{ type: 'text', text: (e as Error).message }] }; | |
| 38 | 추가: } | |
| 39 | 추가: }); | |
| 40 | 추가: } | |
| 41 | 추가: | |
| 42 | 추가: await server.connect(new StdioServerTransport()); |
| @@ -0,0 +1,317 @@ | ||
| 1 | 추가: // Paper test server: download, configure, start/stop, logs, RCON, world snapshots. | |
| 2 | 추가: import fs from 'node:fs'; | |
| 3 | 추가: import path from 'node:path'; | |
| 4 | 추가: import { spawn, type ChildProcess } from 'node:child_process'; | |
| 5 | 추가: import { DIRS, secrets, type Config } from './config.ts'; | |
| 6 | 추가: import { resolvePlugins } from './plugins.ts'; | |
| 7 | 추가: import { download, fetchJson } from './download.ts'; | |
| 8 | 추가: import { Rcon } from './rcon.ts'; | |
| 9 | 추가: | |
| 10 | 추가: export interface LogLine { | |
| 11 | 추가: seq: number; | |
| 12 | 추가: time: number; | |
| 13 | 추가: text: string; | |
| 14 | 추가: } | |
| 15 | 추가: | |
| 16 | 추가: const ERROR_RE = /(\bERROR\]|Exception|Caused by:|\bat [\w.$]+\([\w.]+:\d+\))/; | |
| 17 | 추가: | |
| 18 | 추가: export class PaperServer { | |
| 19 | 추가: private cfg: Config; | |
| 20 | 추가: private proc: ChildProcess | null = null; | |
| 21 | 추가: private rcon: Rcon | null = null; | |
| 22 | 추가: private lines: LogLine[] = []; | |
| 23 | 추가: private seq = 0; | |
| 24 | 추가: private ready = false; | |
| 25 | 추가: private exitInfo: string | null = null; | |
| 26 | 추가: | |
| 27 | 추가: constructor(cfg: Config) { | |
| 28 | 추가: this.cfg = cfg; | |
| 29 | 추가: } | |
| 30 | 추가: | |
| 31 | 추가: get dir(): string { | |
| 32 | 추가: return DIRS.server; | |
| 33 | 추가: } | |
| 34 | 추가: | |
| 35 | 추가: /** Live config shared with the daemon (plugins_set edits server.plugins in place). */ | |
| 36 | 추가: get config(): Config { | |
| 37 | 추가: return this.cfg; | |
| 38 | 추가: } | |
| 39 | 추가: | |
| 40 | 추가: get running(): boolean { | |
| 41 | 추가: return this.proc !== null && this.proc.exitCode === null; | |
| 42 | 추가: } | |
| 43 | 추가: | |
| 44 | 추가: status() { | |
| 45 | 추가: return { | |
| 46 | 추가: running: this.running, | |
| 47 | 추가: ready: this.ready, | |
| 48 | 추가: pid: this.proc?.pid ?? null, | |
| 49 | 추가: address: `127.0.0.1:${this.cfg.server.port}`, | |
| 50 | 추가: onlineMode: this.cfg.server.onlineMode, | |
| 51 | 추가: logSeq: this.seq, | |
| 52 | 추가: lastExit: this.exitInfo, | |
| 53 | 추가: plugins: this.installedPlugins(), | |
| 54 | 추가: }; | |
| 55 | 추가: } | |
| 56 | 추가: | |
| 57 | 추가: private installedPlugins(): string[] { | |
| 58 | 추가: const p = path.join(this.dir, 'plugins'); | |
| 59 | 추가: if (!fs.existsSync(p)) return []; | |
| 60 | 추가: return fs.readdirSync(p).filter((f) => f.endsWith('.jar')); | |
| 61 | 추가: } | |
| 62 | 추가: | |
| 63 | 추가: async ensureJar(): Promise<string> { | |
| 64 | 추가: const v = this.cfg.mcVersion; | |
| 65 | 추가: const builds = await fetchJson<any[]>(`https://fill.papermc.io/v3/projects/paper/versions/${v}/builds`); | |
| 66 | 추가: const want = this.cfg.server.paperBuild; | |
| 67 | 추가: const build = want === 'latest' ? builds.find((b) => b.channel === 'STABLE') ?? builds[0] : builds.find((b) => b.id === want); | |
| 68 | 추가: if (!build) throw new Error(`Paper build ${want} for ${v} not found`); | |
| 69 | 추가: const dl = build.downloads['server:default']; | |
| 70 | 추가: const dest = path.join(DIRS.cache, 'paper', dl.name); | |
| 71 | 추가: await download({ url: dl.url, dest, sha256: dl.checksums?.sha256 }); | |
| 72 | 추가: return dest; | |
| 73 | 추가: } | |
| 74 | 추가: | |
| 75 | 추가: private writeConfig(): void { | |
| 76 | 추가: const s = this.cfg.server; | |
| 77 | 추가: fs.mkdirSync(this.dir, { recursive: true }); | |
| 78 | 추가: // The user accepted the Minecraft EULA (https://aka.ms/MinecraftEULA) when setting up this harness. | |
| 79 | 추가: fs.writeFileSync(path.join(this.dir, 'eula.txt'), 'eula=true\n'); | |
| 80 | 추가: const propsFile = path.join(this.dir, 'server.properties'); | |
| 81 | 추가: const props: Record<string, string> = {}; | |
| 82 | 추가: if (fs.existsSync(propsFile)) { | |
| 83 | 추가: for (const line of fs.readFileSync(propsFile, 'utf8').split('\n')) { | |
| 84 | 추가: const m = line.match(/^([^#=]+)=(.*)$/); | |
| 85 | 추가: if (m) props[m[1].trim()] = m[2]; | |
| 86 | 추가: } | |
| 87 | 추가: } | |
| 88 | 추가: const forced: Record<string, string | number | boolean> = { | |
| 89 | 추가: 'server-ip': '127.0.0.1', | |
| 90 | 추가: 'server-port': s.port, | |
| 91 | 추가: 'online-mode': s.onlineMode, | |
| 92 | 추가: 'enforce-secure-profile': s.onlineMode, | |
| 93 | 추가: 'enable-rcon': true, | |
| 94 | 추가: 'rcon.port': s.rconPort, | |
| 95 | 추가: 'rcon.password': secrets().rconPassword, | |
| 96 | 추가: 'broadcast-rcon-to-ops': false, | |
| 97 | 추가: 'level-seed': 'mc-tester', | |
| 98 | 추가: 'level-type': 'minecraft\\:flat', | |
| 99 | 추가: 'generator-settings': JSON.stringify({ | |
| 100 | 추가: layers: [ | |
| 101 | 추가: { block: 'minecraft:bedrock', height: 1 }, | |
| 102 | 추가: { block: 'minecraft:dirt', height: 2 }, | |
| 103 | 추가: { block: 'minecraft:grass_block', height: 1 }, | |
| 104 | 추가: ], | |
| 105 | 추가: biome: 'minecraft:plains', | |
| 106 | 추가: }).replace(/:/g, '\\:'), | |
| 107 | 추가: 'spawn-protection': 0, | |
| 108 | 추가: 'view-distance': 6, | |
| 109 | 추가: 'simulation-distance': 6, | |
| 110 | 추가: 'allow-flight': true, | |
| 111 | 추가: 'difficulty': 'peaceful', | |
| 112 | 추가: 'gamemode': 'survival', | |
| 113 | 추가: 'motd': 'mc-tester QA server', | |
| 114 | 추가: 'max-players': 50, | |
| 115 | 추가: 'white-list': false, | |
| 116 | 추가: 'enforce-whitelist': false, | |
| 117 | 추가: 'sync-chunk-writes': false, | |
| 118 | 추가: ...s.properties, | |
| 119 | 추가: }; | |
| 120 | 추가: // Drop keys that came from a previous `server.properties` override but are no longer configured, | |
| 121 | 추가: // so removing an override really reverts it (Paper re-adds the default on start). | |
| 122 | 추가: const overridesFile = path.join(this.dir, '.mct-properties.json'); | |
| 123 | 추가: const previousOverrides: string[] = fs.existsSync(overridesFile) ? JSON.parse(fs.readFileSync(overridesFile, 'utf8')) : []; | |
| 124 | 추가: for (const k of previousOverrides) if (!(k in s.properties)) delete props[k]; | |
| 125 | 추가: fs.writeFileSync(overridesFile, JSON.stringify(Object.keys(s.properties))); | |
| 126 | 추가: for (const [k, v] of Object.entries(forced)) props[k] = String(v); | |
| 127 | 추가: fs.writeFileSync(propsFile, Object.entries(props).map(([k, v]) => `${k}=${v}`).join('\n') + '\n'); | |
| 128 | 추가: } | |
| 129 | 추가: | |
| 130 | 추가: /** Copy the resolved plugin jars (one per plugin, newest build) into plugins/, removing what we copied last time. */ | |
| 131 | 추가: private syncPlugins(): { copied: string[]; skipped: { file: string; reason: string }[] } { | |
| 132 | 추가: const res = resolvePlugins(this.cfg.server.plugins); | |
| 133 | 추가: if (res.unmatched.length) { | |
| 134 | 추가: throw new Error(`plugin pattern(s) matched no jar: ${res.unmatched.join(', ')} (build the plugin first, or fix the path with plugins_set)`); | |
| 135 | 추가: } | |
| 136 | 추가: const pdir = path.join(this.dir, 'plugins'); | |
| 137 | 추가: fs.mkdirSync(pdir, { recursive: true }); | |
| 138 | 추가: const manifest = path.join(this.dir, '.mct-plugins.json'); | |
| 139 | 추가: const previous: string[] = fs.existsSync(manifest) ? JSON.parse(fs.readFileSync(manifest, 'utf8')) : []; | |
| 140 | 추가: for (const f of previous) fs.rmSync(path.join(pdir, f), { force: true }); | |
| 141 | 추가: const copied: string[] = []; | |
| 142 | 추가: for (const j of res.selected) { | |
| 143 | 추가: const name = path.basename(j.file); | |
| 144 | 추가: fs.copyFileSync(j.file, path.join(pdir, name)); | |
| 145 | 추가: copied.push(name); | |
| 146 | 추가: } | |
| 147 | 추가: fs.writeFileSync(manifest, JSON.stringify(copied)); | |
| 148 | 추가: return { copied, skipped: res.skipped.map((j) => ({ file: j.file, reason: j.reason })) }; | |
| 149 | 추가: } | |
| 150 | 추가: | |
| 151 | 추가: private push(text: string): void { | |
| 152 | 추가: this.lines.push({ seq: ++this.seq, time: Date.now(), text }); | |
| 153 | 추가: if (this.lines.length > 20000) this.lines.splice(0, this.lines.length - 20000); | |
| 154 | 추가: } | |
| 155 | 추가: | |
| 156 | 추가: async start(timeoutMs = 180_000): Promise<object> { | |
| 157 | 추가: if (this.running) return { alreadyRunning: true, ...this.status() }; | |
| 158 | 추가: const jar = await this.ensureJar(); | |
| 159 | 추가: this.writeConfig(); | |
| 160 | 추가: const plugins = this.syncPlugins(); | |
| 161 | 추가: this.ready = false; | |
| 162 | 추가: this.exitInfo = null; | |
| 163 | 추가: const mem = this.cfg.server.memory; | |
| 164 | 추가: const proc = spawn('java', [`-Xms${mem}`, `-Xmx${mem}`, '-Dterminal.jline=false', '-Dterminal.ansi=false', '-jar', jar, '--nogui'], { | |
| 165 | 추가: cwd: this.dir, | |
| 166 | 추가: stdio: ['pipe', 'pipe', 'pipe'], | |
| 167 | 추가: env: { ...process.env, TERM: 'dumb' }, | |
| 168 | 추가: }); | |
| 169 | 추가: this.proc = proc; | |
| 170 | 추가: const startSeq = this.seq; | |
| 171 | 추가: let partial = ''; | |
| 172 | 추가: const onChunk = (d: Buffer) => { | |
| 173 | 추가: partial += d.toString('utf8'); | |
| 174 | 추가: const parts = partial.split('\n'); | |
| 175 | 추가: partial = parts.pop() ?? ''; | |
| 176 | 추가: for (const raw of parts) { | |
| 177 | 추가: // Strip ANSI and the console prompt redraw ("> \r \r") that JLine interleaves. | |
| 178 | 추가: const line = (raw.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').split('\r').filter((x) => x.trim()).pop() ?? '').replace(/^> /, ''); | |
| 179 | 추가: this.push(line); | |
| 180 | 추가: if (/Done \([\d.,]+s\)! For help/.test(line)) this.ready = true; | |
| 181 | 추가: } | |
| 182 | 추가: }; | |
| 183 | 추가: proc.stdout!.on('data', onChunk); | |
| 184 | 추가: proc.stderr!.on('data', onChunk); | |
| 185 | 추가: proc.on('exit', (code, sig) => { | |
| 186 | 추가: this.exitInfo = `exited code=${code} signal=${sig}`; | |
| 187 | 추가: this.push(`[mc-tester] server ${this.exitInfo}`); | |
| 188 | 추가: this.ready = false; | |
| 189 | 추가: this.rcon?.close(); | |
| 190 | 추가: this.rcon = null; | |
| 191 | 추가: }); | |
| 192 | 추가: const t0 = Date.now(); | |
| 193 | 추가: while (!this.ready) { | |
| 194 | 추가: if (!this.running) throw new Error(`server exited during startup (${this.exitInfo}). Last log:\n${this.tail(40, startSeq)}`); | |
| 195 | 추가: if (Date.now() - t0 > timeoutMs) throw new Error(`server not ready after ${timeoutMs}ms. Last log:\n${this.tail(40, startSeq)}`); | |
| 196 | 추가: await sleep(250); | |
| 197 | 추가: } | |
| 198 | 추가: const onStart: Record<string, string> = {}; | |
| 199 | 추가: for (const c of this.cfg.server.onStart) onStart[c] = await this.command(c); | |
| 200 | 추가: return { ...this.status(), started: true, seconds: (Date.now() - t0) / 1000, copiedPlugins: plugins.copied, skippedJars: plugins.skipped, onStart }; | |
| 201 | 추가: } | |
| 202 | 추가: | |
| 203 | 추가: async stop(timeoutMs = 60_000): Promise<object> { | |
| 204 | 추가: if (!this.running) return { running: false }; | |
| 205 | 추가: const proc = this.proc!; | |
| 206 | 추가: try { | |
| 207 | 추가: await this.command('stop', 5000); | |
| 208 | 추가: } catch { | |
| 209 | 추가: proc.stdin?.write('stop\n'); | |
| 210 | 추가: } | |
| 211 | 추가: const t0 = Date.now(); | |
| 212 | 추가: while (proc.exitCode === null && Date.now() - t0 < timeoutMs) await sleep(200); | |
| 213 | 추가: if (proc.exitCode === null) proc.kill('SIGKILL'); | |
| 214 | 추가: return { stopped: true, seconds: (Date.now() - t0) / 1000 }; | |
| 215 | 추가: } | |
| 216 | 추가: | |
| 217 | 추가: async command(cmd: string, timeoutMs = 15_000): Promise<string> { | |
| 218 | 추가: if (!this.running) throw new Error('server is not running (call server_start)'); | |
| 219 | 추가: const c = cmd.replace(/^\//, ''); | |
| 220 | 추가: for (let attempt = 1; ; attempt++) { | |
| 221 | 추가: if (!this.rcon || !this.rcon.connected) { | |
| 222 | 추가: this.rcon = new Rcon('127.0.0.1', this.cfg.server.rconPort, secrets().rconPassword); | |
| 223 | 추가: } | |
| 224 | 추가: try { | |
| 225 | 추가: return await this.rcon.command(c, timeoutMs); | |
| 226 | 추가: } catch (e) { | |
| 227 | 추가: // The server drops idle RCON sockets; reconnect once and retry. | |
| 228 | 추가: const msg = (e as Error).message; | |
| 229 | 추가: if (attempt >= 2 || !/closed|ECONNRESET|EPIPE|ECONNREFUSED/.test(msg) || !this.running) throw e; | |
| 230 | 추가: this.rcon?.close(); | |
| 231 | 추가: this.rcon = null; | |
| 232 | 추가: } | |
| 233 | 추가: } | |
| 234 | 추가: } | |
| 235 | 추가: | |
| 236 | 추가: log(since = 0, grep?: string, limit = 200): { next: number; lines: LogLine[] } { | |
| 237 | 추가: let out = this.lines.filter((l) => l.seq > since); | |
| 238 | 추가: if (grep) { | |
| 239 | 추가: const re = new RegExp(grep, 'i'); | |
| 240 | 추가: out = out.filter((l) => re.test(l.text)); | |
| 241 | 추가: } | |
| 242 | 추가: return { next: this.seq, lines: out.slice(-limit) }; | |
| 243 | 추가: } | |
| 244 | 추가: | |
| 245 | 추가: errors(since: number): LogLine[] { | |
| 246 | 추가: return this.lines.filter((l) => l.seq > since && ERROR_RE.test(l.text)); | |
| 247 | 추가: } | |
| 248 | 추가: | |
| 249 | 추가: get logSeq(): number { | |
| 250 | 추가: return this.seq; | |
| 251 | 추가: } | |
| 252 | 추가: | |
| 253 | 추가: tail(n: number, since = 0): string { | |
| 254 | 추가: return this.lines.filter((l) => l.seq > since).slice(-n).map((l) => l.text).join('\n'); | |
| 255 | 추가: } | |
| 256 | 추가: | |
| 257 | 추가: // ---------------------------------------------------------------- snapshots | |
| 258 | 추가: | |
| 259 | 추가: private snapshotEntries(): string[] { | |
| 260 | 추가: const out: string[] = []; | |
| 261 | 추가: for (const inc of this.cfg.server.snapshotInclude) { | |
| 262 | 추가: if (inc.endsWith('/*')) { | |
| 263 | 추가: const base = inc.slice(0, -2); | |
| 264 | 추가: const abs = path.join(this.dir, base); | |
| 265 | 추가: if (!fs.existsSync(abs)) continue; | |
| 266 | 추가: for (const e of fs.readdirSync(abs, { withFileTypes: true })) if (e.isDirectory()) out.push(path.join(base, e.name)); | |
| 267 | 추가: } else if (fs.existsSync(path.join(this.dir, inc))) { | |
| 268 | 추가: out.push(inc); | |
| 269 | 추가: } | |
| 270 | 추가: } | |
| 271 | 추가: return out; | |
| 272 | 추가: } | |
| 273 | 추가: | |
| 274 | 추가: async snapshot(name: string): Promise<object> { | |
| 275 | 추가: if (!/^[\w.-]+$/.test(name)) throw new Error('snapshot name must be [A-Za-z0-9_.-]'); | |
| 276 | 추가: const wasRunning = this.running; | |
| 277 | 추가: if (wasRunning) { | |
| 278 | 추가: await this.command('save-off'); | |
| 279 | 추가: await this.command('save-all flush', 60_000); | |
| 280 | 추가: } | |
| 281 | 추가: try { | |
| 282 | 추가: const dest = path.join(DIRS.snapshots, name); | |
| 283 | 추가: fs.rmSync(dest, { recursive: true, force: true }); | |
| 284 | 추가: const entries = this.snapshotEntries(); | |
| 285 | 추가: for (const e of entries) { | |
| 286 | 추가: fs.cpSync(path.join(this.dir, e), path.join(dest, e), { recursive: true, filter: (src) => !src.endsWith('session.lock') }); | |
| 287 | 추가: } | |
| 288 | 추가: fs.writeFileSync(path.join(dest, '.mct-snapshot.json'), JSON.stringify({ entries, created: new Date().toISOString() })); | |
| 289 | 추가: return { snapshot: name, entries }; | |
| 290 | 추가: } finally { | |
| 291 | 추가: if (wasRunning) await this.command('save-on'); | |
| 292 | 추가: } | |
| 293 | 추가: } | |
| 294 | 추가: | |
| 295 | 추가: listSnapshots(): string[] { | |
| 296 | 추가: if (!fs.existsSync(DIRS.snapshots)) return []; | |
| 297 | 추가: return fs.readdirSync(DIRS.snapshots).filter((d) => fs.existsSync(path.join(DIRS.snapshots, d, '.mct-snapshot.json'))); | |
| 298 | 추가: } | |
| 299 | 추가: | |
| 300 | 추가: /** Stop -> replace snapshot paths -> start. Caller reconnects clients. */ | |
| 301 | 추가: async restore(name: string): Promise<object> { | |
| 302 | 추가: const src = path.join(DIRS.snapshots, name); | |
| 303 | 추가: const metaFile = path.join(src, '.mct-snapshot.json'); | |
| 304 | 추가: if (!fs.existsSync(metaFile)) throw new Error(`no snapshot '${name}'. Existing: ${this.listSnapshots().join(', ') || '(none)'}`); | |
| 305 | 추가: const meta = JSON.parse(fs.readFileSync(metaFile, 'utf8')) as { entries: string[] }; | |
| 306 | 추가: const wasRunning = this.running; | |
| 307 | 추가: if (wasRunning) await this.stop(); | |
| 308 | 추가: for (const e of this.snapshotEntries()) fs.rmSync(path.join(this.dir, e), { recursive: true, force: true }); | |
| 309 | 추가: for (const e of meta.entries) fs.cpSync(path.join(src, e), path.join(this.dir, e), { recursive: true }); | |
| 310 | 추가: const started = wasRunning ? await this.start() : null; | |
| 311 | 추가: return { restored: name, entries: meta.entries, restarted: wasRunning, started }; | |
| 312 | 추가: } | |
| 313 | 추가: } | |
| 314 | 추가: | |
| 315 | 추가: export function sleep(ms: number): Promise<void> { | |
| 316 | 추가: return new Promise((r) => setTimeout(r, ms)); | |
| 317 | 추가: } |
| @@ -0,0 +1,121 @@ | ||
| 1 | 추가: // Resolve configured plugin jar patterns to the exact jars to install. | |
| 2 | 추가: // Each jar's plugin.yml / paper-plugin.yml is read so that several builds of the SAME plugin | |
| 3 | 추가: // (old versions left in build/libs, shadow "-all" + plain jar) collapse to the newest one, | |
| 4 | 추가: // while a pattern like "../libs/*.jar" can still bring in many different plugins. | |
| 5 | 추가: import fs from 'node:fs'; | |
| 6 | 추가: import path from 'node:path'; | |
| 7 | 추가: import zlib from 'node:zlib'; | |
| 8 | 추가: import YAML from 'yaml'; | |
| 9 | 추가: import { expandGlob } from './config.ts'; | |
| 10 | 추가: | |
| 11 | 추가: /** Read one entry from a zip/jar without dependencies. Returns null if missing or unreadable. */ | |
| 12 | 추가: export function readZipEntry(file: string, wanted: string): Buffer | null { | |
| 13 | 추가: let buf: Buffer; | |
| 14 | 추가: try { | |
| 15 | 추가: buf = fs.readFileSync(file); | |
| 16 | 추가: } catch { | |
| 17 | 추가: return null; | |
| 18 | 추가: } | |
| 19 | 추가: // End of central directory: signature 0x06054b50, within the last 64KB + 22 bytes. | |
| 20 | 추가: let eocd = -1; | |
| 21 | 추가: for (let i = buf.length - 22; i >= Math.max(0, buf.length - 65_557); i--) { | |
| 22 | 추가: if (buf.readUInt32LE(i) === 0x06054b50) { | |
| 23 | 추가: eocd = i; | |
| 24 | 추가: break; | |
| 25 | 추가: } | |
| 26 | 추가: } | |
| 27 | 추가: if (eocd < 0) return null; | |
| 28 | 추가: const count = buf.readUInt16LE(eocd + 10); | |
| 29 | 추가: let p = buf.readUInt32LE(eocd + 16); | |
| 30 | 추가: for (let n = 0; n < count && p + 46 <= buf.length; n++) { | |
| 31 | 추가: if (buf.readUInt32LE(p) !== 0x02014b50) return null; | |
| 32 | 추가: const method = buf.readUInt16LE(p + 10); | |
| 33 | 추가: const csize = buf.readUInt32LE(p + 20); | |
| 34 | 추가: const nameLen = buf.readUInt16LE(p + 28); | |
| 35 | 추가: const extraLen = buf.readUInt16LE(p + 30); | |
| 36 | 추가: const commentLen = buf.readUInt16LE(p + 32); | |
| 37 | 추가: const local = buf.readUInt32LE(p + 42); | |
| 38 | 추가: const name = buf.subarray(p + 46, p + 46 + nameLen).toString('utf8'); | |
| 39 | 추가: if (name === wanted) { | |
| 40 | 추가: const lNameLen = buf.readUInt16LE(local + 26); | |
| 41 | 추가: const lExtraLen = buf.readUInt16LE(local + 28); | |
| 42 | 추가: const start = local + 30 + lNameLen + lExtraLen; | |
| 43 | 추가: const data = buf.subarray(start, start + csize); | |
| 44 | 추가: try { | |
| 45 | 추가: if (method === 0) return Buffer.from(data); | |
| 46 | 추가: if (method === 8) return zlib.inflateRawSync(data); | |
| 47 | 추가: } catch { | |
| 48 | 추가: return null; | |
| 49 | 추가: } | |
| 50 | 추가: return null; | |
| 51 | 추가: } | |
| 52 | 추가: p += 46 + nameLen + extraLen + commentLen; | |
| 53 | 추가: } | |
| 54 | 추가: return null; | |
| 55 | 추가: } | |
| 56 | 추가: | |
| 57 | 추가: export interface PluginJar { | |
| 58 | 추가: file: string; | |
| 59 | 추가: pattern: string; | |
| 60 | 추가: /** Plugin name from the descriptor, or the file name when the jar has none. */ | |
| 61 | 추가: plugin: string; | |
| 62 | 추가: version: string | null; | |
| 63 | 추가: descriptor: 'paper-plugin.yml' | 'plugin.yml' | null; | |
| 64 | 추가: mtime: string; | |
| 65 | 추가: } | |
| 66 | 추가: | |
| 67 | 추가: export function describeJar(file: string, pattern = file): PluginJar { | |
| 68 | 추가: let plugin = path.basename(file); | |
| 69 | 추가: let version: string | null = null; | |
| 70 | 추가: let descriptor: PluginJar['descriptor'] = null; | |
| 71 | 추가: for (const d of ['paper-plugin.yml', 'plugin.yml'] as const) { | |
| 72 | 추가: const raw = readZipEntry(file, d); | |
| 73 | 추가: if (!raw) continue; | |
| 74 | 추가: try { | |
| 75 | 추가: const y = YAML.parse(raw.toString('utf8')); | |
| 76 | 추가: if (y?.name) { | |
| 77 | 추가: plugin = String(y.name); | |
| 78 | 추가: version = y.version !== undefined ? String(y.version) : null; | |
| 79 | 추가: descriptor = d; | |
| 80 | 추가: break; | |
| 81 | 추가: } | |
| 82 | 추가: } catch { | |
| 83 | 추가: /* fall through */ | |
| 84 | 추가: } | |
| 85 | 추가: } | |
| 86 | 추가: return { file, pattern, plugin, version, descriptor, mtime: fs.statSync(file).mtime.toISOString() }; | |
| 87 | 추가: } | |
| 88 | 추가: | |
| 89 | 추가: export interface Resolution { | |
| 90 | 추가: /** Jars that will be installed: one per plugin, the most recently built. */ | |
| 91 | 추가: selected: PluginJar[]; | |
| 92 | 추가: /** Other jars of an already-selected plugin (older builds, duplicates). */ | |
| 93 | 추가: skipped: (PluginJar & { reason: string })[]; | |
| 94 | 추가: /** Patterns that matched no file. */ | |
| 95 | 추가: unmatched: string[]; | |
| 96 | 추가: } | |
| 97 | 추가: | |
| 98 | 추가: export function resolvePlugins(patterns: string[]): Resolution { | |
| 99 | 추가: const all: PluginJar[] = []; | |
| 100 | 추가: const unmatched: string[] = []; | |
| 101 | 추가: for (const pattern of patterns) { | |
| 102 | 추가: const files = expandGlob(pattern); | |
| 103 | 추가: if (files.length === 0) unmatched.push(pattern); | |
| 104 | 추가: for (const f of files) if (!all.some((j) => j.file === f)) all.push(describeJar(f, pattern)); | |
| 105 | 추가: } | |
| 106 | 추가: const byPlugin = new Map<string, PluginJar[]>(); | |
| 107 | 추가: for (const j of all) { | |
| 108 | 추가: const key = j.plugin.toLowerCase(); | |
| 109 | 추가: byPlugin.set(key, [...(byPlugin.get(key) ?? []), j]); | |
| 110 | 추가: } | |
| 111 | 추가: const selected: PluginJar[] = []; | |
| 112 | 추가: const skipped: Resolution['skipped'] = []; | |
| 113 | 추가: for (const group of byPlugin.values()) { | |
| 114 | 추가: group.sort((a, b) => b.mtime.localeCompare(a.mtime)); | |
| 115 | 추가: selected.push(group[0]); | |
| 116 | 추가: for (const j of group.slice(1)) { | |
| 117 | 추가: skipped.push({ ...j, reason: `older build of plugin '${group[0].plugin}' (using ${path.basename(group[0].file)})` }); | |
| 118 | 추가: } | |
| 119 | 추가: } | |
| 120 | 추가: return { selected, skipped, unmatched }; | |
| 121 | 추가: } |
| @@ -0,0 +1,118 @@ | ||
| 1 | 추가: // Minimal Source RCON client (what Minecraft servers speak on rcon.port). | |
| 2 | 추가: import net from 'node:net'; | |
| 3 | 추가: | |
| 4 | 추가: const AUTH = 3; | |
| 5 | 추가: const EXEC = 2; | |
| 6 | 추가: | |
| 7 | 추가: export class Rcon { | |
| 8 | 추가: private sock: net.Socket | null = null; | |
| 9 | 추가: private buf = Buffer.alloc(0); | |
| 10 | 추가: private nextId = 1; | |
| 11 | 추가: private pending = new Map<number, { resolve: (s: string) => void; reject: (e: Error) => void; parts: string[]; sentinel?: number }>(); | |
| 12 | 추가: private host: string; | |
| 13 | 추가: private port: number; | |
| 14 | 추가: private password: string; | |
| 15 | 추가: | |
| 16 | 추가: constructor(host: string, port: number, password: string) { | |
| 17 | 추가: this.host = host; | |
| 18 | 추가: this.port = port; | |
| 19 | 추가: this.password = password; | |
| 20 | 추가: } | |
| 21 | 추가: | |
| 22 | 추가: get connected(): boolean { | |
| 23 | 추가: return this.sock !== null && !this.sock.destroyed; | |
| 24 | 추가: } | |
| 25 | 추가: | |
| 26 | 추가: async connect(): Promise<void> { | |
| 27 | 추가: if (this.connected) return; | |
| 28 | 추가: await new Promise<void>((resolve, reject) => { | |
| 29 | 추가: const s = net.createConnection({ host: this.host, port: this.port }, () => resolve()); | |
| 30 | 추가: s.once('error', reject); | |
| 31 | 추가: s.on('data', (d) => this.onData(d as Buffer)); | |
| 32 | 추가: s.on('close', () => { | |
| 33 | 추가: this.sock = null; | |
| 34 | 추가: for (const p of this.pending.values()) p.reject(new Error('RCON connection closed')); | |
| 35 | 추가: this.pending.clear(); | |
| 36 | 추가: }); | |
| 37 | 추가: this.sock = s; | |
| 38 | 추가: }); | |
| 39 | 추가: const id = this.nextId++; | |
| 40 | 추가: const res = new Promise<string>((resolve, reject) => this.pending.set(id, { resolve, reject, parts: [] })); | |
| 41 | 추가: this.write(id, AUTH, this.password); | |
| 42 | 추가: await res; | |
| 43 | 추가: } | |
| 44 | 추가: | |
| 45 | 추가: private write(id: number, type: number, body: string): void { | |
| 46 | 추가: const payload = Buffer.from(body, 'utf8'); | |
| 47 | 추가: const pkt = Buffer.alloc(14 + payload.length); | |
| 48 | 추가: pkt.writeInt32LE(10 + payload.length, 0); | |
| 49 | 추가: pkt.writeInt32LE(id, 4); | |
| 50 | 추가: pkt.writeInt32LE(type, 8); | |
| 51 | 추가: payload.copy(pkt, 12); | |
| 52 | 추가: pkt.writeInt16LE(0, 12 + payload.length); | |
| 53 | 추가: this.sock!.write(pkt); | |
| 54 | 추가: } | |
| 55 | 추가: | |
| 56 | 추가: private onData(d: Buffer): void { | |
| 57 | 추가: this.buf = Buffer.concat([this.buf, d]); | |
| 58 | 추가: while (this.buf.length >= 4) { | |
| 59 | 추가: const len = this.buf.readInt32LE(0); | |
| 60 | 추가: if (this.buf.length < 4 + len) return; | |
| 61 | 추가: const id = this.buf.readInt32LE(4); | |
| 62 | 추가: const type = this.buf.readInt32LE(8); | |
| 63 | 추가: const body = this.buf.subarray(12, 4 + len - 2).toString('utf8'); | |
| 64 | 추가: this.buf = this.buf.subarray(4 + len); | |
| 65 | 추가: if (id === -1) { | |
| 66 | 추가: for (const p of this.pending.values()) p.reject(new Error('RCON authentication failed')); | |
| 67 | 추가: this.pending.clear(); | |
| 68 | 추가: continue; | |
| 69 | 추가: } | |
| 70 | 추가: // Fragmented responses: we send a sentinel (id+1 empty) after each command; collect until it echoes. | |
| 71 | 추가: const sentinelFor = this.pending.get(id - 1); | |
| 72 | 추가: if (sentinelFor && sentinelFor.sentinel === id) { | |
| 73 | 추가: this.pending.delete(id - 1); | |
| 74 | 추가: sentinelFor.resolve(sentinelFor.parts.join('')); | |
| 75 | 추가: continue; | |
| 76 | 추가: } | |
| 77 | 추가: const p = this.pending.get(id); | |
| 78 | 추가: if (!p) continue; | |
| 79 | 추가: if (p.sentinel) { | |
| 80 | 추가: p.parts.push(body); | |
| 81 | 추가: } else { | |
| 82 | 추가: void type; | |
| 83 | 추가: this.pending.delete(id); | |
| 84 | 추가: p.resolve(body); | |
| 85 | 추가: } | |
| 86 | 추가: } | |
| 87 | 추가: } | |
| 88 | 추가: | |
| 89 | 추가: async command(cmd: string, timeoutMs = 15000): Promise<string> { | |
| 90 | 추가: await this.connect(); | |
| 91 | 추가: const id = this.nextId; | |
| 92 | 추가: this.nextId += 2; | |
| 93 | 추가: const res = new Promise<string>((resolve, reject) => { | |
| 94 | 추가: const entry = { resolve, reject, parts: [] as string[], sentinel: id + 1 }; | |
| 95 | 추가: this.pending.set(id, entry); | |
| 96 | 추가: setTimeout(() => { | |
| 97 | 추가: if (this.pending.get(id) === entry) { | |
| 98 | 추가: this.pending.delete(id); | |
| 99 | 추가: reject(new Error(`RCON command timed out: ${cmd}`)); | |
| 100 | 추가: } | |
| 101 | 추가: }, timeoutMs); | |
| 102 | 추가: }); | |
| 103 | 추가: this.write(id, EXEC, cmd); | |
| 104 | 추가: // An invalid packet type makes the server answer "Unknown request" with the same id, after the real reply. | |
| 105 | 추가: this.write(id + 1, 200, ''); | |
| 106 | 추가: const raw = await res; | |
| 107 | 추가: return stripFormatting(raw).trim(); | |
| 108 | 추가: } | |
| 109 | 추가: | |
| 110 | 추가: close(): void { | |
| 111 | 추가: this.sock?.destroy(); | |
| 112 | 추가: this.sock = null; | |
| 113 | 추가: } | |
| 114 | 추가: } | |
| 115 | 추가: | |
| 116 | 추가: export function stripFormatting(s: string): string { | |
| 117 | 추가: return s.replace(/§[0-9a-fk-orx]/gi, ''); | |
| 118 | 추가: } |
| @@ -0,0 +1,89 @@ | ||
| 1 | 추가: // Client side of the daemon RPC, with auto-start of the daemon. | |
| 2 | 추가: import http from 'node:http'; | |
| 3 | 추가: import fs from 'node:fs'; | |
| 4 | 추가: import path from 'node:path'; | |
| 5 | 추가: import { spawn } from 'node:child_process'; | |
| 6 | 추가: import { DIRS, ROOT, ensureDirs, loadConfig } from './config.ts'; | |
| 7 | 추가: | |
| 8 | 추가: const cfg = loadConfig(); | |
| 9 | 추가: | |
| 10 | 추가: function request(method: string, route: string, body?: unknown): Promise<any> { | |
| 11 | 추가: return new Promise((resolve, reject) => { | |
| 12 | 추가: const data = body === undefined ? undefined : Buffer.from(JSON.stringify(body)); | |
| 13 | 추가: const req = http.request( | |
| 14 | 추가: { host: '127.0.0.1', port: cfg.daemonPort, path: route, method, headers: data ? { 'Content-Type': 'application/json', 'Content-Length': data.length } : {} }, | |
| 15 | 추가: (res) => { | |
| 16 | 추가: const chunks: Buffer[] = []; | |
| 17 | 추가: res.on('data', (c) => chunks.push(c)); | |
| 18 | 추가: res.on('end', () => { | |
| 19 | 추가: try { | |
| 20 | 추가: resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); | |
| 21 | 추가: } catch (e) { | |
| 22 | 추가: reject(e); | |
| 23 | 추가: } | |
| 24 | 추가: }); | |
| 25 | 추가: }, | |
| 26 | 추가: ); | |
| 27 | 추가: req.on('error', reject); | |
| 28 | 추가: if (data) req.write(data); | |
| 29 | 추가: req.end(); | |
| 30 | 추가: }); | |
| 31 | 추가: } | |
| 32 | 추가: | |
| 33 | 추가: export async function daemonUp(): Promise<boolean> { | |
| 34 | 추가: try { | |
| 35 | 추가: const r = await request('GET', '/health'); | |
| 36 | 추가: return !!r.ok; | |
| 37 | 추가: } catch { | |
| 38 | 추가: return false; | |
| 39 | 추가: } | |
| 40 | 추가: } | |
| 41 | 추가: | |
| 42 | 추가: export async function ensureDaemon(): Promise<void> { | |
| 43 | 추가: if (await daemonUp()) return; | |
| 44 | 추가: ensureDirs(); | |
| 45 | 추가: const out = fs.openSync(path.join(DIRS.run, 'daemon.out'), 'a'); | |
| 46 | 추가: const child = spawn(process.execPath, [path.join(ROOT, 'harness', 'daemon.ts')], { | |
| 47 | 추가: cwd: ROOT, | |
| 48 | 추가: detached: true, | |
| 49 | 추가: stdio: ['ignore', out, out], | |
| 50 | 추가: env: process.env, | |
| 51 | 추가: }); | |
| 52 | 추가: child.unref(); | |
| 53 | 추가: const t0 = Date.now(); | |
| 54 | 추가: while (Date.now() - t0 < 15_000) { | |
| 55 | 추가: if (await daemonUp()) return; | |
| 56 | 추가: await new Promise((r) => setTimeout(r, 200)); | |
| 57 | 추가: } | |
| 58 | 추가: throw new Error(`daemon did not start; see ${path.join(DIRS.run, 'daemon.out')}`); | |
| 59 | 추가: } | |
| 60 | 추가: | |
| 61 | 추가: export async function call(tool: string, params: object = {}): Promise<any> { | |
| 62 | 추가: await ensureDaemon(); | |
| 63 | 추가: const r = await request('POST', '/rpc', { tool, params }); | |
| 64 | 추가: if (!r.ok) throw new Error(r.error); | |
| 65 | 추가: return r.result; | |
| 66 | 추가: } | |
| 67 | 추가: | |
| 68 | 추가: /** Ask the daemon to stop clients + server and exit; waits until the process is gone. */ | |
| 69 | 추가: export async function shutdownDaemon(timeoutMs = 90_000): Promise<boolean> { | |
| 70 | 추가: let pid: number | null = null; | |
| 71 | 추가: try { | |
| 72 | 추가: const h = await request('GET', '/health'); | |
| 73 | 추가: if (!h.ok) return false; | |
| 74 | 추가: pid = h.pid; | |
| 75 | 추가: } catch { | |
| 76 | 추가: return false; | |
| 77 | 추가: } | |
| 78 | 추가: await request('POST', '/shutdown', {}); | |
| 79 | 추가: const t0 = Date.now(); | |
| 80 | 추가: while (Date.now() - t0 < timeoutMs) { | |
| 81 | 추가: try { | |
| 82 | 추가: process.kill(pid!, 0); | |
| 83 | 추가: } catch { | |
| 84 | 추가: return true; // process gone | |
| 85 | 추가: } | |
| 86 | 추가: await new Promise((r) => setTimeout(r, 300)); | |
| 87 | 추가: } | |
| 88 | 추가: throw new Error(`daemon pid ${pid} still running after ${timeoutMs}ms`); | |
| 89 | 추가: } |
| @@ -0,0 +1,220 @@ | ||
| 1 | 추가: // YAML scenario runner: ordered tool calls + assertions, with failure screenshots and a JSON report. | |
| 2 | 추가: import fs from 'node:fs'; | |
| 3 | 추가: import path from 'node:path'; | |
| 4 | 추가: import YAML from 'yaml'; | |
| 5 | 추가: import { DIRS, ROOT, stamp } from './config.ts'; | |
| 6 | 추가: import { TOOL_MAP, type Ctx } from './tools.ts'; | |
| 7 | 추가: import { sleep } from './paper.ts'; | |
| 8 | 추가: | |
| 9 | 추가: /** For `- tool: "string"` shorthand: which parameter the string fills. */ | |
| 10 | 추가: const DEFAULT_ARG: Record<string, string> = { | |
| 11 | 추가: rcon: 'command', | |
| 12 | 추가: chat: 'text', | |
| 13 | 추가: type_text: 'text', | |
| 14 | 추가: key: 'key', | |
| 15 | 추가: screenshot: 'label', | |
| 16 | 추가: world_reset: 'name', | |
| 17 | 추가: world_snapshot: 'name', | |
| 18 | 추가: client_launch: 'name', | |
| 19 | 추가: client_stop: 'client', | |
| 20 | 추가: expect_rcon: 'command', | |
| 21 | 추가: expect_chat: 'chat', | |
| 22 | 추가: run_scenario: 'file', | |
| 23 | 추가: }; | |
| 24 | 추가: | |
| 25 | 추가: interface StepResult { | |
| 26 | 추가: phase: string; | |
| 27 | 추가: index: number; | |
| 28 | 추가: label?: string; | |
| 29 | 추가: tool: string; | |
| 30 | 추가: args: any; | |
| 31 | 추가: ok: boolean; | |
| 32 | 추가: ms: number; | |
| 33 | 추가: result?: any; | |
| 34 | 추가: error?: string; | |
| 35 | 추가: skipped?: boolean; | |
| 36 | 추가: } | |
| 37 | 추가: | |
| 38 | 추가: function short(v: any, max = 1500): any { | |
| 39 | 추가: const s = JSON.stringify(v); | |
| 40 | 추가: if (s === undefined || s.length <= max) return v; | |
| 41 | 추가: return s.slice(0, max) + `... (${s.length} chars)`; | |
| 42 | 추가: } | |
| 43 | 추가: | |
| 44 | 추가: function parseStep(raw: any): { tool: string; args: any; label?: string } { | |
| 45 | 추가: if (typeof raw === 'string') return { tool: raw, args: {} }; | |
| 46 | 추가: const keys = Object.keys(raw).filter((k) => k !== 'label'); | |
| 47 | 추가: if (keys.length !== 1) throw new Error(`a step must have exactly one tool key (plus optional label): ${JSON.stringify(raw)}`); | |
| 48 | 추가: const tool = keys[0]; | |
| 49 | 추가: let args = raw[tool]; | |
| 50 | 추가: if (args === null || args === undefined) args = {}; | |
| 51 | 추가: else if (typeof args !== 'object') { | |
| 52 | 추가: if (tool === 'sleep') args = { ms: Number(args) }; | |
| 53 | 추가: else if (DEFAULT_ARG[tool]) args = { [DEFAULT_ARG[tool]]: args }; | |
| 54 | 추가: else throw new Error(`step '${tool}' needs an object of arguments`); | |
| 55 | 추가: } | |
| 56 | 추가: return { tool, args, label: raw.label }; | |
| 57 | 추가: } | |
| 58 | 추가: | |
| 59 | 추가: function itemMatches(item: any, q: any): boolean { | |
| 60 | 추가: if (!item) return false; | |
| 61 | 추가: if (q.id && item.id !== q.id && item.id !== `minecraft:${q.id}`) return false; | |
| 62 | 추가: if (q.name && !String(item.name).includes(q.name)) return false; | |
| 63 | 추가: if (q.lore && !(item.lore ?? []).concat(item.tooltip ?? []).some((l: string) => l.includes(q.lore))) return false; | |
| 64 | 추가: return true; | |
| 65 | 추가: } | |
| 66 | 추가: | |
| 67 | 추가: function compareCount(actual: number, q: any): boolean { | |
| 68 | 추가: if (q.count !== undefined && actual !== q.count) return false; | |
| 69 | 추가: if (q.min !== undefined && actual < q.min) return false; | |
| 70 | 추가: if (q.max !== undefined && actual > q.max) return false; | |
| 71 | 추가: return true; | |
| 72 | 추가: } | |
| 73 | 추가: | |
| 74 | 추가: export async function runScenario(ctx: Ctx, file: string, opts: { stopOnFail?: boolean } = {}): Promise<object> { | |
| 75 | 추가: const abs = path.isAbsolute(file) ? file : path.join(ROOT, file); | |
| 76 | 추가: const doc = YAML.parse(fs.readFileSync(abs, 'utf8')) ?? {}; | |
| 77 | 추가: const name = doc.name ?? path.basename(abs); | |
| 78 | 추가: const stopOnFail = opts.stopOnFail ?? true; | |
| 79 | 추가: const startSeq = ctx.server.running ? ctx.server.logSeq : 0; | |
| 80 | 추가: const results: StepResult[] = []; | |
| 81 | 추가: const screenshots: string[] = []; | |
| 82 | 추가: const t0 = Date.now(); | |
| 83 | 추가: let failed = false; | |
| 84 | 추가: | |
| 85 | 추가: const asserts: Record<string, (a: any) => Promise<any>> = { | |
| 86 | 추가: sleep: async (a) => { | |
| 87 | 추가: await sleep(a.ms ?? 500); | |
| 88 | 추가: return { slept: a.ms ?? 500 }; | |
| 89 | 추가: }, | |
| 90 | 추가: expect_rcon: async (a) => { | |
| 91 | 추가: const out: string = await ctx.server.command(a.command); | |
| 92 | 추가: if (a.contains !== undefined && !out.includes(a.contains)) throw new Error(`rcon output does not contain ${JSON.stringify(a.contains)}: ${out}`); | |
| 93 | 추가: if (a.not_contains !== undefined && out.includes(a.not_contains)) throw new Error(`rcon output contains ${JSON.stringify(a.not_contains)}: ${out}`); | |
| 94 | 추가: if (a.matches !== undefined && !new RegExp(a.matches).test(out)) throw new Error(`rcon output does not match /${a.matches}/: ${out}`); | |
| 95 | 추가: if (a.json !== undefined) { | |
| 96 | 추가: const m = out.match(/\{.*\}/s); | |
| 97 | 추가: if (!m) throw new Error(`rcon output has no JSON object: ${out}`); | |
| 98 | 추가: const obj = JSON.parse(m[0]); | |
| 99 | 추가: for (const [k, v] of Object.entries(a.json)) { | |
| 100 | 추가: if (JSON.stringify(obj[k]) !== JSON.stringify(v)) throw new Error(`json.${k} = ${JSON.stringify(obj[k])}, expected ${JSON.stringify(v)} (full: ${m[0]})`); | |
| 101 | 추가: } | |
| 102 | 추가: } | |
| 103 | 추가: return { output: out }; | |
| 104 | 추가: }, | |
| 105 | 추가: expect_chat: async (a) => TOOL_MAP.get('wait_for')!.run(ctx, { client: a.client, chat: a.chat, since: a.since, timeout_ms: a.timeout_ms ?? 5000 }), | |
| 106 | 추가: expect_screen: async (a) => { | |
| 107 | 추가: const scr = await ctx.clients.call(a.client, 'screen'); | |
| 108 | 추가: if (a.closed === true) { | |
| 109 | 추가: if (scr.open) throw new Error(`expected no screen, but ${scr.class} "${scr.title}" is open`); | |
| 110 | 추가: return { closed: true }; | |
| 111 | 추가: } | |
| 112 | 추가: if (!scr.open) throw new Error('expected a screen to be open, but none is'); | |
| 113 | 추가: if (a.title !== undefined && !new RegExp(a.title).test(scr.title)) throw new Error(`screen title "${scr.title}" does not match /${a.title}/`); | |
| 114 | 추가: if (a.has_item) { | |
| 115 | 추가: const q = a.has_item; | |
| 116 | 추가: const area = q.area ?? 'container'; | |
| 117 | 추가: const hits = (scr.slots ?? []).filter((s: any) => (area === 'any' || s.area === area) && itemMatches(s.item, q)); | |
| 118 | 추가: if (hits.length === 0) throw new Error(`no ${area} slot with ${JSON.stringify(q)}`); | |
| 119 | 추가: if (q.slot !== undefined && !hits.some((h: any) => h.slot === q.slot)) throw new Error(`item found but not in slot ${q.slot}: ${hits.map((h: any) => h.slot)}`); | |
| 120 | 추가: } | |
| 121 | 추가: if (a.carried !== undefined) { | |
| 122 | 추가: if (a.carried === null && scr.carried) throw new Error(`expected empty cursor, carrying ${JSON.stringify(scr.carried)}`); | |
| 123 | 추가: if (a.carried && !itemMatches(scr.carried, a.carried)) throw new Error(`cursor item ${JSON.stringify(scr.carried)} != ${JSON.stringify(a.carried)}`); | |
| 124 | 추가: } | |
| 125 | 추가: return { title: scr.title, class: scr.class }; | |
| 126 | 추가: }, | |
| 127 | 추가: expect_inventory: async (a) => { | |
| 128 | 추가: const st = await ctx.clients.call(a.client, 'state'); | |
| 129 | 추가: const total = (st.player?.inventory ?? []) | |
| 130 | 추가: .filter((e: any) => itemMatches(e.item, a)) | |
| 131 | 추가: .reduce((n: number, e: any) => n + e.item.count, 0); | |
| 132 | 추가: if (!compareCount(total, a)) throw new Error(`inventory has ${total} of ${JSON.stringify({ id: a.id, name: a.name })}, expected ${JSON.stringify({ count: a.count, min: a.min, max: a.max })}`); | |
| 133 | 추가: return { count: total }; | |
| 134 | 추가: }, | |
| 135 | 추가: expect_no_server_errors: async (a) => { | |
| 136 | 추가: const errs = ctx.server.errors(a.since ?? startSeq).filter((l) => !(a.ignore ?? []).some((ig: string) => new RegExp(ig).test(l.text))); | |
| 137 | 추가: if (errs.length) throw new Error(`server logged ${errs.length} error line(s):\n${errs.slice(0, 20).map((l) => l.text).join('\n')}`); | |
| 138 | 추가: return { errors: 0 }; | |
| 139 | 추가: }, | |
| 140 | 추가: expect_error: async (a) => { | |
| 141 | 추가: // Run a nested step that MUST fail (e.g. clicking something that should be rejected). | |
| 142 | 추가: const inner = parseStep(a.step); | |
| 143 | 추가: try { | |
| 144 | 추가: await exec(inner.tool, inner.args); | |
| 145 | 추가: } catch (e) { | |
| 146 | 추가: const msg = (e as Error).message; | |
| 147 | 추가: if (a.matches && !new RegExp(a.matches).test(msg)) throw new Error(`step failed, but message /${a.matches}/ not matched: ${msg}`); | |
| 148 | 추가: return { failedAsExpected: msg }; | |
| 149 | 추가: } | |
| 150 | 추가: throw new Error(`expected step ${inner.tool} to fail, but it succeeded`); | |
| 151 | 추가: }, | |
| 152 | 추가: }; | |
| 153 | 추가: | |
| 154 | 추가: async function exec(tool: string, args: any): Promise<any> { | |
| 155 | 추가: if (asserts[tool]) return asserts[tool](args); | |
| 156 | 추가: const t = TOOL_MAP.get(tool); | |
| 157 | 추가: if (!t) throw new Error(`unknown step '${tool}'. Tools: ${[...TOOL_MAP.keys()].join(', ')}; assertions: ${Object.keys(asserts).join(', ')}`); | |
| 158 | 추가: if (tool === 'run_scenario') throw new Error('nested run_scenario is not supported'); | |
| 159 | 추가: return t.run(ctx, args); | |
| 160 | 추가: } | |
| 161 | 추가: | |
| 162 | 추가: async function phase(phaseName: string, steps: any[] | undefined, always = false) { | |
| 163 | 추가: for (const [i, raw] of (steps ?? []).entries()) { | |
| 164 | 추가: let parsed: { tool: string; args: any; label?: string }; | |
| 165 | 추가: try { | |
| 166 | 추가: parsed = parseStep(raw); | |
| 167 | 추가: } catch (e) { | |
| 168 | 추가: results.push({ phase: phaseName, index: i, tool: '?', args: raw, ok: false, ms: 0, error: (e as Error).message }); | |
| 169 | 추가: failed = true; | |
| 170 | 추가: if (stopOnFail && !always) return; | |
| 171 | 추가: continue; | |
| 172 | 추가: } | |
| 173 | 추가: if (failed && stopOnFail && !always) { | |
| 174 | 추가: results.push({ phase: phaseName, index: i, label: parsed.label, tool: parsed.tool, args: parsed.args, ok: false, ms: 0, skipped: true }); | |
| 175 | 추가: continue; | |
| 176 | 추가: } | |
| 177 | 추가: const s0 = Date.now(); | |
| 178 | 추가: try { | |
| 179 | 추가: const result = await exec(parsed.tool, parsed.args); | |
| 180 | 추가: if (result?.screenshot) screenshots.push(result.screenshot); | |
| 181 | 추가: if (parsed.tool === 'screenshot' && result?.path) screenshots.push(result.path); | |
| 182 | 추가: results.push({ phase: phaseName, index: i, label: parsed.label, tool: parsed.tool, args: parsed.args, ok: true, ms: Date.now() - s0, result: short(result) }); | |
| 183 | 추가: } catch (e) { | |
| 184 | 추가: failed = failed || !always; | |
| 185 | 추가: const err = (e as Error).message; | |
| 186 | 추가: results.push({ phase: phaseName, index: i, label: parsed.label, tool: parsed.tool, args: parsed.args, ok: false, ms: Date.now() - s0, error: err }); | |
| 187 | 추가: // Evidence: screenshot every running client at the moment of failure. | |
| 188 | 추가: for (const c of ctx.clients.running()) { | |
| 189 | 추가: try { | |
| 190 | 추가: const r = await TOOL_MAP.get('screenshot')!.run(ctx, { client: c, label: `FAIL-${parsed.tool}` }); | |
| 191 | 추가: screenshots.push(r.path); | |
| 192 | 추가: } catch { | |
| 193 | 추가: /* ignore */ | |
| 194 | 추가: } | |
| 195 | 추가: } | |
| 196 | 추가: } | |
| 197 | 추가: } | |
| 198 | 추가: } | |
| 199 | 추가: | |
| 200 | 추가: await phase('setup', doc.setup); | |
| 201 | 추가: await phase('steps', doc.steps); | |
| 202 | 추가: await phase('teardown', doc.teardown, true); | |
| 203 | 추가: | |
| 204 | 추가: const passed = !failed && results.every((r) => r.ok || r.phase === 'teardown'); | |
| 205 | 추가: const serverErrors = ctx.server.running || ctx.server.logSeq > 0 ? ctx.server.errors(startSeq).slice(0, 50).map((l) => l.text) : []; | |
| 206 | 추가: const report = { | |
| 207 | 추가: name, | |
| 208 | 추가: file: path.relative(ROOT, abs), | |
| 209 | 추가: passed, | |
| 210 | 추가: durationMs: Date.now() - t0, | |
| 211 | 추가: failures: results.filter((r) => !r.ok && !r.skipped).map((r) => ({ phase: r.phase, index: r.index, label: r.label, tool: r.tool, error: r.error })), | |
| 212 | 추가: steps: results, | |
| 213 | 추가: screenshots, | |
| 214 | 추가: serverErrors, | |
| 215 | 추가: }; | |
| 216 | 추가: fs.mkdirSync(DIRS.reports, { recursive: true }); | |
| 217 | 추가: const reportPath = path.join(DIRS.reports, `${stamp()}-${path.basename(abs).replace(/\.ya?ml$/, '')}.json`); | |
| 218 | 추가: fs.writeFileSync(reportPath, JSON.stringify(report, null, 2)); | |
| 219 | 추가: return { ...report, report: reportPath }; | |
| 220 | 추가: } |
Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기