@sususgh/gamer-dsh-plugin 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,546 @@
1
- # Temporary Holding Version
1
+ # Gamer DSH Plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **PC-first AI game agent + Android companion | DeepSeek Harness integration**
4
+
5
+ Gamer DSH Plugin is the Windows/desktop control center and AI orchestration layer for the Gamer game-agent ecosystem. It connects a DeepSeek Harness (DSH) agent, a desktop Gamer Engine, model APIs and (when playing mobile games) an Android phone.
6
+
7
+ The key design is simple:
8
+
9
+ > **The computer does the main processing and AI orchestration. DeepSeek (or another configured model API) provides the reasoning. The phone runs the mobile game, captures observations and executes touch actions.**
10
+
11
+ The phone is not expected to host a large language model. It can perform lightweight device-side work, while the computer handles the heavier vision pipeline, game context, model requests, planning, validation, telemetry and coordination.
12
+
13
+ - **Repository:** https://github.com/sususgh/Gamer-DSH-Plugin
14
+ - **DSH plugin package:** `@sususgh/gamer-dsh-plugin` (install this package name from DSH Plugins → Add plugin)
15
+ - **Companion project:** Gamer-Mobile (Android)
16
+ - **Primary target:** Windows desktop + Android phone
17
+ - **DSH role:** agent entry point, tool orchestration, session and task coordination
18
+ - **Model role:** game understanding and decision-making through DeepSeek API or compatible model adapters
19
+ - **Desktop role:** main processing, local game control, model routing, device bridge and telemetry
20
+ - **Android role:** mobile game runtime, screen/audio/sensor observations when permitted, touch execution and acknowledgements
21
+
22
+ > **Project status:** This repository is being bootstrapped. The first desktop UI shell is a visual prototype. Network values, model health and device status are not real until their runtime adapters are connected and tested. This README describes the intended architecture and integration contract; it does not claim that every planned feature is already implemented.
23
+
24
+ ---
25
+
26
+ ## 1. What the project does
27
+
28
+ Gamer is designed to let an AI agent play supported games through a closed feedback loop:
29
+
30
+ 1. Observe the game screen or an allowed game-state signal.
31
+ 2. Process the observation and extract useful visual/state information.
32
+ 3. Give the relevant context to a vision-capable and/or reasoning-capable model.
33
+ 4. Receive a structured decision from the model.
34
+ 5. Validate the decision locally before execution.
35
+ 6. Send the action to the computer game or paired Android phone.
36
+ 7. Receive execution acknowledgement and capture the next observation.
37
+ 8. Verify the result, update game context and plan the next action.
38
+
39
+ The system is intended for both PC games and Android mobile games. The location where the game runs is separate from the location where the main AI processing runs.
40
+
41
+ ## 2. End-to-end user workflow: desktop QR → Android → start playing
42
+
43
+ The intended product has two clients with different responsibilities:
44
+
45
+ - **Windows/desktop application:** the control center. It owns the DSH integration, configured model/API profile, primary processing pipeline, game-agent coordinator and device session.
46
+ - **Android application:** the mobile companion and game terminal. It scans the desktop's pairing QR code, obtains explicit user confirmation, runs the mobile game, captures observations and executes approved touch actions.
47
+
48
+ ### Pairing and start sequence
49
+
50
+ 1. The desktop user opens **Connect Android**. The desktop generates a short-lived, single-use QR pairing code containing a pairing token and the host connection information. It must not contain a permanent model API key.
51
+ 2. The Android user opens Gamer-Mobile and scans the QR code.
52
+ 3. Android displays the desktop identity and requested permissions. The user explicitly taps **Confirm connection**.
53
+ 4. The desktop validates the one-time token and authenticates the phone. Both clients complete a session handshake and show **Paired / Connected** only after authentication succeeds.
54
+ 5. The desktop reads the active DSH model/API configuration through its local integration. It resolves the configured provider, API base URL, model identifier and supported capabilities. The phone does not need to know or store the model API key.
55
+ 6. Android displays the available connection and model/session status. The user opens a supported game and taps **Start** on the phone.
56
+ 7. Android sends a start-session command to the desktop. The desktop checks pairing, permissions, model health, game profile and safety conditions before accepting the session.
57
+ 8. The desktop begins the observe → vision → model reasoning → action planning → validation loop. It sends approved touch actions to Android, receives acknowledgements and new frames, and continues while the session is active.
58
+ 9. The user can pause or stop from either client. A stop command takes priority over autonomous goals and queued actions.
59
+
60
+ **QR scanning is not the same as pairing success.** A decoded QR must still be confirmed, authenticated and exchanged for a session credential. If confirmation is declined, the token expires, authentication fails or the host is unreachable, the clients must show an error/retry state and must not report a successful connection.
61
+
62
+ ### Automatic API/provider recognition
63
+
64
+ Gamer should use the **active model configuration already selected in DSH**, rather than requiring users to enter a second API key in the Android app.
65
+
66
+ The desktop integration should resolve:
67
+ - Provider identifier (for example, DeepSeek or another configured provider)
68
+ - API base URL / endpoint
69
+ - Model identifier
70
+ - Authentication secret reference (kept local on desktop)
71
+ - Declared capabilities such as vision, reasoning and structured output
72
+ - Timeout, context and request settings supported by that provider
73
+
74
+ The adapter routes requests to the currently selected, healthy provider. If the user changes the active DSH model, the desktop should refresh the model configuration at a safe session boundary, verify the new endpoint with a probe, and then use it. If the selected model is unavailable or lacks a required capability, pause and explain the issue or use an explicitly configured compatible fallback. Never guess a provider from an API key string, expose credentials to the phone, or silently send requests to an unrelated endpoint.
75
+
76
+ A text-only DeepSeek/model endpoint cannot interpret raw screenshots by itself. For pure-computer-vision gameplay, the desktop can run local visual perception (image processing, OCR, UI/object detection and game-state extraction) and send structured observations to a text reasoning model. If the chosen model itself supports image input, the adapter may send selected frames/crops as well. The architecture must support both paths and declare which one is active.
77
+
78
+ ## 3. Game-agnostic visual learning and gameplay
79
+
80
+ The intended agent is not limited to one hard-coded game. It should use general computer-vision and AI techniques to observe a game, infer its current state, learn controls and mechanics through permitted interaction, and improve its policy from observed outcomes.
81
+
82
+ The general learning loop is:
83
+
84
+ 1. Detect the game window/screen, UI elements, scene changes and relevant objects.
85
+ 2. Estimate state such as player position, health, inventory, objectives, menus, hazards and available controls when visually observable.
86
+ 3. Identify the current game/profile and map screen coordinates to normalized actions.
87
+ 4. Form a small hypothesis or goal, choose a low-risk action and execute it.
88
+ 5. Compare the next observation with the predicted result.
89
+ 6. Record successful/failed action outcomes and update the game-specific state/profile.
90
+ 7. Repeat, progressively learning navigation, interaction patterns and task sequences.
91
+
92
+ **Minecraft, Genshin Impact and other games are target examples, not a guarantee of universal compatibility on day one.** Each game has different camera controls, UI, combat timing, menus, permissions and input mappings. A game profile and validation/testing are required for reliable support. For example, Minecraft may require movement, camera, inventory, block interaction and survival-state perception; Genshin Impact may require camera, movement, menus, combat and interaction recognition. The system should not assume the same actions or mechanics exist in every title.
93
+
94
+ “Learning” here means measurable software adaptation: building visual/game state, remembering action outcomes, updating game profiles and improving strategies. It does not imply that the model permanently trains its neural-network weights during play. Persistent learning data should be stored locally and be inspectable/resettable by the user.
95
+
96
+ The project should rely on screen-based computer vision and approved input interfaces. It must not bypass anti-cheat, tamper with game memory, inject unauthorized code or defeat platform protections. Respect each game's terms and applicable laws.
97
+
98
+
99
+ ## 3.1 Built-in vision, online game research and persistent experience
100
+
101
+ The intended Gamer Engine includes three cooperating subsystems. They are part of the product architecture, not a requirement that every DSH model natively understand images.
102
+
103
+ ### Visual perception engine
104
+
105
+ The desktop vision pipeline should support:
106
+ - Frame validation, orientation detection, resize/crop and duplicate-frame suppression.
107
+ - OCR for menus, dialogue, quest text, item labels and visible HUD values.
108
+ - UI element detection and matching for buttons, maps, health bars, inventory and interaction prompts.
109
+ - Object/scene detection for game-specific targets, hazards, characters and landmarks where a suitable detector/profile exists.
110
+ - Temporal tracking across frames so the agent can distinguish a moving object from a static UI element.
111
+ - Structured game-state output with timestamps, confidence, source frame IDs and unknown values when evidence is insufficient.
112
+
113
+ A text-only model can receive the structured state without receiving raw screenshots. A model that explicitly supports image input may additionally receive selected frames or crops. The system must never silently assume that a text-only endpoint is multimodal.
114
+
115
+ ### Online guide and knowledge research
116
+
117
+ When a task is blocked or the agent needs game knowledge, a research adapter may search the web for official documentation, game wikis, patch notes and community guides. Every retrieved claim should retain its source URL, title, retrieval time, game version/patch context and confidence.
118
+
119
+ The agent should:
120
+ 1. Form a focused query from the current game, quest, location, boss or mechanic.
121
+ 2. Prefer official sources and well-maintained references; compare multiple sources for consequential mechanics.
122
+ 3. Extract a concise procedure and cite the source records in its internal task context.
123
+ 4. Compare the guide's game version and prerequisites with the live visual state.
124
+ 5. Treat web pages as untrusted reference data, never as executable instructions or permission to run downloads/scripts.
125
+ 6. Mark conflicting, outdated or unverified guidance as uncertain and ask the user when needed.
126
+
127
+ Online research is optional and user-configurable. The agent must not upload screenshots, account identifiers or personal data to search providers unless the user has explicitly enabled that behavior.
128
+
129
+ ### Local experience memory and adaptive strategies
130
+
131
+ Store compact, inspectable records such as:
132
+ - Game/profile/version and relevant scene or task identifier.
133
+ - Observation features and confidence, not necessarily every raw screenshot.
134
+ - Action type, parameters, duration and execution acknowledgement.
135
+ - Expected result versus observed result.
136
+ - Success/failure/uncertain outcome and a short reason.
137
+ - Strategy revision, timestamp and provenance (live observation or external guide).
138
+
139
+ Use retrieval by game, scene, objective and similar state. Update strategy scores only from verified outcomes; do not treat an unacknowledged action as success. Keep profiles isolated by game and allow the user to inspect, export and delete memory. This is local policy/experience adaptation, not automatic fine-tuning of model weights.
140
+
141
+ ### Game profiles and compatibility
142
+
143
+ Each supported title needs a versioned profile containing screen layout assumptions, OCR labels, target classes, coordinate calibration, allowed action types, timing bounds, task-state rules and test fixtures. Minecraft and Genshin Impact are target profiles, not claims of current compatibility. Add a profile only after repeatable tests demonstrate observation quality, safe action execution and recovery behavior.
144
+
145
+ See [Vision, research and game-memory design](docs/vision-research-memory.md) for the detailed subsystem contract.
146
+
147
+ ## 4. Two operating modes
148
+
149
+ ### Mode A — AI plays a PC game
150
+
151
+ The game runs on the desktop computer.
152
+
153
+ - The desktop capture adapter obtains screenshots or selected game-window regions.
154
+ - Local vision adapters preprocess frames and, where supported, perform OCR/UI/object recognition.
155
+ - The DSH agent and Gamer coordinator maintain the task, game context and recent action history.
156
+ - The model adapter sends the necessary observation and context to DeepSeek API or another configured model.
157
+ - The model returns a proposed decision or structured action.
158
+ - The desktop action adapter validates and executes supported keyboard, mouse, controller or game-specific input.
159
+ - The engine captures the next frame and verifies whether the expected state change occurred.
160
+
161
+ In this mode, the computer runs both the game and the main processing pipeline. An Android phone is optional.
162
+
163
+ ### Mode B — AI plays an Android mobile game
164
+
165
+ The game runs on the Android phone. **The computer remains the primary AI workstation.**
166
+
167
+ **Android phone — device-side responsibilities**
168
+ - Run the actual mobile game.
169
+ - Capture the game screen or provide permitted observation data.
170
+ - Send frames/metadata to the paired computer.
171
+ - Execute approved tap, swipe, press, release and other supported touch actions.
172
+ - Return action acknowledgements, device state and timestamps.
173
+ - Optionally perform lightweight work such as image encoding, basic checks and sensor sampling.
174
+ - Display companion status and play optional local TTS audio when enabled.
175
+
176
+ **Desktop computer — main processing responsibilities**
177
+ - Receive and validate observations from the phone.
178
+ - Perform the heavier image preprocessing, OCR, UI recognition and visual-state aggregation supported by installed modules.
179
+ - Maintain game objectives, current state, recent observations and action history.
180
+ - Select an appropriate model based on capabilities and health.
181
+ - Call the configured DeepSeek API for AI reasoning and decision-making.
182
+ - Convert model output into a constrained action plan and validate coordinates, action types, durations and deadlines.
183
+ - Send the approved action to the phone.
184
+ - Receive the phone's acknowledgement and the next observation.
185
+ - Verify the result, update telemetry and decide whether to continue, re-plan or pause.
186
+
187
+ **Important distinction:** DeepSeek API is the reasoning service; it is not the machine that captures the phone screen or physically touches the game. The computer runs the local Gamer Engine and communicates with the API. The phone runs the game and performs device input. The phone may process a small amount of data locally, but the main workload is designed to stay on the computer.
188
+
189
+ The data split is configurable. Not every frame must be uploaded to a model API: local preprocessing can reduce image size and send only the relevant frame, crop, extracted state and context required for a decision.
190
+
191
+ ## 5. Architecture overview
192
+
193
+ ```text
194
+ User
195
+ |
196
+ v
197
+ DeepSeek Harness (DSH)
198
+ Plugin / Agent / Tool Layer
199
+ |
200
+ Task and tool control
201
+ |
202
+ v
203
+ Desktop Gamer Engine
204
+ +------------------+-------------------+
205
+ | | |
206
+ v v v
207
+ Vision & State Game Context Session / Task
208
+ Processing and History Coordinator
209
+ | | |
210
+ +------------------+-------------------+
211
+ |
212
+ v
213
+ Model Capability Router
214
+ |
215
+ v
216
+ Model API Adapter
217
+ DeepSeek / compatible APIs
218
+ |
219
+ structured decision
220
+ |
221
+ v
222
+ Action Planner & Validator
223
+ |
224
+ Execution Action Router
225
+ / \
226
+ / \
227
+ PC Game Adapter Android Bridge
228
+ | USB / ADB / LAN
229
+ v |
230
+ Desktop Game v
231
+ Android Gamer-Mobile
232
+ +------------------+
233
+ | Mobile Game |
234
+ | Screen Capture |
235
+ | Touch Execution |
236
+ | Action ACK |
237
+ +------------------+
238
+ |
239
+ observations / results
240
+ |
241
+ +----> Desktop Engine
242
+ ```
243
+
244
+ The DSH plugin coordinates the agent and tools. The desktop engine is the main runtime and processing center. Model adapters provide reasoning. PC and Android adapters connect the runtime to the actual game device.
245
+
246
+ ## 6. Main processing loop
247
+
248
+ The intended loop is:
249
+
250
+ 1. **Observe** — capture a PC game frame or receive an Android frame.
251
+ 2. **Preprocess** — crop, resize, encode and extract available UI/text/state signals locally.
252
+ 3. **Update context** — combine the observation with the current objective, previous state and recent action outcomes.
253
+ 4. **Select model** — choose a healthy model whose declared capabilities match the task.
254
+ 5. **Reason** — send the relevant observation/context to the model API and request a structured decision.
255
+ 6. **Validate** — check the schema, action type, coordinates, duration, deadline and game-profile constraints.
256
+ 7. **Execute** — run the action through the PC adapter or send it to the paired Android device.
257
+ 8. **Acknowledge** — wait for a matching action acknowledgement or report a timeout/failure.
258
+ 9. **Verify** — obtain a fresh observation and determine whether the action had the expected effect.
259
+ 10. **Re-plan** — continue, recover, pause or request user input based on the verified result.
260
+
261
+ Prefer short, verifiable actions over long blind action sequences. When observations are stale, the model is unavailable or the state is uncertain, stop issuing new inputs until the system recovers.
262
+
263
+ ## 7. DeepSeek API and model integration
264
+
265
+ The model provider is separated from game control so that the project is not locked to a single vendor.
266
+
267
+ Planned adapter responsibilities:
268
+ - Configure API base URL, model identifier and authentication key.
269
+ - Integrate DeepSeek API as the initial provider.
270
+ - Support compatible OpenAI-style API endpoints through provider adapters where their request/response capabilities match.
271
+ - Declare model capabilities such as `vision`, `reasoning`, `audio` and `structured_actions`.
272
+ - Send only the observation and context required for the current task.
273
+ - Parse model output into a strict internal action schema.
274
+ - Handle request timeouts, rate limits, connection errors and malformed responses.
275
+ - Keep provider credentials on the desktop side; never embed a long-lived API key in the Android app or frontend source.
276
+
277
+ A model response is a **proposal**, not an unrestricted command. The desktop engine must validate it before any action is executed.
278
+
279
+ ### Vision capability matters
280
+
281
+ A text-only model cannot independently interpret a raw screenshot. Screenshot-based gameplay requires a vision-capable model or a local vision pipeline that converts the image into structured state before a text model is called. The model router must check capability compatibility rather than assuming every model can process images.
282
+
283
+ ### Example configuration contract
284
+
285
+ This is an illustrative configuration shape, not a claim that the current UI or runtime already implements these exact fields:
286
+
287
+ ```yaml
288
+ gamer:
289
+ model:
290
+ provider: deepseek
291
+ base_url: ${DEEPSEEK_BASE_URL}
292
+ api_key_env: DEEPSEEK_API_KEY
293
+ model: ${DEEPSEEK_MODEL}
294
+ timeout_seconds: 60
295
+
296
+ desktop:
297
+ vision_enabled: true
298
+ max_action_duration_ms: 1500
299
+
300
+ android:
301
+ transport: adb
302
+ require_pairing: true
303
+ require_action_ack: true
304
+
305
+ safety:
306
+ max_actions_per_batch: 3
307
+ pause_on_uncertain_state: true
308
+ require_confirmation_for_sensitive_actions: true
309
+ ```
310
+
311
+ Store secrets in environment variables or a local secret manager. Never commit API keys, access tokens or device credentials.
312
+
313
+ ## 8. Local model discovery and failover
314
+
315
+ The desktop control center is intended to discover configured local model endpoints, check their health and route tasks to a compatible model.
316
+
317
+ Failover policy:
318
+
319
+ 1. Discover configured local model endpoints and declared capabilities.
320
+ 2. Run a bounded health check and a small inference probe.
321
+ 3. Select the highest-priority healthy model that supports the requested task.
322
+ 4. On timeout, connection failure, repeated server/runtime errors or invalid structured output, mark the active model degraded according to configurable thresholds.
323
+ 5. Probe the fallback with a real task-compatible inference before declaring it active.
324
+ 6. Preserve compact task context and recent verified action outcomes where possible.
325
+ 7. Re-check the preferred model and switch back only after a stable recovery window.
326
+ 8. If all compatible models fail, pause automation and show a clear error. Never claim the AI is still playing when inference has stopped.
327
+
328
+ A running process alone does not prove that a model is healthy. For screenshot understanding, the health check must verify vision capability using a representative image input.
329
+
330
+ ## 9. Android connection and data transport
331
+
332
+ The desktop and Android app require explicit, authenticated pairing.
333
+
334
+ Planned transports:
335
+ - **USB / ADB:** useful for development, debugging, screen capture and direct device control.
336
+ - **LAN Wi-Fi:** useful when the phone and computer share a trusted local network.
337
+ - **WebRTC or equivalent media transport:** suitable for low-latency continuous video/audio where available.
338
+ - **Reliable WebSocket channel:** suitable for control messages, action acknowledgements, model events and telemetry.
339
+
340
+ The runtime protocol defines versioned messages for:
341
+ - Device status and pairing
342
+ - Screen frame and observation metadata
343
+ - Optional audio/sensor observations with explicit permission
344
+ - Model/task state
345
+ - Action request and action acknowledgement
346
+ - Stop, pause, disconnect and heartbeat
347
+ - Telemetry and error events
348
+ - Companion state and optional speech
349
+
350
+ Each message should carry a protocol version, session ID, message ID and timestamp. Reject stale commands, duplicate action IDs, malformed payloads and messages from unpaired clients.
351
+
352
+ Do not expose ADB or unauthenticated control ports to the public internet.
353
+
354
+ See [Gamer-Mobile ↔ Gamer-DSH Runtime Protocol v1](docs/runtime-protocol-v1.md).
355
+
356
+ ## 10. Desktop control center and telemetry
357
+
358
+ The desktop UI is a view of actual runtime events, not the source of truth. Its intended capabilities include:
359
+
360
+ - Android device connection over USB or LAN Wi-Fi
361
+ - TCP/UDP transport telemetry: throughput, latency, packet loss and connection state
362
+ - Animated live data-flow visualization
363
+ - Local model discovery, health checks and primary/fallback routing
364
+ - Explicit model failover with recovery checks
365
+ - Game session controls and event logs
366
+ - Clear connected, connecting, disconnected, demo and stale-data states
367
+
368
+ Telemetry must come from real measurements. TCP and UDP metrics must be reported separately. Do not infer UDP packet loss from TCP metrics. If a metric is unavailable, show N/A rather than a fabricated zero. Decorative animation must not be presented as real network traffic.
369
+
370
+ **Run the desktop UI with its local pairing service (Node.js 22.13+):** do not open `desktop-ui/index.html` directly. From the repository root run `cd desktop-runtime`, `npm install`, then `npm start`; open `http://127.0.0.1:8765` on the computer. Choose the computer's LAN adapter and click **生成二维码**. The QR is generated locally and expires after five minutes. The phone must be on the same trusted LAN. Scanning opens a validation page; it does not yet complete Android pairing because the Android Companion handshake is not implemented. Never expose this HTTP pairing service to the public internet. The telemetry panel still shows “等待连接”; its animated trace is decorative until a real telemetry source is integrated.
371
+
372
+ ## 11. Companion state and voice
373
+
374
+ The Android app and desktop UI can display the same logical companion session. The desktop host is authoritative for task and game state; the phone reports execution and can play optional local TTS.
375
+
376
+ Planned states include idle/listening, thinking, exploring, moving, interacting, task progress, success, warning, model switching, paused and disconnected. State transitions must be driven by real session events, not decorative timers.
377
+
378
+ Optional voice playback should use a user-selected installed voice or a properly licensed voice pack. Speech must be interruptible and rate-limited so it does not interfere with gameplay.
379
+
380
+ The companion is a user-interface character and does not imply that the model is conscious.
381
+
382
+
383
+ ### Optional community Paimon voice pack
384
+
385
+ Gamer can optionally connect to a separately installed community TTS service so the companion can speak task updates, guide summaries, warnings and verified action results. The desktop dashboard includes a TTS endpoint health check and a short audio preview.
386
+
387
+ A community project worth evaluating is [gaaiyun/ai-paimon](https://github.com/gaaiyun/ai-paimon), which documents a local Paimon VITS server with `GET /health` and `POST /tts_to_audio` endpoints. Its repository states that its Paimon voice checkpoint is for personal, non-commercial use only. Gamer does not bundle or redistribute that checkpoint; users must obtain model files from the original project and follow its current terms. The upstream project also contains game-derived Live2D assets, which are not part of Gamer's distribution.
388
+
389
+ The integration is optional and endpoint-based. The voice service should remain on localhost or a trusted LAN, and must not be exposed publicly without authentication and transport protection. TTS is playback only; it does not change model-provider credentials or game-control permissions. See [Community TTS integration](docs/community-tts.md).
390
+
391
+ ## 12. Safety, privacy and user control
392
+
393
+ - Keep screenshots, game state and device data on the user's computer by default.
394
+ - Send only the minimum context needed to the selected model API.
395
+ - Keep model API keys on the desktop; redact secrets from logs.
396
+ - Require explicit user approval for screen capture, audio capture and accessibility/input control.
397
+ - Pair devices explicitly and authenticate both sides.
398
+ - Bind local control endpoints to loopback by default; expose LAN access only intentionally.
399
+ - Validate action type, coordinate bounds, duration, deadline and batch size.
400
+ - Provide an immediate stop/pause control.
401
+ - Stop issuing actions on disconnect, stale observations, unavailable models or uncertain state.
402
+ - Require explicit approval for purchases, premium-currency spending, save deletion or other irreversible/account-sensitive actions.
403
+ - Respect game terms, anti-cheat rules and applicable laws. Do not bypass anti-cheat, access controls or platform protections.
404
+
405
+ ## 13. Repository layout
406
+
407
+ - `desktop-ui/` — responsive desktop dashboard and real QR preview.
408
+ - `desktop-runtime/` — local HTTP server, LAN interface discovery, short-lived QR token manager and QR image generation.
409
+ - `docs/architecture.md` — runtime architecture and integration contract.
410
+ - `docs/runtime-protocol-v1.md` — Android ↔ desktop pairing, observations, actions, telemetry, model failover and companion protocol.
411
+ - Future runtime modules — Android bridge, telemetry collector, local inference adapter, model health router, game-agent coordinator and PC input adapter.
412
+
413
+ Platform-specific code should stay behind adapters. DSH orchestration, model providers and device transports should remain independently testable.
414
+
415
+ ## 14. Development roadmap
416
+
417
+ ### Phase 1 — Foundation
418
+ - Establish the DSH plugin entry point and package structure.
419
+ - Define shared types for observations, actions, results and errors.
420
+ - Add local configuration validation and secure secret handling.
421
+
422
+ ### Phase 2 — Desktop AI loop
423
+ - Implement desktop screen capture and a minimal vision pipeline.
424
+ - Integrate the DeepSeek model adapter.
425
+ - Implement structured action parsing, validation and a safe PC input adapter.
426
+ - Demonstrate observe → reason → act → verify in a controlled test game.
427
+
428
+ ### Phase 3 — Android companion
429
+ - Implement authenticated phone pairing.
430
+ - Add Android screen capture and observation transfer.
431
+ - Add touch execution and action acknowledgements.
432
+ - Demonstrate mobile gameplay with the game running on Android and the main AI processing on the computer.
433
+
434
+ ### Phase 4 — Reliability
435
+ - Add reconnect handling, timeouts, cancellation and recovery.
436
+ - Optimize image transfer, request frequency, token usage and latency.
437
+ - Add diagnostics and reproducible test cases.
438
+
439
+ ### Phase 5 — Compatibility
440
+ - Add more game input adapters and model providers.
441
+ - Improve UI recognition and game-specific state adapters.
442
+ - Publish tested releases with clear compatibility notes.
443
+
444
+ ## 15. Implementation status and honesty
445
+
446
+ The README and protocol documents define the target behavior and contracts. A feature should be called **implemented** only after its code exists, dependencies are declared and the workflow has been tested.
447
+
448
+ This repository's desktop UI remains a prototype for most gameplay and telemetry features. The standalone desktop runtime can now generate a real, five-minute LAN QR code and validate its scan landing page. This is not a completed Android pairing: Android Companion identity submission, mutual authentication, ADB control, PC input injection, OCR, model routing, live telemetry and automatic gameplay are not yet operational. Those capabilities must be delivered and verified module by module.
449
+
450
+ ## 16. Contributing
451
+
452
+ Contributions are welcome in DSH integration, desktop vision, Android communication, model adapters, action validation, telemetry, documentation and testing.
453
+
454
+ Please include:
455
+ - Operating system, device model and Android version
456
+ - DSH and runtime versions
457
+ - Reproduction steps
458
+ - Expected and actual behavior
459
+ - Relevant logs with API keys, tokens and personal data removed
460
+
461
+ ## License
462
+
463
+ The repository license is governed by the license file included in this repository. If no license file is present, do not assume that the source is licensed for redistribution or commercial use.
464
+
465
+
466
+ ## 17. Paimon as an autonomous voice companion
467
+
468
+ The Android companion is intended to feel like a persistent in-game partner, not merely a speaker for desktop notifications. This section defines the target behavior; it is not a claim that voice recognition, autonomous roaming or game automation is already implemented.
469
+
470
+ ### Connection greeting
471
+
472
+ After QR pairing has been authenticated and the session is ready, Android plays a short Paimon greeting, for example: “旅行者,连接成功啦!派蒙已经准备好,随时听候你的吩咐!” The greeting is emitted once per successful pairing/session, not on every heartbeat or reconnect loop. If TTS is unavailable, show a text fallback and do not claim audio played.
473
+
474
+ ### Voice command loop
475
+
476
+ - Android requests microphone permission explicitly and shows a visible listening indicator. Push-to-talk is the default; optional wake-word listening must be separately enabled and easy to disable.
477
+ - Speech recognition produces a transcript plus confidence/language metadata. The transcript is sent over the authenticated session to the desktop agent; model API credentials remain on desktop.
478
+ - The desktop resolves the command against the currently detected game profile, current state and permitted action set. It asks for clarification when confidence is low or the command is ambiguous.
479
+ - The agent returns a short spoken acknowledgement, executes bounded actions, then reports only outcomes verified by new observations.
480
+ - “派蒙,停止 / 暂停” is a high-priority local command. Android must stop dispatching queued actions immediately, even if the desktop or model is slow or disconnected.
481
+
482
+ Example commands include “派蒙,跟着我”、“去砍一些橡木”、“回到安全的地方” and “暂停一下”. Command vocabulary and action semantics are profile-specific; examples are not guarantees that every game supports those actions.
483
+
484
+ ### Autonomous companion behavior when no task is queued
485
+
486
+ The user may enable an explicit **陪伴探索 / 自主漫游** mode. When enabled and the agent is idle, it may:
487
+ - Make occasional in-character comments about visible, confidently recognized events.
488
+ - Use short original, non-infringing humming or songs, or audio the user has rights to use. Do not reproduce copyrighted game songs or commercial tracks without permission.
489
+ - Explore within a bounded radius, observe landmarks and learn safe routes.
490
+ - In Minecraft, gather permitted resources such as nearby wood only when the active profile confirms the target, tool, inventory capacity and environmental safety. It should avoid lava, cliffs, hostile mobs, protected builds and other players' property; do not break blocks near other players or user-designated protected areas.
491
+ - Return to a configured safe point or stop when health, hunger, durability, inventory, danger or uncertainty crosses profile thresholds.
492
+
493
+ Autonomy is opt-in, bounded and interruptible. Default behavior while idle is **wait and chat**, not uncontrolled movement. The user can set exploration radius, allowed activities, protected areas, resource limits, speech frequency and quiet hours. Purchases, premium-currency spending, irreversible account actions, PvP, griefing and interactions affecting other players require explicit user authorization and must not be initiated autonomously.
494
+
495
+ ### Automatic game recognition and profile switching
496
+
497
+ The agent should combine Android foreground package/title metadata (when the OS permits) with screen-layout fingerprints, OCR/UI signatures and scene cues. It must not rely on a single title string or assume that a visual guess is certain. On a game change:
498
+ 1. Stop or pause actions from the previous profile.
499
+ 2. Identify candidate game and platform; calculate confidence.
500
+ 3. Load the matching versioned profile only after validation.
501
+ 4. Display the detected title/profile and confidence to the user.
502
+ 5. If uncertain or unsupported, enter observe-only mode and ask the user to select/confirm a profile.
503
+
504
+ Each title needs its own tested control map and safety rules. Minecraft resource gathering cannot be reused as Genshin Impact behavior. For Genshin and other games, the agent may explore, follow, navigate or interact only where the profile has validated controls and the action is allowed. “Automatic recognition” means detecting and selecting a profile, not instant universal compatibility.
505
+
506
+ ### Suggested state machine
507
+
508
+ `disconnected → pairing → connected_greeting → idle_companion → voice_command → task_planning → executing → verifying → idle_companion`
509
+
510
+ Any state may transition to `paused`, `stopping` or `error`. A new voice command interrupts low-priority chatter; stop/pause interrupts speech and action queues. Disconnect, stale frames, low-confidence perception, model failure or an unknown game must stop new autonomous actions.
511
+
512
+ ### Acceptance tests
513
+
514
+ - A successful pairing produces one greeting; failed pairing produces none.
515
+ - The phone can receive a voice command and the desktop returns a transcript/intent acknowledgement without exposing API credentials.
516
+ - Stop/pause works locally even during network loss or a pending inference request.
517
+ - Idle autonomy is off by default and cannot start without user opt-in.
518
+ - A game switch cancels old-profile actions before loading a new profile.
519
+ - Unknown game/profile confidence causes observe-only behavior.
520
+ - Minecraft gathering respects health, danger, inventory, protected-area and action-bound checks.
521
+ - Spoken commentary is based on current observations; songs are original/licensed/public-domain only.
522
+
523
+ See [runtime protocol](runtime-protocol-v1.md) for the corresponding event contract.
524
+
525
+
526
+ ---
527
+
528
+ ## Native DSH plugin installation
529
+
530
+ The repository now includes a native DSH bundle package manifest and plugin entry point. The npm package is published separately from the GitHub source release.
531
+
532
+ **Desktop DSH installation (after the npm package is published):**
533
+ 1. Open **Plugins** in the DSH sidebar.
534
+ 2. Select **Add plugin**.
535
+ 3. Enter `@sususgh/gamer-dsh-plugin` (the npm package name, not this GitHub URL).
536
+ 4. Install and restart DSH.
537
+ 5. Open the Gamer plugin page. In a new conversation, ask the model to call `gamer_project_status` to verify that the plugin loaded.
538
+
539
+ For CLI-managed profiles, use:
540
+ ```bash
541
+ npx -y @deepseek-ai/dsh plugin --profile web add @sususgh/gamer-dsh-plugin@1.0.1
542
+ ```
543
+
544
+ See [DSH installation instructions](docs/DSH-INSTALL.zh-CN.md).
545
+
546
+ **Current release (v1.0.1):** the native DSH package provides the plugin bundle, a status tool and a bilingual configuration page (简体中文 / English) on the bundle's own page in the DSH Plugins sidebar. The page includes an Android QR-pairing status panel. The standalone desktop runtime now provides real QR generation and a scan-validation landing page. The Android APK/companion bridge, device identity approval, authenticated session handshake, live visual perception and autonomous game actions are not implemented yet; scanning the QR does not mean the phone is paired. Installing the DSH bundle does not enable game control.
@@ -0,0 +1,4 @@
1
+ # Mount Gamer as a native DSH plugin bundle.
2
+ - insert:
3
+ - id: gamer-dsh-plugin
4
+ name: '@sususgh/gamer-dsh-plugin'
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "gamer-desktop-runtime",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "description": "Local Gamer desktop UI and short-lived QR pairing server",
7
+ "scripts": {
8
+ "start": "node server.js",
9
+ "check": "node --check server.js && node --check pairing.js"
10
+ },
11
+ "dependencies": {
12
+ "qrcode": "^1.5.4"
13
+ },
14
+ "engines": {
15
+ "node": ">=22.13"
16
+ }
17
+ }
@@ -0,0 +1,75 @@
1
+ import { createHash, randomBytes, timingSafeEqual, randomUUID } from 'node:crypto';
2
+
3
+ const DEFAULT_TTL_MS = 5 * 60 * 1000;
4
+
5
+ export class PairingManager {
6
+ #active = null;
7
+
8
+ constructor({ ttlMs = DEFAULT_TTL_MS } = {}) {
9
+ if (!Number.isInteger(ttlMs) || ttlMs < 10_000 || ttlMs > 15 * 60 * 1000) {
10
+ throw new RangeError('ttlMs must be between 10 seconds and 15 minutes');
11
+ }
12
+ this.ttlMs = ttlMs;
13
+ this.instanceId = randomUUID();
14
+ }
15
+
16
+ create({ host, port, protocol = 'gamer-runtime/1' }) {
17
+ if (typeof host !== 'string' || !host.trim()) throw new TypeError('A LAN host address is required');
18
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new RangeError('Invalid port');
19
+ if (protocol !== 'gamer-runtime/1') throw new TypeError('Unsupported pairing protocol');
20
+
21
+ const token = randomBytes(32).toString('base64url');
22
+ const now = Date.now();
23
+ this.#active = {
24
+ tokenHash: createHash('sha256').update(token).digest(),
25
+ createdAt: now,
26
+ expiresAt: now + this.ttlMs,
27
+ host,
28
+ port,
29
+ protocol,
30
+ };
31
+
32
+ return {
33
+ token,
34
+ protocol,
35
+ instanceId: this.instanceId,
36
+ host,
37
+ port,
38
+ createdAt: now,
39
+ expiresAt: now + this.ttlMs,
40
+ };
41
+ }
42
+
43
+ verify(token, { consume = false } = {}) {
44
+ const current = this.#active;
45
+ if (!current || Date.now() >= current.expiresAt || typeof token !== 'string') {
46
+ if (current && Date.now() >= current.expiresAt) this.#active = null;
47
+ return false;
48
+ }
49
+
50
+ const candidate = createHash('sha256').update(token).digest();
51
+ const valid = candidate.length === current.tokenHash.length
52
+ && timingSafeEqual(candidate, current.tokenHash);
53
+
54
+ if (valid && consume) this.#active = null;
55
+ return valid;
56
+ }
57
+
58
+ status() {
59
+ if (this.#active && Date.now() >= this.#active.expiresAt) this.#active = null;
60
+ if (!this.#active) return { active: false, expiresAt: null, host: null, port: null };
61
+ return {
62
+ active: true,
63
+ createdAt: this.#active.createdAt,
64
+ expiresAt: this.#active.expiresAt,
65
+ remainingMs: Math.max(0, this.#active.expiresAt - Date.now()),
66
+ host: this.#active.host,
67
+ port: this.#active.port,
68
+ };
69
+ }
70
+
71
+ stop() {
72
+ this.#active = null;
73
+ return this.status();
74
+ }
75
+ }