aram-mayhem-dsh 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/INSTALL.zh-CN.txt +61 -54
  2. package/LICENSE +27 -27
  3. package/README.md +234 -194
  4. package/THIRD_PARTY_NOTICES.md +50 -50
  5. package/client.js +973 -829
  6. package/config/settings.json +57 -57
  7. package/cordis.patch.yml +5 -6
  8. package/data/README.md +9 -9
  9. package/docs/DETAIL.md +3 -3
  10. package/docs/DETAIL.zh.md +3 -3
  11. package/docs/preview.svg +63 -63
  12. package/icon.svg +23 -23
  13. package/index.js +544 -439
  14. package/install.ps1 +63 -63
  15. package/locale/en.json +7 -7
  16. package/locale/zh.json +7 -7
  17. package/package.json +72 -72
  18. package/requirements-core.txt +6 -6
  19. package/requirements-dsh.txt +8 -8
  20. package/scripts/desktop_overlay.py +1305 -1305
  21. package/scripts/dsh_service.py +999 -999
  22. package/src/__init__.py +3 -3
  23. package/src/app.py +462 -462
  24. package/src/core/__init__.py +1 -1
  25. package/src/core/event_bus.py +56 -56
  26. package/src/core/events.py +28 -28
  27. package/src/core/hotkeys.py +166 -166
  28. package/src/core/logging_setup.py +44 -44
  29. package/src/core/paths.py +44 -44
  30. package/src/core/settings.py +271 -271
  31. package/src/data/__init__.py +1 -1
  32. package/src/data/fetcher.py +239 -239
  33. package/src/data/matcher.py +534 -534
  34. package/src/data/models.py +287 -287
  35. package/src/data/schema.py +128 -128
  36. package/src/data/scoring.py +127 -127
  37. package/src/data/store.py +543 -543
  38. package/src/lcu/__init__.py +1 -1
  39. package/src/lcu/connector.py +316 -316
  40. package/src/lcu/listener.py +507 -507
  41. package/src/main.py +76 -76
  42. package/src/ui/__init__.py +1 -1
  43. package/src/ui/augment_panel.py +276 -276
  44. package/src/ui/build_panel.py +319 -319
  45. package/src/ui/champ_panel.py +236 -236
  46. package/src/ui/overlay_window.py +631 -631
  47. package/src/ui/theme.py +298 -298
  48. package/src/ui/widgets.py +408 -408
  49. package/src/vision/__init__.py +1 -1
  50. package/src/vision/capture.py +249 -249
  51. package/src/vision/ocr_engine.py +122 -122
  52. package/src/vision/scanner.py +272 -272
package/index.js CHANGED
@@ -1,439 +1,544 @@
1
- import { spawn } from 'node:child_process'
2
- import { existsSync } from 'node:fs'
3
- import { dirname, join } from 'node:path'
4
- import { fileURLToPath } from 'node:url'
5
-
6
- /**
7
- * Host half of the ARAM: Mayhem DSH plugin.
8
- *
9
- * It owns the local Python service and exposes its operations as agent tools.
10
- * The client page (client.js) talks to the same service over loopback.
11
- */
12
- export const name = 'aram-mayhem'
13
- export const inject = ['tools', 'systemPrompt', 'webServer']
14
-
15
- const DEFAULTS = {
16
- pythonPath: 'python',
17
- host: '127.0.0.1',
18
- port: 8123,
19
- overlay: true,
20
- }
21
-
22
- const here = dirname(fileURLToPath(import.meta.url))
23
- const serviceScript = join(here, 'scripts', 'dsh_service.py')
24
-
25
- /** @param {unknown} value */
26
- const asText = value => [{ type: 'text', text: String(value) }]
27
-
28
- /** @param {Record<string, unknown>} properties @param {string[]} required */
29
- const objectSchema = (properties, required = []) => ({
30
- type: 'object',
31
- properties,
32
- ...(required.length ? { required } : {}),
33
- })
34
-
35
- function fmtPct(value) {
36
- return typeof value === 'number' ? `${(value * 100).toFixed(1)}%` : '--'
37
- }
38
-
39
- function fmtEval(item) {
40
- const a = item.augment || {}
41
- const tags = (item.tags || []).filter(Boolean)
42
- return `${a.name}(${a.rarity_label || a.rarity || '?'},${item.tier})`
43
- + ` ${Number(item.score || 0).toFixed(0)} 分`
44
- + `|胜率 ${item.win_rate_label || fmtPct(item.adjusted_win_rate)}`
45
- + `|差值 ${item.delta_label || '0.0'}pp`
46
- + `|选取 ${item.pick_rate_label || '--'}`
47
- + `|样本 ${Number(item.games || 0).toLocaleString('en-US')}`
48
- + (tags.length ? `|${tags.join(' / ')}` : '')
49
- }
50
-
51
- function fmtChampion(summary) {
52
- const c = summary.champion
53
- const lines = [
54
- `${c.name}(${c.title})${c.tier}|胜率 ${c.win_rate_label}|排名 ${c.rank}|选取 ${c.pick_rate_label}|样本 ${Number(c.games || 0).toLocaleString('en-US')}`,
55
- `推荐取向:${summary.style_label || '均衡强化'}`,
56
- ]
57
- if (summary.top_augments?.length) {
58
- lines.push('', '推荐海克斯:')
59
- summary.top_augments.forEach((item, index) => lines.push(`${index + 1}. ${fmtEval(item)}`))
60
- }
61
- if (summary.build) {
62
- lines.push('', buildBrief(summary.build))
63
- if (summary.build.notes) lines.push(summary.build.notes)
64
- }
65
- return lines.join('\n')
66
- }
67
-
68
- function buildBrief(build) {
69
- const names = items => (items || []).map(item => item.name).join(' + ') || '暂无'
70
- const cores = (build.core_builds || []).map((core, index) =>
71
- `${index + 1}) ${(core.items || []).map(item => item.name).join(' → ')}(${core.win_rate_label},${Number(core.games || 0).toLocaleString('en-US')} 局)`,
72
- )
73
- const destiny = build.destiny
74
- ? `${(build.destiny.items || []).map(item => item.name).join(' / ')}(${build.destiny.win_rate_label},${Number(build.destiny.games || 0).toLocaleString('en-US')} 局)`
75
- : '暂无达标样本'
76
- return [
77
- `出门装:${names(build.starting_items)}`,
78
- `核心:${cores.join(';') || '暂无'}`,
79
- `鞋子:${names(build.boots)}`,
80
- `召唤师技能:${(build.spells || []).join(' + ') || '暂无'}`,
81
- `技能加点:${(build.skill_priority || []).join(' → ') || '暂无'}(${build.skill_note || '通用模板'})`,
82
- `命运之武器:${destiny}`,
83
- ].join('\n')
84
- }
85
-
86
- /**
87
- * @param {import('@deepseek-ai/cordis').Context} ctx
88
- * @param {Partial<typeof DEFAULTS>} [config]
89
- */
90
- export function apply(ctx, config = {}) {
91
- const cfg = { ...DEFAULTS, ...config }
92
- const base = `http://${cfg.host}:${cfg.port}`
93
- let child = null
94
- let starting = null
95
- let metaCache = null
96
- let metaAt = 0
97
-
98
- async function alive() {
99
- try {
100
- const response = await fetch(`${base}/health`, { signal: AbortSignal.timeout(1200) })
101
- if (!response.ok) return false
102
- const data = await response.json().catch(() => null)
103
- return data?.service === 'aram-mayhem-dsh'
104
- } catch {
105
- return false
106
- }
107
- }
108
-
109
- async function ensure() {
110
- if (await alive()) return
111
- if (starting) return starting
112
- starting = (async () => {
113
- if (!existsSync(serviceScript)) throw new Error(`本地服务脚本不存在:${serviceScript}`)
114
- if (!child) {
115
- child = spawn(cfg.pythonPath, [serviceScript, '--port', String(cfg.port), '--root', here], {
116
- cwd: here,
117
- detached: true,
118
- stdio: 'ignore',
119
- windowsHide: true,
120
- })
121
- child.on('error', () => { child = null })
122
- child.on('exit', () => { child = null })
123
- child.unref()
124
- }
125
- const deadline = Date.now() + 60_000
126
- while (Date.now() < deadline) {
127
- await new Promise(resolve => setTimeout(resolve, 700))
128
- if (await alive()) return
129
- }
130
- throw new Error(
131
- `海斗助手服务启动超时(${base})。请确认 ${cfg.pythonPath} 可用并安装依赖:`
132
- + `python -m pip install -r "${join(here, 'requirements-dsh.txt')}"`,
133
- )
134
- })()
135
- try {
136
- return await starting
137
- } finally {
138
- starting = null
139
- }
140
- }
141
-
142
- async function request(path, options = {}) {
143
- await ensure()
144
- const response = await fetch(`${base}${path}`, {
145
- ...options,
146
- signal: options.signal || AbortSignal.timeout(180_000),
147
- })
148
- const data = await response.json().catch(() => ({}))
149
- if (!response.ok) throw new Error(data.error || `海斗助手服务返回 HTTP ${response.status}`)
150
- return data
151
- }
152
-
153
- /**
154
- * Relay page requests through DSH's own origin. Electron loads the SPA as
155
- * app://app and file:// pages have an opaque origin, so a direct fetch to
156
- * 127.0.0.1 can be rejected by CORS/PNA even when the service is healthy.
157
- * The page uses /aram-api/*; DSH's web server forwards it to this handler.
158
- */
159
- async function proxy(req, res) {
160
- try {
161
- await ensure()
162
- const chunks = []
163
- for await (const chunk of req) chunks.push(chunk)
164
- const body = chunks.length ? Buffer.concat(chunks) : undefined
165
- const incoming = (req.url || '/').replace(/^\/aram-api/, '') || '/'
166
- const headers = { Accept: 'application/json' }
167
- if (req.headers['content-type']) headers['Content-Type'] = req.headers['content-type']
168
- const upstream = await fetch(`${base}${incoming}`, {
169
- method: req.method || 'GET',
170
- headers,
171
- body: req.method && !['GET', 'HEAD'].includes(req.method) ? body : undefined,
172
- signal: AbortSignal.timeout(180_000),
173
- })
174
- const payload = Buffer.from(await upstream.arrayBuffer())
175
- res.statusCode = upstream.status
176
- res.setHeader('Content-Type', upstream.headers.get('content-type') || 'application/json; charset=utf-8')
177
- res.setHeader('Cache-Control', 'no-store')
178
- res.end(payload)
179
- } catch (error) {
180
- res.statusCode = 502
181
- res.setHeader('Content-Type', 'application/json; charset=utf-8')
182
- res.end(JSON.stringify({
183
- ok: false,
184
- error: `海斗助手本地服务不可达:${error?.message || error}`,
185
- }))
186
- }
187
- }
188
-
189
- const get = path => request(path)
190
- const post = (path, body) => request(path, {
191
- method: 'POST',
192
- headers: { 'Content-Type': 'application/json; charset=utf-8' },
193
- body: JSON.stringify(body || {}),
194
- })
195
-
196
- async function dataNote() {
197
- try {
198
- if (!metaCache || Date.now() - metaAt > 60_000) {
199
- metaCache = await get('/meta')
200
- metaAt = Date.now()
201
- }
202
- return `数据 ${metaCache.patch || '--'} · ${metaCache.source || '--'} · ${metaCache.license || '--'}`
203
- + ` · 更新 ${metaCache.updated_label || '--'};部分对局样本,相关不等于因果。`
204
- } catch {
205
- return '数据为部分对局样本;相关不等于因果。'
206
- }
207
- }
208
-
209
- const definitions = {}
210
-
211
- definitions.aram_status = {
212
- name: 'aram_status',
213
- description: 'Report the local ARAM: Mayhem data snapshot and current League client state: patch, sample size, '
214
- + 'data source, LCU connection, queue and current champion. Use it before making version-specific claims.',
215
- parameters: objectSchema({}, []),
216
- output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
217
- execute: async () => {
218
- const health = await get('/health')
219
- const snapshot = await get('/snapshot')
220
- const meta = snapshot.meta || {}
221
- const lcu = snapshot.lcu || {}
222
- const state = snapshot.champ_select
223
- const lines = [
224
- `数据:${meta.label || meta.patch || '--'}|来源 ${meta.source || '--'}|协议 ${meta.license || '--'}`,
225
- `样本:${Number(meta.matches || 0).toLocaleString('en-US')} 场|更新 ${meta.updated_label || '--'}|英雄 ${health.counts?.champions ?? '?'}|海克斯 ${health.counts?.augments ?? '?'}`,
226
- `LCU:${lcu.connected ? `已连接(${lcu.phase})` : '未连接'}${lcu.queue_name ? `|队列 ${lcu.queue_id} ${lcu.queue_name}` : ''}${lcu.error ? `|${lcu.error}` : ''}`,
227
- ]
228
- if (state?.my_champion_id) {
229
- lines.push(`我的英雄 ID:${state.my_champion_id}${snapshot.my_champion ? `(${snapshot.my_champion.champion.name})` : ''}`)
230
- } else if (snapshot.my_champion?.champion) {
231
- lines.push(`当前英雄:${snapshot.my_champion.champion.name}(${snapshot.my_champion.champion.tier},${snapshot.my_champion.champion.win_rate_label})`)
232
- }
233
- lines.push('', '统计为部分国服对局样本;海克斯持有与获胜是相关关系,不是因果。')
234
- return lines.join('\n')
235
- },
236
- }
237
-
238
- definitions.aram_champion = {
239
- name: 'aram_champion',
240
- description: 'Look up one champion\'s ARAM: Mayhem win rate, tier, rank, recommended augments and build. '
241
- + 'Use champion names, aliases or numeric Riot champion IDs.',
242
- parameters: objectSchema({
243
- champion: { type: 'string', description: 'Champion name, alias or numeric ID, e.g. 亚索, Yasuo, 157.' },
244
- top: { type: 'integer', description: 'How many augment recommendations to include, 1-8. Default 5.' },
245
- }, ['champion']),
246
- output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
247
- execute: async args => {
248
- const top = Math.min(Math.max(Math.round(Number(args?.top ?? 5)) || 5, 1), 8)
249
- const data = await get(`/champion?champion=${encodeURIComponent(String(args?.champion ?? ''))}&top=${top}`)
250
- return `${fmtChampion(data.summary)}\n\n${await dataNote()}`
251
- },
252
- }
253
-
254
- definitions.aram_build = {
255
- name: 'aram_build',
256
- description: 'Get the ARAM: Mayhem starting items, core builds, boots, summoner spells, skill order and '
257
- + 'Weapon of Destiny item reference for one champion.',
258
- parameters: objectSchema({
259
- champion: { type: 'string', description: 'Champion name, alias or numeric ID.' },
260
- }, ['champion']),
261
- output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
262
- execute: async args => {
263
- const data = await get(`/build?champion=${encodeURIComponent(String(args?.champion ?? ''))}`)
264
- return `${data.champion.name}(${data.champion.title})${data.champion.tier}|胜率 ${data.champion.win_rate_label}\n\n`
265
- + (data.build ? buildBrief(data.build) : '暂无出装数据。')
266
- + (data.build?.notes ? `\n\n${data.build.notes}` : '')
267
- + `\n\n${await dataNote()}`
268
- },
269
- }
270
-
271
- definitions.aram_augment_rank = {
272
- name: 'aram_augment_rank',
273
- description: 'Rank augment choices for one champion. Omit augments to get the champion\'s top recommendations; '
274
- + 'pass a comma-separated list of names or IDs to compare specific cards.',
275
- parameters: objectSchema({
276
- champion: { type: 'string', description: 'Champion name, alias or numeric ID.' },
277
- augments: { type: 'string', description: 'Optional comma-separated augment names or IDs, e.g. 命运之武器,尤里卡.' },
278
- top: { type: 'integer', description: 'Maximum results, 1-10. Default 5.' },
279
- }, ['champion']),
280
- output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
281
- execute: async args => {
282
- const top = Math.min(Math.max(Math.round(Number(args?.top ?? 5)) || 5, 1), 10)
283
- const q = new URLSearchParams({
284
- champion: String(args?.champion ?? ''),
285
- augments: String(args?.augments ?? ''),
286
- top: String(top),
287
- })
288
- const data = await get(`/augments?${q}`)
289
- if (!data.evaluations?.length) return '没有找到对应的海克斯数据。'
290
- return `${data.evaluations.map((item, index) => `${index + 1}. ${fmtEval(item)}`).join('\n')}\n\n${await dataNote()}`
291
- },
292
- }
293
-
294
- definitions.aram_lcu = {
295
- name: 'aram_lcu',
296
- description: 'Read the local League client state without automating anything: game phase, queue, my champion, '
297
- + 'and the ARAM bench. Returns a clear disconnected state when the client or game is unavailable.',
298
- parameters: objectSchema({}, []),
299
- output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
300
- execute: async () => {
301
- const snapshot = await get('/snapshot')
302
- const lcu = snapshot.lcu || {}
303
- const state = snapshot.champ_select
304
- const lines = [
305
- `LCU:${lcu.connected ? '已连接' : '未连接'}|阶段 ${lcu.phase || '--'}${lcu.queue_name ? `|队列 ${lcu.queue_id} ${lcu.queue_name}` : ''}`,
306
- ]
307
- if (lcu.error) lines.push(`说明:${lcu.error}`)
308
- if (state) {
309
- lines.push(`我的英雄:${snapshot.my_champion?.champion?.name || state.my_champion_id || '未知'}`)
310
- const bench = snapshot.bench || []
311
- if (bench.length) {
312
- lines.push('备战席:' + bench.map(item => {
313
- const c = item.champion
314
- return `${c.name} ${c.tier} ${c.win_rate_label}`
315
- }).join('|'))
316
- }
317
- } else if (snapshot.my_champion?.champion) {
318
- lines.push(`当前英雄:${snapshot.my_champion.champion.name}(${snapshot.my_champion.champion.tier},${snapshot.my_champion.champion.win_rate_label})`)
319
- }
320
- return lines.join('\n')
321
- },
322
- }
323
-
324
- definitions.aram_scan = {
325
- name: 'aram_scan',
326
- description: 'Run the local screen OCR scan for the in-game augment card selection. It reads the game client '
327
- + 'area only, maps card titles to augments, and ranks them for the current or specified champion. '
328
- + 'Use only when the user is in an ARAM: Mayhem game and asks about the current cards.',
329
- parameters: objectSchema({
330
- champion: { type: 'string', description: 'Optional champion name/ID; omit to use the champion detected in champ select.' },
331
- }, []),
332
- output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
333
- execute: async args => {
334
- const data = await post('/scan', { champion: args?.champion || undefined })
335
- if (!data.ok) return `识别失败:${data.error || '未知原因'}`
336
- if (!data.matches?.length) return '没有识别到海克斯卡片。请确认游戏使用无边框/窗口化,并调整识别区域。'
337
- const lines = [`识别到 ${data.matches.length} 张卡片:${data.matches.map(item => `${item.name}(${Math.round(item.confidence * 100)}%)`).join(' / ')}`]
338
- if (data.champion) lines.push(`当前英雄:${data.champion.name}`)
339
- if (data.evaluations?.length) {
340
- lines.push('', '按当前英雄推荐:')
341
- data.evaluations.forEach((item, index) => lines.push(`${index + 1}. ${fmtEval(item)}`))
342
- }
343
- lines.push('', await dataNote())
344
- return lines.join('\n')
345
- },
346
- }
347
-
348
- definitions.aram_refresh = {
349
- name: 'aram_refresh',
350
- description: 'Download a new portable ARAM: Mayhem dataset from a URL and atomically replace the local cache. '
351
- + 'Only use when the user explicitly asks to refresh statistics or supplies a licensed data URL.',
352
- parameters: objectSchema({
353
- url: { type: 'string', description: 'Optional dataset JSON URL. Omit to use the configured stats_url.' },
354
- }, []),
355
- output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
356
- execute: async args => {
357
- const data = await post('/refresh', { url: args?.url || '' })
358
- const meta = data.meta || {}
359
- return `数据已更新:${meta.label || meta.patch || '--'}|来源 ${meta.source || '--'}|`
360
- + `英雄 ${data.meta?.counts?.champions ?? '?'}|海克斯 ${data.meta?.counts?.augments ?? '?'}\n`
361
- + `${meta.license || '--'};统计为部分对局样本。`
362
- },
363
- }
364
-
365
- definitions.aram_overlay = {
366
- name: 'aram_overlay',
367
- description: 'Open, close or inspect the always-on-top desktop icon for the ARAM: Mayhem assistant. '
368
- + 'The icon expands into champion, recommended augment and build views without opening the DSH page.',
369
- parameters: objectSchema({
370
- action: {
371
- type: 'string',
372
- enum: ['open', 'close', 'status'],
373
- description: 'open shows the desktop icon; close exits it; status only reports whether it is running.',
374
- },
375
- }, []),
376
- output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
377
- execute: async args => {
378
- const action = String(args?.action || 'open')
379
- if (action === 'status') {
380
- const data = await get('/overlay/status')
381
- return data.running
382
- ? `桌面图标正在运行(PID ${data.pid})。`
383
- : '桌面图标当前未运行。'
384
- }
385
- if (action === 'close') {
386
- const data = await post('/overlay/stop', { persist: true })
387
- return data.running ? '关闭请求已发送,但进程仍在运行。' : '桌面图标已关闭;自动启动开关已关闭。'
388
- }
389
- const data = await post('/overlay/start', { persist: true })
390
- return data.running
391
- ? `桌面图标已打开(PID ${data.pid})。点击图标展开英雄/推荐海克斯/出装。`
392
- : `桌面图标未启动:${data.note || '未知原因'}`
393
- },
394
- }
395
-
396
- for (const definition of Object.values(definitions)) ctx.tools.register(definition)
397
-
398
- ctx.effect(
399
- () => ctx.webServer.register({
400
- kind: 'prefix',
401
- path: '/aram-api',
402
- handler: proxy,
403
- }),
404
- 'aram-mayhem: local service proxy',
405
- )
406
-
407
- ctx.systemPrompt.section({
408
- name: 'aram-mayhem',
409
- order: 210,
410
- text: 'When the user asks about League of Legends ARAM: Mayhem (海克斯大乱斗) champions, augment choices, '
411
- + 'win rates, builds or the current client state, use the aram_status / aram_champion / aram_augment_rank / '
412
- + 'aram_build / aram_lcu tools instead of guessing. Use aram_scan only when a game is running and the user '
413
- + 'asks about the cards currently on screen. State the patch and that the data is a partial sample; '
414
- + 'when giving statistics, mention the source and its CC BY-NC 4.0 non-commercial license. '
415
- + 'Never present correlation as causation. The plugin is read-only and must not automate picks or gameplay.',
416
- })
417
-
418
- // Start the local service and the screen-top icon in the background.
419
- void ensure()
420
- .then(() => {
421
- if (cfg.overlay !== false) return post('/overlay/start', {})
422
- return null
423
- })
424
- .catch(error => {
425
- console.warn('[aram-mayhem] local service or overlay start failed:', error?.message || error)
426
- })
427
-
428
- ctx.effect(() => () => {
429
- // The overlay is independent of this Host process; close it when the
430
- // plugin is disabled/unloaded, then release the managed service child.
431
- try {
432
- void fetch(`${base}/overlay/stop`, { method: 'POST', signal: AbortSignal.timeout(1500) }).catch(() => {})
433
- } catch { /* ignore */ }
434
- if (child) {
435
- try { child.kill() } catch { /* already gone */ }
436
- child = null
437
- }
438
- })
439
- }
1
+ import { spawn } from 'node:child_process'
2
+ import { existsSync } from 'node:fs'
3
+ import { dirname, join } from 'node:path'
4
+ import { fileURLToPath } from 'node:url'
5
+
6
+ /**
7
+ * Host half of the ARAM: Mayhem DSH plugin.
8
+ *
9
+ * It owns the local Python service and exposes its operations as agent tools.
10
+ * The client page (client.js) talks to the same service over loopback.
11
+ */
12
+ export const name = 'aram-mayhem'
13
+ export const inject = ['tools', 'systemPrompt', 'webServer']
14
+
15
+ const DEFAULTS = {
16
+ pythonPath: 'python',
17
+ host: '127.0.0.1',
18
+ port: 8123,
19
+ }
20
+
21
+ const here = dirname(fileURLToPath(import.meta.url))
22
+ const serviceScript = join(here, 'scripts', 'dsh_service.py')
23
+
24
+ /** @param {unknown} value */
25
+ const asText = value => [{ type: 'text', text: String(value) }]
26
+
27
+ /** @param {Record<string, unknown>} properties @param {string[]} required */
28
+ const objectSchema = (properties, required = []) => ({
29
+ type: 'object',
30
+ properties,
31
+ ...(required.length ? { required } : {}),
32
+ })
33
+
34
+ function fmtPct(value) {
35
+ return typeof value === 'number' ? `${(value * 100).toFixed(1)}%` : '--'
36
+ }
37
+
38
+ function fmtEval(item) {
39
+ const a = item.augment || {}
40
+ const tags = (item.tags || []).filter(Boolean)
41
+ return `${a.name}(${a.rarity_label || a.rarity || '?'},${item.tier})`
42
+ + ` ${Number(item.score || 0).toFixed(0)} 分`
43
+ + `|胜率 ${item.win_rate_label || fmtPct(item.adjusted_win_rate)}`
44
+ + `|差值 ${item.delta_label || '0.0'}pp`
45
+ + `|选取 ${item.pick_rate_label || '--'}`
46
+ + `|样本 ${Number(item.games || 0).toLocaleString('en-US')}`
47
+ + (tags.length ? `|${tags.join(' / ')}` : '')
48
+ }
49
+
50
+ function fmtChampion(summary) {
51
+ const c = summary.champion
52
+ const lines = [
53
+ `${c.name}(${c.title})${c.tier}|胜率 ${c.win_rate_label}|排名 ${c.rank}|选取 ${c.pick_rate_label}|样本 ${Number(c.games || 0).toLocaleString('en-US')}`,
54
+ `推荐取向:${summary.style_label || '均衡强化'}`,
55
+ ]
56
+ if (summary.top_augments?.length) {
57
+ lines.push('', '推荐海克斯:')
58
+ summary.top_augments.forEach((item, index) => lines.push(`${index + 1}. ${fmtEval(item)}`))
59
+ }
60
+ if (summary.build) {
61
+ lines.push('', buildBrief(summary.build))
62
+ if (summary.build.notes) lines.push(summary.build.notes)
63
+ }
64
+ return lines.join('\n')
65
+ }
66
+
67
+ function buildBrief(build) {
68
+ const names = items => (items || []).map(item => item.name).join(' + ') || '暂无'
69
+ const cores = (build.core_builds || []).map((core, index) =>
70
+ `${index + 1}) ${(core.items || []).map(item => item.name).join(' → ')}(${core.win_rate_label},${Number(core.games || 0).toLocaleString('en-US')} 局)`,
71
+ )
72
+ const destiny = build.destiny
73
+ ? `${(build.destiny.items || []).map(item => item.name).join(' / ')}(${build.destiny.win_rate_label},${Number(build.destiny.games || 0).toLocaleString('en-US')} 局)`
74
+ : '暂无达标样本'
75
+ return [
76
+ `出门装:${names(build.starting_items)}`,
77
+ `核心:${cores.join(';') || '暂无'}`,
78
+ `鞋子:${names(build.boots)}`,
79
+ `召唤师技能:${(build.spells || []).join(' + ') || '暂无'}`,
80
+ `技能加点:${(build.skill_priority || []).join(' → ') || '暂无'}(${build.skill_note || '通用模板'})`,
81
+ `命运之武器:${destiny}`,
82
+ ].join('\n')
83
+ }
84
+
85
+ /**
86
+ * @param {import('@deepseek-ai/cordis').Context} ctx
87
+ * @param {Partial<typeof DEFAULTS>} [config]
88
+ */
89
+ export function apply(ctx, config = {}) {
90
+ const cfg = { ...DEFAULTS, ...config }
91
+ const base = `http://${cfg.host}:${cfg.port}`
92
+ let child = null
93
+ let starting = null
94
+ let metaCache = null
95
+ let metaAt = 0
96
+
97
+ async function alive() {
98
+ try {
99
+ const response = await fetch(`${base}/health`, { signal: AbortSignal.timeout(1200) })
100
+ if (!response.ok) return false
101
+ const data = await response.json().catch(() => null)
102
+ return data?.service === 'aram-mayhem-dsh'
103
+ } catch {
104
+ return false
105
+ }
106
+ }
107
+
108
+ async function serviceInfo() {
109
+ try {
110
+ const response = await fetch(`${base}/health`, { signal: AbortSignal.timeout(1200) })
111
+ if (!response.ok) return { ok: true, running: false, starting: !!starting }
112
+ const data = await response.json().catch(() => null)
113
+ if (data?.service !== 'aram-mayhem-dsh') return { ok: true, running: false, starting: !!starting }
114
+ return { ok: true, running: true, pid: data.pid, version: data.version, starting: false }
115
+ } catch {
116
+ return { ok: true, running: false, starting: !!starting }
117
+ }
118
+ }
119
+
120
+ async function startService() {
121
+ const current = await serviceInfo()
122
+ if (current.running) return current
123
+ if (starting) {
124
+ try { await starting } catch { /* propagate below via status */ }
125
+ return serviceInfo()
126
+ }
127
+ starting = (async () => {
128
+ if (!existsSync(serviceScript)) throw new Error(`本地服务脚本不存在:${serviceScript}`)
129
+ if (!child) {
130
+ child = spawn(cfg.pythonPath, [serviceScript, '--port', String(cfg.port), '--root', here], {
131
+ cwd: here,
132
+ detached: true,
133
+ stdio: 'ignore',
134
+ windowsHide: true,
135
+ })
136
+ child.on('error', () => { child = null })
137
+ child.on('exit', () => { child = null })
138
+ child.unref()
139
+ }
140
+ const deadline = Date.now() + 60_000
141
+ while (Date.now() < deadline) {
142
+ await new Promise(resolve => setTimeout(resolve, 700))
143
+ if (await alive()) return
144
+ }
145
+ throw new Error(
146
+ `海斗助手服务启动超时(${base})。请确认 ${cfg.pythonPath} 可用并安装依赖:`
147
+ + `python -m pip install -r "${join(here, 'requirements-dsh.txt')}"`,
148
+ )
149
+ })()
150
+ try {
151
+ await starting
152
+ } finally {
153
+ starting = null
154
+ }
155
+ return serviceInfo()
156
+ }
157
+
158
+ async function stopService() {
159
+ if (starting) {
160
+ try { await starting } catch { /* start failed */ }
161
+ }
162
+ // The icon is a separate process; close it before stopping its API.
163
+ try {
164
+ await fetch(`${base}/overlay/stop`, {
165
+ method: 'POST',
166
+ headers: { 'Content-Type': 'application/json' },
167
+ body: '{}',
168
+ signal: AbortSignal.timeout(1500),
169
+ })
170
+ } catch { /* service or icon not running */ }
171
+ const current = await serviceInfo()
172
+ if (!current.running) {
173
+ child = null
174
+ return current
175
+ }
176
+ const pid = child?.pid || current.pid
177
+ if (pid) {
178
+ try { process.kill(pid) } catch { /* already gone */ }
179
+ }
180
+ const deadline = Date.now() + 5000
181
+ while (Date.now() < deadline) {
182
+ await new Promise(resolve => setTimeout(resolve, 250))
183
+ if (!(await alive())) break
184
+ }
185
+ child = null
186
+ return serviceInfo()
187
+ }
188
+
189
+ async function request(path, options = {}) {
190
+ if (!(await alive())) {
191
+ throw new Error('海斗助手服务未启动。请打开「海斗助手」页面,点击「服务 开」启动,或调用 aram_service start。')
192
+ }
193
+ const response = await fetch(`${base}${path}`, {
194
+ ...options,
195
+ signal: options.signal || AbortSignal.timeout(180_000),
196
+ })
197
+ const data = await response.json().catch(() => ({}))
198
+ if (!response.ok) throw new Error(data.error || `海斗助手服务返回 HTTP ${response.status}`)
199
+ return data
200
+ }
201
+
202
+ /**
203
+ * Relay page requests through DSH's own origin. Electron loads the SPA as
204
+ * app://app and file:// pages have an opaque origin, so a direct fetch to
205
+ * 127.0.0.1 can be rejected by CORS/PNA even when the service is healthy.
206
+ * The page uses /aram-api/*; DSH's web server forwards it to this handler.
207
+ */
208
+ async function proxy(req, res) {
209
+ try {
210
+ if (!(await alive())) {
211
+ res.statusCode = 503
212
+ res.setHeader('Content-Type', 'application/json; charset=utf-8')
213
+ res.setHeader('Cache-Control', 'no-store')
214
+ res.end(JSON.stringify({
215
+ ok: false,
216
+ error: '海斗助手服务未启动。请打开插件页面,点击「服务 开」。',
217
+ }))
218
+ return
219
+ }
220
+ const chunks = []
221
+ for await (const chunk of req) chunks.push(chunk)
222
+ const body = chunks.length ? Buffer.concat(chunks) : undefined
223
+ const incoming = (req.url || '/').replace(/^\/aram-api/, '') || '/'
224
+ const headers = { Accept: 'application/json' }
225
+ if (req.headers['content-type']) headers['Content-Type'] = req.headers['content-type']
226
+ const upstream = await fetch(`${base}${incoming}`, {
227
+ method: req.method || 'GET',
228
+ headers,
229
+ body: req.method && !['GET', 'HEAD'].includes(req.method) ? body : undefined,
230
+ signal: AbortSignal.timeout(180_000),
231
+ })
232
+ const payload = Buffer.from(await upstream.arrayBuffer())
233
+ res.statusCode = upstream.status
234
+ res.setHeader('Content-Type', upstream.headers.get('content-type') || 'application/json; charset=utf-8')
235
+ res.setHeader('Cache-Control', 'no-store')
236
+ res.end(payload)
237
+ } catch (error) {
238
+ res.statusCode = 502
239
+ res.setHeader('Content-Type', 'application/json; charset=utf-8')
240
+ res.end(JSON.stringify({
241
+ ok: false,
242
+ error: `海斗助手本地服务不可达:${error?.message || error}`,
243
+ }))
244
+ }
245
+ }
246
+
247
+ /** Start/stop/status control plane for the Python service (no auto-start). */
248
+ async function control(req, res) {
249
+ const path = (req.url || '/').replace(/^\/aram-control/, '') || '/status'
250
+ const send = (status, payload) => {
251
+ res.statusCode = status
252
+ res.setHeader('Content-Type', 'application/json; charset=utf-8')
253
+ res.setHeader('Cache-Control', 'no-store')
254
+ res.end(JSON.stringify(payload))
255
+ }
256
+ try {
257
+ if (req.method === 'GET' && path === '/status') {
258
+ return send(200, await serviceInfo())
259
+ }
260
+ if (req.method === 'POST' && path === '/start') {
261
+ await startService()
262
+ return send(200, await serviceInfo())
263
+ }
264
+ if (req.method === 'POST' && path === '/stop') {
265
+ await stopService()
266
+ return send(200, await serviceInfo())
267
+ }
268
+ return send(404, { ok: false, error: 'not found' })
269
+ } catch (error) {
270
+ return send(500, { ok: false, running: false, error: String(error?.message || error) })
271
+ }
272
+ }
273
+
274
+ const get = path => request(path)
275
+ const post = (path, body) => request(path, {
276
+ method: 'POST',
277
+ headers: { 'Content-Type': 'application/json; charset=utf-8' },
278
+ body: JSON.stringify(body || {}),
279
+ })
280
+
281
+ async function dataNote() {
282
+ try {
283
+ if (!metaCache || Date.now() - metaAt > 60_000) {
284
+ metaCache = await get('/meta')
285
+ metaAt = Date.now()
286
+ }
287
+ return `数据 ${metaCache.patch || '--'} · ${metaCache.source || '--'} · ${metaCache.license || '--'}`
288
+ + ` · 更新 ${metaCache.updated_label || '--'};部分对局样本,相关不等于因果。`
289
+ } catch {
290
+ return '数据为部分对局样本;相关不等于因果。'
291
+ }
292
+ }
293
+
294
+ const definitions = {}
295
+
296
+ definitions.aram_status = {
297
+ name: 'aram_status',
298
+ description: 'Report the local ARAM: Mayhem data snapshot and current League client state: patch, sample size, '
299
+ + 'data source, LCU connection, queue and current champion. Use it before making version-specific claims.',
300
+ parameters: objectSchema({}, []),
301
+ output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
302
+ execute: async () => {
303
+ const health = await get('/health')
304
+ const snapshot = await get('/snapshot')
305
+ const meta = snapshot.meta || {}
306
+ const lcu = snapshot.lcu || {}
307
+ const state = snapshot.champ_select
308
+ const lines = [
309
+ `数据:${meta.label || meta.patch || '--'}|来源 ${meta.source || '--'}|协议 ${meta.license || '--'}`,
310
+ `样本:${Number(meta.matches || 0).toLocaleString('en-US')} 场|更新 ${meta.updated_label || '--'}|英雄 ${health.counts?.champions ?? '?'}|海克斯 ${health.counts?.augments ?? '?'}`,
311
+ `LCU:${lcu.connected ? `已连接(${lcu.phase})` : '未连接'}${lcu.queue_name ? `|队列 ${lcu.queue_id} ${lcu.queue_name}` : ''}${lcu.error ? `|${lcu.error}` : ''}`,
312
+ ]
313
+ if (state?.my_champion_id) {
314
+ lines.push(`我的英雄 ID:${state.my_champion_id}${snapshot.my_champion ? `(${snapshot.my_champion.champion.name})` : ''}`)
315
+ } else if (snapshot.my_champion?.champion) {
316
+ lines.push(`当前英雄:${snapshot.my_champion.champion.name}(${snapshot.my_champion.champion.tier},${snapshot.my_champion.champion.win_rate_label})`)
317
+ }
318
+ lines.push('', '统计为部分国服对局样本;海克斯持有与获胜是相关关系,不是因果。')
319
+ return lines.join('\n')
320
+ },
321
+ }
322
+
323
+ definitions.aram_champion = {
324
+ name: 'aram_champion',
325
+ description: 'Look up one champion\'s ARAM: Mayhem win rate, tier, rank, recommended augments and build. '
326
+ + 'Use champion names, aliases or numeric Riot champion IDs.',
327
+ parameters: objectSchema({
328
+ champion: { type: 'string', description: 'Champion name, alias or numeric ID, e.g. 亚索, Yasuo, 157.' },
329
+ top: { type: 'integer', description: 'How many augment recommendations to include, 1-8. Default 5.' },
330
+ }, ['champion']),
331
+ output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
332
+ execute: async args => {
333
+ const top = Math.min(Math.max(Math.round(Number(args?.top ?? 5)) || 5, 1), 8)
334
+ const data = await get(`/champion?champion=${encodeURIComponent(String(args?.champion ?? ''))}&top=${top}`)
335
+ return `${fmtChampion(data.summary)}\n\n${await dataNote()}`
336
+ },
337
+ }
338
+
339
+ definitions.aram_build = {
340
+ name: 'aram_build',
341
+ description: 'Get the ARAM: Mayhem starting items, core builds, boots, summoner spells, skill order and '
342
+ + 'Weapon of Destiny item reference for one champion.',
343
+ parameters: objectSchema({
344
+ champion: { type: 'string', description: 'Champion name, alias or numeric ID.' },
345
+ }, ['champion']),
346
+ output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
347
+ execute: async args => {
348
+ const data = await get(`/build?champion=${encodeURIComponent(String(args?.champion ?? ''))}`)
349
+ return `${data.champion.name}(${data.champion.title})${data.champion.tier}|胜率 ${data.champion.win_rate_label}\n\n`
350
+ + (data.build ? buildBrief(data.build) : '暂无出装数据。')
351
+ + (data.build?.notes ? `\n\n${data.build.notes}` : '')
352
+ + `\n\n${await dataNote()}`
353
+ },
354
+ }
355
+
356
+ definitions.aram_augment_rank = {
357
+ name: 'aram_augment_rank',
358
+ description: 'Rank augment choices for one champion. Omit augments to get the champion\'s top recommendations; '
359
+ + 'pass a comma-separated list of names or IDs to compare specific cards.',
360
+ parameters: objectSchema({
361
+ champion: { type: 'string', description: 'Champion name, alias or numeric ID.' },
362
+ augments: { type: 'string', description: 'Optional comma-separated augment names or IDs, e.g. 命运之武器,尤里卡.' },
363
+ top: { type: 'integer', description: 'Maximum results, 1-10. Default 5.' },
364
+ }, ['champion']),
365
+ output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
366
+ execute: async args => {
367
+ const top = Math.min(Math.max(Math.round(Number(args?.top ?? 5)) || 5, 1), 10)
368
+ const q = new URLSearchParams({
369
+ champion: String(args?.champion ?? ''),
370
+ augments: String(args?.augments ?? ''),
371
+ top: String(top),
372
+ })
373
+ const data = await get(`/augments?${q}`)
374
+ if (!data.evaluations?.length) return '没有找到对应的海克斯数据。'
375
+ return `${data.evaluations.map((item, index) => `${index + 1}. ${fmtEval(item)}`).join('\n')}\n\n${await dataNote()}`
376
+ },
377
+ }
378
+
379
+ definitions.aram_lcu = {
380
+ name: 'aram_lcu',
381
+ description: 'Read the local League client state without automating anything: game phase, queue, my champion, '
382
+ + 'and the ARAM bench. Returns a clear disconnected state when the client or game is unavailable.',
383
+ parameters: objectSchema({}, []),
384
+ output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
385
+ execute: async () => {
386
+ const snapshot = await get('/snapshot')
387
+ const lcu = snapshot.lcu || {}
388
+ const state = snapshot.champ_select
389
+ const lines = [
390
+ `LCU:${lcu.connected ? '已连接' : '未连接'}|阶段 ${lcu.phase || '--'}${lcu.queue_name ? `|队列 ${lcu.queue_id} ${lcu.queue_name}` : ''}`,
391
+ ]
392
+ if (lcu.error) lines.push(`说明:${lcu.error}`)
393
+ if (state) {
394
+ lines.push(`我的英雄:${snapshot.my_champion?.champion?.name || state.my_champion_id || '未知'}`)
395
+ const bench = snapshot.bench || []
396
+ if (bench.length) {
397
+ lines.push('备战席:' + bench.map(item => {
398
+ const c = item.champion
399
+ return `${c.name} ${c.tier} ${c.win_rate_label}`
400
+ }).join('|'))
401
+ }
402
+ } else if (snapshot.my_champion?.champion) {
403
+ lines.push(`当前英雄:${snapshot.my_champion.champion.name}(${snapshot.my_champion.champion.tier},${snapshot.my_champion.champion.win_rate_label})`)
404
+ }
405
+ return lines.join('\n')
406
+ },
407
+ }
408
+
409
+ definitions.aram_scan = {
410
+ name: 'aram_scan',
411
+ description: 'Run the local screen OCR scan for the in-game augment card selection. It reads the game client '
412
+ + 'area only, maps card titles to augments, and ranks them for the current or specified champion. '
413
+ + 'Use only when the user is in an ARAM: Mayhem game and asks about the current cards.',
414
+ parameters: objectSchema({
415
+ champion: { type: 'string', description: 'Optional champion name/ID; omit to use the champion detected in champ select.' },
416
+ }, []),
417
+ output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
418
+ execute: async args => {
419
+ const data = await post('/scan', { champion: args?.champion || undefined })
420
+ if (!data.ok) return `识别失败:${data.error || '未知原因'}`
421
+ if (!data.matches?.length) return '没有识别到海克斯卡片。请确认游戏使用无边框/窗口化,并调整识别区域。'
422
+ const lines = [`识别到 ${data.matches.length} 张卡片:${data.matches.map(item => `${item.name}(${Math.round(item.confidence * 100)}%)`).join(' / ')}`]
423
+ if (data.champion) lines.push(`当前英雄:${data.champion.name}`)
424
+ if (data.evaluations?.length) {
425
+ lines.push('', '按当前英雄推荐:')
426
+ data.evaluations.forEach((item, index) => lines.push(`${index + 1}. ${fmtEval(item)}`))
427
+ }
428
+ lines.push('', await dataNote())
429
+ return lines.join('\n')
430
+ },
431
+ }
432
+
433
+ definitions.aram_refresh = {
434
+ name: 'aram_refresh',
435
+ description: 'Download a new portable ARAM: Mayhem dataset from a URL and atomically replace the local cache. '
436
+ + 'Only use when the user explicitly asks to refresh statistics or supplies a licensed data URL.',
437
+ parameters: objectSchema({
438
+ url: { type: 'string', description: 'Optional dataset JSON URL. Omit to use the configured stats_url.' },
439
+ }, []),
440
+ output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
441
+ execute: async args => {
442
+ const data = await post('/refresh', { url: args?.url || '' })
443
+ const meta = data.meta || {}
444
+ return `数据已更新:${meta.label || meta.patch || '--'}|来源 ${meta.source || '--'}|`
445
+ + `英雄 ${data.meta?.counts?.champions ?? '?'}|海克斯 ${data.meta?.counts?.augments ?? '?'}\n`
446
+ + `${meta.license || '--'};统计为部分对局样本。`
447
+ },
448
+ }
449
+
450
+ definitions.aram_service = {
451
+ name: 'aram_service',
452
+ description: 'Start, stop or inspect the local ARAM: Mayhem Python service. The service does not auto-start; '
453
+ + 'all data tools require it to be running.',
454
+ parameters: objectSchema({
455
+ action: {
456
+ type: 'string',
457
+ enum: ['start', 'stop', 'status'],
458
+ description: 'start launches the local service; stop terminates it; status only reports whether it is running.',
459
+ },
460
+ }, []),
461
+ output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
462
+ execute: async args => {
463
+ const action = String(args?.action || 'status')
464
+ if (action === 'start') await startService()
465
+ if (action === 'stop') await stopService()
466
+ const info = await serviceInfo()
467
+ if (info.running) {
468
+ return `海斗助手服务正在运行(PID ${info.pid}${info.version ? `,v${info.version}` : ''})。`
469
+ }
470
+ return info.starting ? '海斗助手服务正在启动…' : '海斗助手服务未运行。'
471
+ },
472
+ }
473
+
474
+ definitions.aram_overlay = {
475
+ name: 'aram_overlay',
476
+ description: 'Open, close or inspect the always-on-top desktop icon for the ARAM: Mayhem assistant. '
477
+ + 'The icon expands into champion, recommended augment and build views without opening the DSH page.',
478
+ parameters: objectSchema({
479
+ action: {
480
+ type: 'string',
481
+ enum: ['open', 'close', 'status'],
482
+ description: 'open shows the desktop icon; close exits it; status only reports whether it is running.',
483
+ },
484
+ }, []),
485
+ output: { schema: { type: 'string' }, render: (_args, value) => asText(value) },
486
+ execute: async args => {
487
+ const action = String(args?.action || 'open')
488
+ if (!(await alive())) return '海斗助手服务未启动;请让用户先在页面点击「服务 开」,或调用 aram_service start。'
489
+ if (action === 'status') {
490
+ const data = await get('/overlay/status')
491
+ return data.running
492
+ ? `桌面图标正在运行(PID ${data.pid})。`
493
+ : '桌面图标当前未运行。'
494
+ }
495
+ if (action === 'close') {
496
+ const data = await post('/overlay/stop', { persist: true })
497
+ return data.running ? '关闭请求已发送,但进程仍在运行。' : '桌面图标已关闭;自动启动开关已关闭。'
498
+ }
499
+ const data = await post('/overlay/start', { persist: true })
500
+ return data.running
501
+ ? `桌面图标已打开(PID ${data.pid})。点击图标展开英雄/推荐海克斯/出装。`
502
+ : `桌面图标未启动:${data.note || '未知原因'}`
503
+ },
504
+ }
505
+
506
+ for (const definition of Object.values(definitions)) ctx.tools.register(definition)
507
+
508
+ ctx.effect(
509
+ () => ctx.webServer.register({
510
+ kind: 'prefix',
511
+ path: '/aram-api',
512
+ handler: proxy,
513
+ }),
514
+ 'aram-mayhem: local service proxy',
515
+ )
516
+
517
+ ctx.effect(
518
+ () => ctx.webServer.register({
519
+ kind: 'prefix',
520
+ path: '/aram-control',
521
+ handler: control,
522
+ }),
523
+ 'aram-mayhem: service control',
524
+ )
525
+
526
+ ctx.systemPrompt.section({
527
+ name: 'aram-mayhem',
528
+ order: 210,
529
+ text: 'When the user asks about League of Legends ARAM: Mayhem (海克斯大乱斗) champions, augment choices, '
530
+ + 'win rates, builds or the current client state, use the aram_status / aram_champion / aram_augment_rank / '
531
+ + 'aram_build / aram_lcu tools instead of guessing. The local service does not auto-start; use aram_service '
532
+ + 'to start/stop it when needed. '
533
+ + 'Use aram_scan only when a game is running and the user '
534
+ + 'asks about the cards currently on screen. State the patch and that the data is a partial sample; '
535
+ + 'when giving statistics, mention the source and its CC BY-NC 4.0 non-commercial license. '
536
+ + 'Never present correlation as causation. The plugin is read-only and must not automate picks or gameplay.',
537
+ })
538
+
539
+ // Intentionally no auto-start: the service and icon are started from the
540
+ // page switches, the aram_service tool, or aram_overlay open.
541
+ ctx.effect(() => () => {
542
+ void stopService().catch(() => {})
543
+ })
544
+ }