@nonz250/ai-rotom 0.0.2 → 1.0.0

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/dist/index.mjs CHANGED
@@ -2,8 +2,12 @@
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
4
  import { z } from "zod";
5
+ import { randomBytes } from "node:crypto";
6
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { dirname, join } from "node:path";
5
9
  //#region \0rolldown/runtime.js
6
- var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
10
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
7
11
  //#endregion
8
12
  //#region ../../shared/src/utils/name-resolver.ts
9
13
  var NameResolver = class {
@@ -59,6 +63,10 @@ function levenshteinDistance(a, b) {
59
63
  return matrix[a.length][b.length];
60
64
  }
61
65
  //#endregion
66
+ //#region ../../shared/src/constants/champions.ts
67
+ /** タイプ一致 (STAB) 補正倍率。てきおうりょく等の特性補正は含まない通常値 */
68
+ const STAB_MULTIPLIER = 1.5;
69
+ //#endregion
62
70
  //#region ../../shared/src/analysis/type-matchup.ts
63
71
  /** 等倍の相性倍率 */
64
72
  const NEUTRAL_EFFECTIVENESS = 1;
@@ -108,6 +116,245 @@ function compareSpeed(a, b) {
108
116
  return "tie";
109
117
  }
110
118
  //#endregion
119
+ //#region ../../shared/src/analysis/priority-moves.ts
120
+ /** 優先度が 0 の技はこのモジュールの対象外(先制技のみを扱う) */
121
+ const MIN_PRIORITY_FOR_INCLUSION = 1;
122
+ /**
123
+ * learnset(技 ID の配列)から先制技のみを抽出し、priority 降順にソートして返す。
124
+ *
125
+ * - `priority >= 1` のみ対象
126
+ * - ソート: priority 降順 → 英名昇順(安定化のための二次キー)
127
+ * - `resolveMove` が undefined を返した ID は静かにスキップ(learnset と moves の
128
+ * 不整合で対面分析が落ちるのを避ける防衛的実装)
129
+ * - 日本語名は `resolveMove().nameJa` を優先し、null の場合は `toJapanese(enName)` に
130
+ * フォールバック。さらに未解決なら英名をそのまま返す
131
+ *
132
+ * 特性による priority 補正(いたずらごころ・はやてのつばさ等)はここでは扱わない。
133
+ */
134
+ function extractPriorityMoves(params) {
135
+ const { learnsetMoveIds, resolveMove, toJapanese } = params;
136
+ const results = [];
137
+ for (const id of learnsetMoveIds) {
138
+ const move = resolveMove(id);
139
+ if (move === void 0) continue;
140
+ if (move.priority < MIN_PRIORITY_FOR_INCLUSION) continue;
141
+ const moveJa = move.nameJa ?? toJapanese(move.name) ?? move.name;
142
+ results.push({
143
+ move: move.name,
144
+ moveJa,
145
+ priority: move.priority,
146
+ category: move.category
147
+ });
148
+ }
149
+ results.sort((a, b) => {
150
+ if (b.priority !== a.priority) return b.priority - a.priority;
151
+ return a.move.localeCompare(b.move);
152
+ });
153
+ return results;
154
+ }
155
+ //#endregion
156
+ //#region ../../shared/src/analysis/defensive-ability-overrides.ts
157
+ /** 無効(0 倍) */
158
+ const IMMUNE_MULTIPLIER = 0;
159
+ /** フィルター系特性が抜群時に掛ける倍率 (3/4 = 0.75) */
160
+ const FILTER_SUPER_EFFECTIVE_MULTIPLIER = .75;
161
+ /** 効果抜群とみなす最低倍率 */
162
+ const SUPER_EFFECTIVE_THRESHOLD = 2;
163
+ /** 文字列を ID 相当(英数字のみ・小文字)に正規化する */
164
+ function toId$1(value) {
165
+ return value.toLowerCase().replace(/[^a-z0-9]/g, "");
166
+ }
167
+ /**
168
+ * タイプ相性を無効化する特性 ID → 無効にする攻撃タイプのマップ。
169
+ * ぼうおん(Soundproof)は「おと系技」という技フラグ依存で、タイプ相性では
170
+ * 表現できないためここには含めない(issue スコープ外)。
171
+ */
172
+ const TYPE_IMMUNITY_ABILITIES = new Map([
173
+ ["levitate", "Ground"],
174
+ ["flashfire", "Fire"],
175
+ ["waterabsorb", "Water"],
176
+ ["voltabsorb", "Electric"],
177
+ ["lightningrod", "Electric"],
178
+ ["motordrive", "Electric"],
179
+ ["stormdrain", "Water"],
180
+ ["sapsipper", "Grass"]
181
+ ]);
182
+ /** 効果抜群時に 0.75 倍にする特性 ID のセット */
183
+ const FILTER_LIKE_ABILITIES = new Set([
184
+ "filter",
185
+ "solidrock",
186
+ "prismarmor"
187
+ ]);
188
+ /**
189
+ * 特性を加味したタイプ相性補正を適用する。
190
+ *
191
+ * 優先順位:
192
+ * 1. 特性による無効化
193
+ * 2. フィルター系の 0.75 倍(抜群時のみ)
194
+ *
195
+ * @param baseMultiplier 純粋なタイプ相性計算の結果
196
+ * @param attackingType 攻撃側の技タイプ
197
+ * @param context 防御側の ability(英語名 or ID)
198
+ * @returns 補正後の倍率
199
+ */
200
+ function applyDefensiveOverrides(baseMultiplier, attackingType, context) {
201
+ const abilityId = context.ability !== void 0 ? toId$1(context.ability) : void 0;
202
+ let multiplier = baseMultiplier;
203
+ if (abilityId !== void 0) {
204
+ const immuneType = TYPE_IMMUNITY_ABILITIES.get(abilityId);
205
+ if (immuneType !== void 0 && attackingType === immuneType) return IMMUNE_MULTIPLIER;
206
+ }
207
+ if (abilityId !== void 0 && FILTER_LIKE_ABILITIES.has(abilityId) && multiplier >= SUPER_EFFECTIVE_THRESHOLD) multiplier *= FILTER_SUPER_EFFECTIVE_MULTIPLIER;
208
+ return multiplier;
209
+ }
210
+ /** ??? タイプは計算対象から除外するためのマーカー */
211
+ const UNKNOWN_TYPE_NAME$1 = "???";
212
+ /** 偶奇判定に使う剰余の除数 (中央値計算で偶数長を判定するため) */
213
+ const EVEN_ODD_MODULUS = 2;
214
+ /** 中央値計算の偶数長時に合計を半分にするための除数 */
215
+ const MEDIAN_AVERAGE_DIVISOR = 2;
216
+ /**
217
+ * 単体ポケモンのタイプ構成に対する全攻撃タイプの相性を分類する。
218
+ * 倍率 >= 2 を weaknesses、< 1 を resistances、0 を immunities に振り分ける。
219
+ *
220
+ * `context` を渡すと特性 (Levitate / Filter 等) を加味した補正を適用する。
221
+ * 省略時は純粋なタイプ相性のみで分類する。
222
+ */
223
+ function classifyPokemonTypeMatchups(pokemonTypes, gen, context = {}) {
224
+ const weaknesses = [];
225
+ const resistances = [];
226
+ const immunities = [];
227
+ const defenderTypes = pokemonTypes;
228
+ for (const attackType of gen.types) {
229
+ if (attackType.name === UNKNOWN_TYPE_NAME$1) continue;
230
+ const multiplier = applyDefensiveOverrides(calculateTypeEffectiveness(gen, attackType.name, defenderTypes), attackType.name, context);
231
+ if (multiplier === 0) immunities.push(attackType.name);
232
+ else if (multiplier >= 2) weaknesses.push({
233
+ type: attackType.name,
234
+ multiplier
235
+ });
236
+ else if (multiplier < 1) resistances.push({
237
+ type: attackType.name,
238
+ multiplier
239
+ });
240
+ }
241
+ return {
242
+ weaknesses,
243
+ resistances,
244
+ immunities
245
+ };
246
+ }
247
+ /**
248
+ * パーティ全メンバーの「弱点タイプ」のユニーク集合を返す。
249
+ * あるタイプに対して 2 倍以上の弱点を持つメンバーが 1 体でもいれば含まれる。
250
+ */
251
+ function collectPartyWeaknessTypes(memberTypes, gen) {
252
+ const result = /* @__PURE__ */ new Set();
253
+ for (const types of memberTypes) {
254
+ const { weaknesses } = classifyPokemonTypeMatchups(types, gen);
255
+ for (const w of weaknesses) result.add(w.type);
256
+ }
257
+ return result;
258
+ }
259
+ /**
260
+ * パーティ全メンバーの「耐性タイプ (半減・無効)」のユニーク集合を返す。
261
+ * あるタイプに対して半減以下の耐性を持つメンバーが 1 体でもいれば含まれる。
262
+ */
263
+ function collectPartyResistanceTypes(memberTypes, gen) {
264
+ const result = /* @__PURE__ */ new Set();
265
+ for (const types of memberTypes) {
266
+ const { resistances, immunities } = classifyPokemonTypeMatchups(types, gen);
267
+ for (const r of resistances) result.add(r.type);
268
+ for (const t of immunities) result.add(t);
269
+ }
270
+ return result;
271
+ }
272
+ /**
273
+ * 数値配列の min / max / mean / median を返す。
274
+ * 空配列は全て 0 を返す (比較ツールで差分 0 として扱うためのフォールバック)。
275
+ */
276
+ function computeNumericStats(values) {
277
+ if (values.length === 0) return {
278
+ min: 0,
279
+ max: 0,
280
+ mean: 0,
281
+ median: 0
282
+ };
283
+ const sorted = [...values].sort((a, b) => a - b);
284
+ const min = sorted[0];
285
+ const max = sorted[sorted.length - 1];
286
+ const mean = sorted.reduce((acc, v) => acc + v, 0) / sorted.length;
287
+ const mid = Math.floor(sorted.length / EVEN_ODD_MODULUS);
288
+ return {
289
+ min,
290
+ max,
291
+ mean,
292
+ median: sorted.length % EVEN_ODD_MODULUS === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / MEDIAN_AVERAGE_DIVISOR
293
+ };
294
+ }
295
+ /**
296
+ * 種族値 6 つの合計 (BST, base stats total)。
297
+ */
298
+ function baseStatsTotal(stats) {
299
+ return stats.hp + stats.atk + stats.def + stats.spa + stats.spd + stats.spe;
300
+ }
301
+ //#endregion
302
+ //#region ../../shared/src/analysis/offensive-ability-overrides.ts
303
+ /**
304
+ * タイプ変更系特性(skin abilities)を扱う純関数モジュール。
305
+ *
306
+ * ノーマル技を別タイプに変換する特性の効果を、カバレッジ計算など
307
+ * 「タイプ相性のみ」を扱うツール向けに反映させる。
308
+ * 威力補正(1.2 倍)はここでは扱わない(ダメージ計算側の責務)。
309
+ */
310
+ /** ノーマル技は `move.type === "Normal"` を満たす */
311
+ const NORMAL_TYPE = "Normal";
312
+ /**
313
+ * 変化技のカテゴリ。変化技にはタイプ変更系特性は乗らない。
314
+ * mcp-server 側の MoveCategory と同じ文字列だが、shared は mcp-server に
315
+ * 依存できないためここで独立に定義する。
316
+ */
317
+ const STATUS_CATEGORY$4 = "Status";
318
+ /** 文字列を ID 相当(英数字のみ・小文字)に正規化する */
319
+ function toId(value) {
320
+ return value.toLowerCase().replace(/[^a-z0-9]/g, "");
321
+ }
322
+ /**
323
+ * 特性 ID → 変換後タイプのマップ。
324
+ * キーは `toId` 相当で正規化済みの特性 ID(例: "pixilate")。
325
+ *
326
+ * `data/champions/abilities.json` の id と一致する。
327
+ */
328
+ const OFFENSIVE_TYPE_OVERRIDES = new Map([
329
+ ["pixilate", "Fairy"],
330
+ ["galvanize", "Electric"],
331
+ ["refrigerate", "Ice"],
332
+ ["aerilate", "Flying"]
333
+ ]);
334
+ /**
335
+ * 攻撃技のタイプに対して、攻撃側の特性によるタイプ変更を適用する。
336
+ *
337
+ * ノーマル技 × タイプ変更系特性の組み合わせのときだけ変換後タイプを返し、
338
+ * それ以外は `originalMoveType` をそのまま返す(regression-free)。
339
+ *
340
+ * ability は英語名(@smogon/calc 互換の "Pixilate" 等)または ID
341
+ * ("pixilate" 等)を受け付ける。内部で `toId` による正規化を行う。
342
+ * 未知の値はそのまま無視する。
343
+ *
344
+ * @param originalMoveType 技本来のタイプ
345
+ * @param moveCategory 技カテゴリ(Status は変換対象外)
346
+ * @param ability 特性名(英語名 or ID、未指定・不明な特性は変換しない)
347
+ */
348
+ function applyOffensiveTypeOverride(originalMoveType, moveCategory, ability) {
349
+ if (ability === void 0) return originalMoveType;
350
+ if (originalMoveType !== NORMAL_TYPE) return originalMoveType;
351
+ if (moveCategory === STATUS_CATEGORY$4) return originalMoveType;
352
+ const abilityId = toId(ability);
353
+ const overrideType = OFFENSIVE_TYPE_OVERRIDES.get(abilityId);
354
+ if (overrideType === void 0) return originalMoveType;
355
+ return overrideType;
356
+ }
357
+ //#endregion
111
358
  //#region ../../shared/src/schemas/stats.ts
112
359
  const statPointValueSchema = z.number({ message: "能力ポイント(SP)は数値で指定してください。" }).int({ message: "能力ポイント(SP)は整数で指定してください。" }).finite().min(0, { message: "能力ポイント(SP)は 0 以上で指定してください。" }).max(32, { message: `能力ポイント(SP)は各ステータス 32 以下です (ポケモンチャンピオンズ仕様)。` });
113
360
  /**
@@ -154,11 +401,45 @@ const pokemonSchema = z.object({
154
401
  const conditionsSchema = z.object({
155
402
  weather: z.string().optional().describe("天候(Sun, Rain, Sand, Hail, Snow)"),
156
403
  terrain: z.string().optional().describe("フィールド(Electric, Grassy, Misty, Psychic)"),
404
+ battleFormat: z.enum(["singles", "doubles"]).optional().describe("対戦形式(シングル: singles / ダブル: doubles)。省略時は singles。doubles 指定時は全体攻撃技 (じしん/ねっぷう等) の威力が ×0.75 され、壁系の軽減率が約 0.667 倍に変わる。"),
157
405
  isReflect: z.boolean().optional().describe("リフレクター"),
158
406
  isLightScreen: z.boolean().optional().describe("ひかりのかべ"),
159
407
  isAuroraVeil: z.boolean().optional().describe("オーロラベール"),
160
408
  isCriticalHit: z.boolean().optional().describe("急所")
161
409
  });
410
+ /** メモの最大文字数。 */
411
+ const MAX_PARTY_MEMO_LENGTH = 4e3;
412
+ const nameField$1 = z.string().min(1, { message: "名前は 1 文字以上で指定してください。" }).max(100, { message: `名前は 100 文字以下で指定してください。` });
413
+ const optionalNameField = nameField$1.optional();
414
+ /**
415
+ * パーティに所属する 1 匹分の入力スキーマ。
416
+ */
417
+ const partyMemberSchema = z.object({
418
+ name: nameField$1.describe("ポケモン名 (日本語 or 英語)。"),
419
+ nature: optionalNameField.describe("性格名 (日本語 or 英語)。"),
420
+ ability: optionalNameField.describe("特性名 (日本語 or 英語)。"),
421
+ item: optionalNameField.describe("持ち物名 (日本語 or 英語)。"),
422
+ evs: evsSchema.optional().describe("能力ポイント (SP) の配分。"),
423
+ moves: z.array(nameField$1).max(4, { message: `技は 4 個までです。` }).optional().describe("技リスト (日本語 or 英語、最大 4)。")
424
+ });
425
+ const isoDateTimeField = z.string().refine((value) => !Number.isNaN(Date.parse(value)), { message: "ISO 8601 形式の日時文字列で指定してください。" });
426
+ /**
427
+ * 1 パーティ分の入力スキーマ。
428
+ */
429
+ const partySchema = z.object({
430
+ name: z.string().min(1, { message: "パーティ名は 1 文字以上で指定してください。" }).max(50, { message: `パーティ名は 50 文字以下で指定してください。` }).describe("パーティの識別子。"),
431
+ memo: z.string().max(MAX_PARTY_MEMO_LENGTH, { message: `メモは ${MAX_PARTY_MEMO_LENGTH} 文字以下で指定してください。` }).optional().describe("自由記述メモ。"),
432
+ members: z.array(partyMemberSchema).min(1, { message: `パーティには 1 匹以上を含めてください。` }).max(6, { message: `パーティには 6 匹までしか含められません。` }).describe("1〜6 匹のメンバー。"),
433
+ createdAt: isoDateTimeField.describe("作成日時 (ISO 8601)。"),
434
+ updatedAt: isoDateTimeField.describe("更新日時 (ISO 8601)。")
435
+ });
436
+ /**
437
+ * `~/.ai-rotom/parties.json` 全体のスキーマ。
438
+ */
439
+ const partiesFileSchema = z.object({
440
+ schemaVersion: z.number().int().positive().describe("パーティファイルの schemaVersion。"),
441
+ parties: z.array(partySchema).describe("登録済みパーティの一覧。")
442
+ });
162
443
  //#endregion
163
444
  //#region ../../node_modules/@smogon/calc/dist/util.js
164
445
  var require_util$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
@@ -44610,7 +44891,8 @@ var require_move = /* @__PURE__ */ __commonJSMin(((exports) => {
44610
44891
  this.overrides = options.overrides;
44611
44892
  this.species = options.species;
44612
44893
  this.bp = data.basePower;
44613
- this.type = (gen.num === 0 || gen.num >= 2) && data.id === "struggle" || gen.num > 0 && gen.num <= 4 && ["futuresight", "doomdesire"].includes(data.id) ? "???" : data.type;
44894
+ var typelessDamage = (gen.num === 0 || gen.num >= 2) && data.id === "struggle" || gen.num > 0 && gen.num <= 4 && ["futuresight", "doomdesire"].includes(data.id);
44895
+ this.type = typelessDamage ? "???" : data.type;
44614
44896
  this.category = data.category || (gen.num > 0 && gen.num < 4 ? SPECIAL.includes(data.type) ? "Special" : "Physical" : "Status");
44615
44897
  var stat = this.category === "Special" ? "spa" : "atk";
44616
44898
  if (((_b = data.self) === null || _b === void 0 ? void 0 : _b.boosts) && data.self.boosts[stat] && data.self.boosts[stat] < 0) this.dropsStats = Math.abs(data.self.boosts[stat]);
@@ -44948,7 +45230,7 @@ function resolveNameWithFallback(resolver, name, label) {
44948
45230
  * `resolveNameWithFallback` の undefined 許容版。
44949
45231
  * name が undefined なら undefined を返し、指定があれば解決する。
44950
45232
  */
44951
- function resolveOptionalName(resolver, name, label) {
45233
+ function resolveOptionalName$2(resolver, name, label) {
44952
45234
  if (name === void 0) return;
44953
45235
  return resolveNameWithFallback(resolver, name, label);
44954
45236
  }
@@ -44975,7 +45257,7 @@ function toSmogonBoosts(boosts) {
44975
45257
  * @smogon/calc の Specie 型は types を文字列 union のタプル ([TypeName] | [TypeName, TypeName]) として
44976
45258
  * 厳密に定義しているが、PokemonEntry 側は string[] で保持するため、呼び出し側でキャストする。
44977
45259
  */
44978
- function buildSpeciesOverrides$1(entry) {
45260
+ function buildSpeciesOverrides$2(entry) {
44979
45261
  return {
44980
45262
  types: entry.types,
44981
45263
  baseStats: entry.baseStats
@@ -45001,18 +45283,30 @@ function buildPokemonOptions(input, natureEn, abilityEn, itemEn, pokemonEntry) {
45001
45283
  item: itemEn,
45002
45284
  status: input.status ?? ""
45003
45285
  };
45004
- if (pokemonEntry !== void 0) baseOptions.overrides = buildSpeciesOverrides$1(pokemonEntry);
45286
+ if (pokemonEntry !== void 0) baseOptions.overrides = buildSpeciesOverrides$2(pokemonEntry);
45005
45287
  return baseOptions;
45006
45288
  }
45007
45289
  //#endregion
45008
45290
  //#region ../../shared/src/calc/builders/field-builder.ts
45009
45291
  /**
45292
+ * battleFormat を @smogon/calc の GameType に変換する。
45293
+ * 未指定 / "singles" は "Singles"、"doubles" は "Doubles"。
45294
+ */
45295
+ function toGameType(battleFormat) {
45296
+ return battleFormat === "doubles" ? "Doubles" : "Singles";
45297
+ }
45298
+ /**
45010
45299
  * ConditionsInput から @smogon/calc の Field オブジェクトを組み立てる。
45011
- * conditions が undefined の場合は空の Field を返す。
45300
+ * conditions が undefined の場合は gameType=Singles の空の Field を返す。
45301
+ *
45302
+ * gameType="Doubles" 指定時は @smogon/calc が以下のダブル補正を自動で適用する:
45303
+ * - 全体攻撃技 (target: allAdjacent / allAdjacentFoes) の威力 ×0.75
45304
+ * - リフレクター/ひかりのかべ/オーロラベールの軽減率が 0.5 → 約 0.667 倍
45012
45305
  */
45013
45306
  function buildField(conditions) {
45014
- if (conditions === void 0) return new import_dist.Field();
45307
+ if (conditions === void 0) return new import_dist.Field({ gameType: "Singles" });
45015
45308
  return new import_dist.Field({
45309
+ gameType: toGameType(conditions.battleFormat),
45016
45310
  weather: conditions.weather,
45017
45311
  terrain: conditions.terrain,
45018
45312
  defenderSide: {
@@ -45039,8 +45333,19 @@ function toPercent(value, maxHP) {
45039
45333
  }
45040
45334
  //#endregion
45041
45335
  //#region ../../shared/src/calc/damage-calculator.ts
45042
- const CHAMPIONS_GEN_NUM$9 = 0;
45043
- const DEFAULT_NATURE_EN$1 = "Serious";
45336
+ const CHAMPIONS_GEN_NUM$10 = 0;
45337
+ const DEFAULT_NATURE_EN$2 = "Serious";
45338
+ function buildTypeMetrics(gen, move, attacker, defender) {
45339
+ const moveType = move.type;
45340
+ const typeMultiplier = calculateTypeEffectiveness(gen, moveType, defender.types);
45341
+ const isStab = attacker.types.includes(moveType);
45342
+ return {
45343
+ moveType,
45344
+ typeMultiplier,
45345
+ isStab,
45346
+ effectivePowerMultiplier: (isStab ? STAB_MULTIPLIER : 1) * typeMultiplier
45347
+ };
45348
+ }
45044
45349
  /**
45045
45350
  * @smogon/calc のラッパー。日本語名入力を受け付け、
45046
45351
  * 名前解決・Pokemon/Move/Field 組み立て・結果整形をまとめて担う Facade。
@@ -45068,29 +45373,33 @@ var DamageCalculatorAdapter = class {
45068
45373
  const moveName = resolveNameWithFallback(this.resolvers.move, input.moveName, "技");
45069
45374
  const attackerNature = this.resolveNature(input.attacker.nature);
45070
45375
  const defenderNature = this.resolveNature(input.defender.nature);
45071
- const attackerAbility = resolveOptionalName(this.resolvers.ability, input.attacker.ability, "特性");
45072
- const defenderAbility = resolveOptionalName(this.resolvers.ability, input.defender.ability, "特性");
45073
- const attackerItem = resolveOptionalName(this.resolvers.item, input.attacker.item, "持ち物");
45074
- const defenderItem = resolveOptionalName(this.resolvers.item, input.defender.item, "持ち物");
45376
+ const attackerAbility = resolveOptionalName$2(this.resolvers.ability, input.attacker.ability, "特性");
45377
+ const defenderAbility = resolveOptionalName$2(this.resolvers.ability, input.defender.ability, "特性");
45378
+ const attackerItem = resolveOptionalName$2(this.resolvers.item, input.attacker.item, "持ち物");
45379
+ const defenderItem = resolveOptionalName$2(this.resolvers.item, input.defender.item, "持ち物");
45075
45380
  const attacker = new import_dist.Pokemon(gen, attackerName, buildPokemonOptions(input.attacker, attackerNature, attackerAbility, attackerItem, this.entryProvider?.getByName(attackerName)));
45076
45381
  const defender = new import_dist.Pokemon(gen, defenderName, buildPokemonOptions(input.defender, defenderNature, defenderAbility, defenderItem, this.entryProvider?.getByName(defenderName)));
45077
- const result = (0, import_dist.calculate)(gen, attacker, defender, new import_dist.Move(gen, moveName, { isCrit: input.conditions?.isCriticalHit }), buildField(input.conditions));
45382
+ const move = new import_dist.Move(gen, moveName, { isCrit: input.conditions?.isCriticalHit });
45383
+ const result = (0, import_dist.calculate)(gen, attacker, defender, move, buildField(input.conditions));
45078
45384
  const [min, max] = result.range();
45079
45385
  const defenderMaxHP = defender.maxHP();
45080
45386
  const minPercent = toPercent(min, defenderMaxHP);
45081
45387
  const maxPercent = toPercent(max, defenderMaxHP);
45082
45388
  const koResult = result.kochance();
45389
+ const damageArray = flattenDamage(result.damage);
45390
+ const typeMetrics = buildTypeMetrics(gen, move, attacker, defender);
45083
45391
  return {
45084
45392
  attacker: attackerName,
45085
45393
  defender: defenderName,
45086
45394
  move: moveName,
45087
- damage: flattenDamage(result.damage),
45395
+ damage: damageArray,
45088
45396
  min,
45089
45397
  max,
45090
45398
  minPercent,
45091
45399
  maxPercent,
45092
45400
  koChance: koResult.text,
45093
- description: result.fullDesc()
45401
+ description: result.fullDesc(),
45402
+ ...typeMetrics
45094
45403
  };
45095
45404
  }
45096
45405
  calculateAllMoves(input) {
@@ -45099,10 +45408,10 @@ var DamageCalculatorAdapter = class {
45099
45408
  const defenderName = resolveNameWithFallback(this.resolvers.pokemon, input.defender.name, "ポケモン");
45100
45409
  const attackerNature = this.resolveNature(input.attacker.nature);
45101
45410
  const defenderNature = this.resolveNature(input.defender.nature);
45102
- const attackerAbility = resolveOptionalName(this.resolvers.ability, input.attacker.ability, "特性");
45103
- const defenderAbility = resolveOptionalName(this.resolvers.ability, input.defender.ability, "特性");
45104
- const attackerItem = resolveOptionalName(this.resolvers.item, input.attacker.item, "持ち物");
45105
- const defenderItem = resolveOptionalName(this.resolvers.item, input.defender.item, "持ち物");
45411
+ const attackerAbility = resolveOptionalName$2(this.resolvers.ability, input.attacker.ability, "特性");
45412
+ const defenderAbility = resolveOptionalName$2(this.resolvers.ability, input.defender.ability, "特性");
45413
+ const attackerItem = resolveOptionalName$2(this.resolvers.item, input.attacker.item, "持ち物");
45414
+ const defenderItem = resolveOptionalName$2(this.resolvers.item, input.defender.item, "持ち物");
45106
45415
  const attacker = new import_dist.Pokemon(gen, attackerName, buildPokemonOptions(input.attacker, attackerNature, attackerAbility, attackerItem, this.entryProvider?.getByName(attackerName)));
45107
45416
  const defender = new import_dist.Pokemon(gen, defenderName, buildPokemonOptions(input.defender, defenderNature, defenderAbility, defenderItem, this.entryProvider?.getByName(defenderName)));
45108
45417
  const field = buildField(input.conditions);
@@ -45111,13 +45420,15 @@ var DamageCalculatorAdapter = class {
45111
45420
  for (const moveData of gen.moves) {
45112
45421
  if (!moveData.basePower || moveData.basePower <= 0) continue;
45113
45422
  try {
45114
- const result = (0, import_dist.calculate)(gen, attacker, defender, new import_dist.Move(gen, moveData.name, { isCrit: input.conditions?.isCriticalHit }), field);
45423
+ const move = new import_dist.Move(gen, moveData.name, { isCrit: input.conditions?.isCriticalHit });
45424
+ const result = (0, import_dist.calculate)(gen, attacker, defender, move, field);
45115
45425
  const [min, max] = result.range();
45116
45426
  if (max <= 0) continue;
45117
45427
  const minPercent = toPercent(min, defenderMaxHP);
45118
45428
  const maxPercent = toPercent(max, defenderMaxHP);
45119
45429
  const koResult = result.kochance();
45120
45430
  const damageArray = flattenDamage(result.damage);
45431
+ const typeMetrics = buildTypeMetrics(gen, move, attacker, defender);
45121
45432
  results.push({
45122
45433
  attacker: attackerName,
45123
45434
  defender: defenderName,
@@ -45128,7 +45439,8 @@ var DamageCalculatorAdapter = class {
45128
45439
  minPercent,
45129
45440
  maxPercent,
45130
45441
  koChance: koResult.text,
45131
- description: result.fullDesc()
45442
+ description: result.fullDesc(),
45443
+ ...typeMetrics
45132
45444
  });
45133
45445
  } catch {}
45134
45446
  }
@@ -45139,12 +45451,12 @@ var DamageCalculatorAdapter = class {
45139
45451
  const gen = this.getGen();
45140
45452
  const resolvedName = resolveNameWithFallback(this.resolvers.pokemon, input.name, "ポケモン");
45141
45453
  return {
45142
- pokemon: new import_dist.Pokemon(gen, resolvedName, buildPokemonOptions(input, this.resolveNature(input.nature), resolveOptionalName(this.resolvers.ability, input.ability, "特性"), resolveOptionalName(this.resolvers.item, input.item, "持ち物"), this.entryProvider?.getByName(resolvedName))),
45454
+ pokemon: new import_dist.Pokemon(gen, resolvedName, buildPokemonOptions(input, this.resolveNature(input.nature), resolveOptionalName$2(this.resolvers.ability, input.ability, "特性"), resolveOptionalName$2(this.resolvers.item, input.item, "持ち物"), this.entryProvider?.getByName(resolvedName))),
45143
45455
  resolvedName
45144
45456
  };
45145
45457
  }
45146
45458
  getGen() {
45147
- return import_dist.Generations.get(CHAMPIONS_GEN_NUM$9);
45459
+ return import_dist.Generations.get(CHAMPIONS_GEN_NUM$10);
45148
45460
  }
45149
45461
  get pokemonResolver() {
45150
45462
  return this.resolvers.pokemon;
@@ -45156,15 +45468,41 @@ var DamageCalculatorAdapter = class {
45156
45468
  return this.resolvers.nature;
45157
45469
  }
45158
45470
  resolveNature(nature) {
45159
- if (nature === void 0) return DEFAULT_NATURE_EN$1;
45471
+ if (nature === void 0) return DEFAULT_NATURE_EN$2;
45160
45472
  return resolveNameWithFallback(this.resolvers.nature, nature, "性格");
45161
45473
  }
45162
45474
  };
45163
45475
  //#endregion
45476
+ //#region ../../shared/src/calc/filters/learnset-filter.ts
45477
+ /**
45478
+ * calculateAllMoves の結果を learnset で絞り込む。
45479
+ *
45480
+ * @smogon/calc は全技を走査するため、実際に覚えない技で過大評価しないように
45481
+ * 呼び出し側で learnset フィルタを適用するための純関数。
45482
+ *
45483
+ * learnsetMoveIds が空集合の場合は、learnset データが無い(不明)とみなして
45484
+ * フィルタせず元の配列をそのまま返す(現行挙動踏襲)。
45485
+ *
45486
+ * 呼び出し側は `results[i].move` と `learnsetMoveIds` を同じ正規化形式で
45487
+ * 揃える責務を持つ。正規化ロジックは `normalize` 引数で注入する。
45488
+ */
45489
+ function filterResultsByLearnset(results, learnsetMoveIds, normalize) {
45490
+ if (learnsetMoveIds.size === 0) return [...results];
45491
+ return results.filter((r) => learnsetMoveIds.has(normalize(r.move)));
45492
+ }
45493
+ //#endregion
45164
45494
  //#region src/instructions.ts
45165
45495
  const SERVER_INSTRUCTIONS = `
45166
45496
  ai-rotom はポケモンチャンピオンズ (Pokemon Champions) の対戦アドバイザー MCP サーバーです。
45167
- 以下の固有仕様に従って入力を組み立ててください。従来シリーズ (SV 等) の知識をそのまま流用すると誤った結果になります。
45497
+
45498
+ ## セッションスコープ(重要)
45499
+
45500
+ - このセッション内でポケモン関連の話題が出た場合は、すべてポケモンチャンピオンズ (Pokemon Champions) の仕様として扱ってください。
45501
+ - 従来作 (SV / 剣盾 / USUM / BDSP / LA 等) の仕様・技威力・特性効果・種族値・タイプ相性などを前提にしないでください。
45502
+ - 従来作の知識と差異が生じ得る項目 (種族値・技の威力/PP・特性効果・タイプ等) は、get_pokemon_info / get_move_info / get_ability_info / get_item_info / get_type_info 等のツールで必ず事実確認してください。
45503
+ - ポケチャン固有仕様で不明な点は推測で埋めず、ユーザーに確認してください。
45504
+
45505
+ 以降は、従来作と差異が出やすい代表的な固有仕様です。
45168
45506
 
45169
45507
  ## 能力ポイント (SP) について
45170
45508
 
@@ -45182,11 +45520,81 @@ ai-rotom はポケモンチャンピオンズ (Pokemon Champions) の対戦ア
45182
45520
  - メガシンカ: 1試合につき1回のみ使用可能。
45183
45521
  - テラスタル: 未対応 (ゲーム側で未実装のため)。
45184
45522
 
45523
+ ## 判断と計算の役割分担
45524
+
45525
+ - 本サーバーのツールは「判断の根拠となる正確なデータを返す」ことに責務を限定しています。
45526
+ 「この選出が最適」「この構築が正解」といった最終判断は返しません。
45527
+ - 選出・構築・対策の結論は、ツールが返したデータ (タイプ相性・ダメ計・素早さ比較・対面マトリクス等) を元に AI が総合的に導いてください。
45528
+ - 一部ツール (find_counters 等) はスコア付きの候補リストを返しますが、これは候補抽出のための目安であり、
45529
+ 最終的な採用判断はダメ計・素早さ・対面状況を踏まえて AI が行うものです。
45530
+
45185
45531
  ## 推奨される使い方
45186
45532
 
45187
45533
  - ポケモン情報の確認: get_pokemon_info / search_pokemon
45188
45534
  - 特定の技のダメージ計算: calculate_damage_single
45189
- - 育成データが不明な場合は evs・nature・ability 等を省略してよい (デフォルト値で計算)
45535
+ - 育成データが不明な場合は evs・nature を省略してよい (デフォルト値で計算)
45536
+
45537
+ ## 計算・分析系ツールでの ability / item 指定
45538
+
45539
+ - 計算・対面分析系ツール (calculate_damage_single / calculate_damage_all_moves / calculate_damage_party_matchup / analyze_damage_range / analyze_matchup / analyze_selection / find_counters) を呼ぶ前に、攻撃側・防御側の ability / item を確認してから指定すること。
45540
+ - 省略時の挙動: ability は通常特性 (pokemon.json の abilities[0]) が自動設定され、item は持ち物なし扱いとなる。そのためメガシンカ・こだわり系・半減きのみ・ちからのハチマキ 等が反映されず、実戦想定の build と乖離した結果になる。
45541
+ - 正確な計算のためには ability / item を明示的に指定することを強く推奨する。
45542
+
45543
+ ## パーティデータの扱い
45544
+
45545
+ - セッション開始時 (初回ユーザー発話への応答前) に必ず list_parties を呼び、保存済みパーティの名前一覧を把握すること。
45546
+ - ユーザーが「メインパ」「ドラゴン軸」等の保存名に言及したら load_party で詳細を取得し、分析ツールに渡すこと。
45547
+ - ユーザーが新規構築を説明した際は「保存しますか」と確認し、同意があれば save_party を呼ぶこと。
45548
+ - パーティの削除依頼は delete_party を使うこと。
45549
+ - 起動時にパーティ詳細まで自動読み込みしないこと (トークン消費を抑えるため、詳細は都度 load_party で取得する)。
45550
+
45551
+ ## パーティ登録の対話スタイル
45552
+
45553
+ ユーザーが「パーティを保存したい」「構築を覚えて」等と依頼した場合:
45554
+
45555
+ ### テキスト一括投入の場合 (ケース A)
45556
+
45557
+ - ユーザーが Showdown 風 or ポケソルテキストを貼り付けた → import_party_from_text を呼ぶ (原文をそのまま渡す)。
45558
+ - ユーザーがゲーム内画面のスクショを添付した → 画像から build を読み取り、下記の対話ケース (B) と同じ手順でポケソルテキストに整理してから import_party_from_text を呼ぶ。
45559
+
45560
+ ### 対話で埋める場合 (ケース B)
45561
+
45562
+ - ユーザーがテキストもスクショも提供しない → AI が段階的に質問する。
45563
+ - 1 匹ずつ以下の順で聞く (ユーザーが知っている情報から埋める):
45564
+ 1. ポケモン名 (日本語 or 英語)
45565
+ 2. 性格 (候補を 4-5 個提示: いじっぱり / ようき / ひかえめ / おくびょう / ずぶとい など)
45566
+ 3. 特性 (該当ポケモンの候補を提示)
45567
+ 4. もちもの (省略可能、候補があれば提示)
45568
+ 5. 技 4 つ
45569
+ 6. SP 配分 (省略時は無振り 0、指定あれば各 0〜32 / 合計 0〜66 で受け付け)
45570
+
45571
+ ### 整理ステップ (重要)
45572
+
45573
+ - 対話で情報が揃ったら、必ずポケソルテキスト形式にまとめて表示し、ユーザーに確認を取ること:
45574
+
45575
+ 例:
45576
+ ガブリアス @ こだわりスカーフ
45577
+ 特性: さめはだ
45578
+ 能力補正: いじっぱり
45579
+ 170(2)-200(32)-115(0)-90(0)-100(0)-167(32)
45580
+ じしん / ドラゴンクロー / つのドリル / いわなだれ
45581
+
45582
+ - 実数値が不明な場合は calculate_stats を呼んで補完する (パーサー仕様上、実数値行は省略可能だが、ユーザー確認用に含めることを推奨)。
45583
+ - 複数匹の場合は空行区切りで並べる。
45584
+ - ユーザー確認後 import_party_from_text(text, name, memo) を呼ぶ。
45585
+ - パーサーがエラーを返した場合は、原因を提示してユーザーに修正を確認する。
45586
+
45587
+ ### 質問の書き方ルール
45588
+
45589
+ - 質問は短く、候補があれば列挙する (「性格はどうしますか? いじっぱり / ようき / ひかえめ」のような形式)。
45590
+ - 一度に 1 項目だけ聞く (複数同時の質問は避ける)。
45591
+ - ユーザーが「後で決める」と言った項目はデフォルト値で埋める (性格=まじめ、特性=基本特性、SP=無振り 等)。
45592
+ - 不明な項目は tool 呼び出しで確認する (例: 覚える技 → get_learnset)。
45593
+
45594
+ ### 絶対に守ること
45595
+
45596
+ - 対話で得た情報を JSON 化して save_party を直接呼ばない (ハルシネーションリスク軽減のため必ずポケソルテキスト経由)。
45597
+ - ユーザー確認なしに save / import を実行しない。
45190
45598
  `.trim();
45191
45599
  //#endregion
45192
45600
  //#region ../../data/champions/abilities.json
@@ -76483,6 +76891,18 @@ function toDataId(name) {
76483
76891
  * 英語名から pokemonById Map を引いて PokemonEntry を返す。
76484
76892
  */
76485
76893
  const pokemonEntryProvider = { getByName: (name) => pokemonById.get(toDataId(name)) };
76894
+ /**
76895
+ * 指定ポケモンの learnset に含まれる技 ID セットを取得する。
76896
+ * 未登録のポケモンは空 Set を返す(shared の filterResultsByLearnset では
76897
+ * 空 Set を「learnset データが無い」フォールバックとして扱う)。
76898
+ * learnset JSON の ID は既に Showdown toID 形式だが、呼び出し側の
76899
+ * 正規化関数({@link toDataId})との対称性を保つため念のため通している。
76900
+ */
76901
+ function getLearnsetMoveIdSet(pokemonId) {
76902
+ const learnset = championsLearnsets[pokemonId];
76903
+ if (learnset === void 0) return /* @__PURE__ */ new Set();
76904
+ return new Set(learnset.map(toDataId));
76905
+ }
76486
76906
  //#endregion
76487
76907
  //#region src/name-resolvers.ts
76488
76908
  /**
@@ -76507,9 +76927,9 @@ const itemNameResolver = new NameResolver(toNameEntries(items_default));
76507
76927
  const moveNameResolver = new NameResolver(toNameEntries(moves_default));
76508
76928
  //#endregion
76509
76929
  //#region src/tools/info/ability-info.ts
76510
- const TOOL_NAME$18 = "get_ability_info";
76511
- const TOOL_DESCRIPTION$18 = "ポケモンの特性の詳細情報(効果説明)を取得する。ポケモンチャンピオンズで使える特性のみ返す。対戦でポケモンの特性を理解したいときに使用する。";
76512
- const inputSchema$15 = { name: z.string().describe("特性名(日本語 or 英語)") };
76930
+ const TOOL_NAME$20 = "get_ability_info";
76931
+ const TOOL_DESCRIPTION$20 = "ポケモンの特性の詳細情報(効果説明)を取得する。ポケモンチャンピオンズで使える特性のみ返す。対戦でポケモンの特性を理解したいときに使用する。";
76932
+ const inputSchema$17 = { name: z.string().describe("特性名(日本語 or 英語)") };
76513
76933
  /**
76514
76934
  * 特性名を英語に解決する。日本語名・英語名どちらでも受け付ける。
76515
76935
  */
@@ -76522,7 +76942,7 @@ function resolveAbilityNameEn$1(input) {
76522
76942
  throw new Error(`特性「${input}」が見つかりません。${suggestionMessage}`);
76523
76943
  }
76524
76944
  function registerAbilityInfoTool(server) {
76525
- server.tool(TOOL_NAME$18, TOOL_DESCRIPTION$18, inputSchema$15, async (args) => {
76945
+ server.tool(TOOL_NAME$20, TOOL_DESCRIPTION$20, inputSchema$17, async (args) => {
76526
76946
  try {
76527
76947
  const abilityId = toDataId(resolveAbilityNameEn$1(args.name));
76528
76948
  const entry = abilitiesById.get(abilityId);
@@ -76550,6 +76970,504 @@ function registerAbilityInfoTool(server) {
76550
76970
  });
76551
76971
  }
76552
76972
  //#endregion
76973
+ //#region src/tools/analysis/party-coverage.ts
76974
+ const CHAMPIONS_GEN_NUM$9 = 0;
76975
+ /** 複合タイプを構成するタイプ数 */
76976
+ const DUAL_TYPE_COUNT = 2;
76977
+ /** 複合タイプ集合キーのセパレータ(タイプ名に現れない文字) */
76978
+ const DUAL_TYPE_KEY_SEPARATOR = "/";
76979
+ /** `dualTypeCoverage` の `examplePokemon` に収める最大件数 */
76980
+ const MAX_EXAMPLE_POKEMON = 3;
76981
+ /** ステータス技(攻撃タイプから除外するため) */
76982
+ const STATUS_CATEGORY$3 = "Status";
76983
+ const TOOL_NAME$19 = "analyze_party_coverage";
76984
+ const TOOL_DESCRIPTION$19 = "パーティの攻撃カバレッジを分析する。各防御タイプ(18種)に対して、パーティのどの技が最も効果的かを算出し、抜群を取れないタイプを洗い出す。 `uncoveredTypes` は『抜群(>1 倍)を取れる技が 1 つも無い防御タイプ』を列挙する(等倍 1 倍も含む)。抜群倍率の内訳は `coverage[].maxMultiplier` を参照。 実在する複合タイプ(データ内に 1 匹以上存在する 2 タイプ組合せ)に対するカバレッジは `dualTypeCoverage` を参照。抜群を取れない複合タイプ数は `dualTypeUncoveredCount`。 攻撃側のタイプ変換系特性(Pixilate 等)は単一/複合カバレッジ双方に反映される。 ポケモンチャンピオンズ対応。";
76985
+ const inputSchema$16 = {
76986
+ myParty: z.array(pokemonSchema).describe("自分のパーティ(moves 未指定時は learnset 内の全攻撃技を候補にする)"),
76987
+ moves: z.record(z.string(), z.array(z.string())).optional().describe("ポケモン名(日本語 or 英語)をキーに技名配列を値とする map。省略時は learnset から全攻撃技を候補にする。")
76988
+ };
76989
+ /**
76990
+ * 1 メンバー分の「覚えている攻撃技 ID」を取得する。
76991
+ * moves 指定があればそれを使い、未指定時は learnset から category !== Status の技を全て拾う。
76992
+ */
76993
+ function resolveAttackingMoveIds(pokemonEntry, explicitMoves) {
76994
+ if (explicitMoves !== void 0) {
76995
+ const result = [];
76996
+ for (const moveName of explicitMoves) {
76997
+ const moveId = toDataId(moveName);
76998
+ const move = movesById.get(moveId);
76999
+ if (move !== void 0 && move.category !== STATUS_CATEGORY$3) result.push(move);
77000
+ }
77001
+ return result;
77002
+ }
77003
+ const learnset = championsLearnsets[pokemonEntry.id];
77004
+ if (learnset === void 0) return [];
77005
+ const moves = [];
77006
+ for (const moveId of learnset) {
77007
+ const move = movesById.get(moveId);
77008
+ if (move !== void 0 && move.category !== STATUS_CATEGORY$3) moves.push(move);
77009
+ }
77010
+ return moves;
77011
+ }
77012
+ /**
77013
+ * 日本語・英語のどちらの名前でも英語名に解決する。
77014
+ * 未知の名前は undefined を返し、呼び出し側で silent ignore する。
77015
+ *
77016
+ * 未知の特性文字列でエラーにしないのは、party_coverage が
77017
+ * 「構築入力を緩く受け取る」UX を取っているため。
77018
+ * 未知の特性は単に override なし扱いとする。
77019
+ */
77020
+ function resolveOptionalName$1(resolver, name) {
77021
+ if (name === void 0) return void 0;
77022
+ const english = resolver.toEnglish(name);
77023
+ if (english !== void 0) return english;
77024
+ if (resolver.hasEnglishName(name)) return name;
77025
+ }
77026
+ /**
77027
+ * ポケモン名を pokemon.json のエントリに解決する。
77028
+ */
77029
+ function resolvePokemonEntry$4(name) {
77030
+ const englishName = pokemonNameResolver.toEnglish(name) ?? (pokemonNameResolver.hasEnglishName(name) ? name : null);
77031
+ if (englishName === null) {
77032
+ const suggestions = pokemonNameResolver.suggestSimilar(name);
77033
+ const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
77034
+ throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
77035
+ }
77036
+ const entry = pokemonById.get(toDataId(englishName));
77037
+ if (entry === void 0) throw new Error(`ポケモン「${name}」のデータが見つかりません。`);
77038
+ return entry;
77039
+ }
77040
+ /**
77041
+ * moves マップのキー(日本語 or 英語ポケモン名)を英語 ID に正規化する。
77042
+ */
77043
+ function normalizeMovesMap(moves) {
77044
+ const result = /* @__PURE__ */ new Map();
77045
+ if (moves === void 0) return result;
77046
+ for (const [pokemonName, moveList] of Object.entries(moves)) {
77047
+ const entry = resolvePokemonEntry$4(pokemonName);
77048
+ result.set(entry.id, moveList);
77049
+ }
77050
+ return result;
77051
+ }
77052
+ /**
77053
+ * 攻撃タイプ → 単一防御タイプへの倍率を計算する。
77054
+ */
77055
+ function getEffectivenessForDefenderType(attackTypeName, defenderTypeName, gen) {
77056
+ return calculateTypeEffectiveness(gen, attackTypeName, [defenderTypeName]);
77057
+ }
77058
+ /**
77059
+ * 攻撃タイプ → 複合防御タイプへの倍率を計算する。
77060
+ */
77061
+ function getEffectivenessForDualTypes(attackTypeName, defenderTypes, gen) {
77062
+ return calculateTypeEffectiveness(gen, attackTypeName, defenderTypes);
77063
+ }
77064
+ /**
77065
+ * 実在する複合タイプ(データ内に 1 匹以上存在するタイプ組合せ)の集合を構築する。
77066
+ * 対称性解消のため、キーは英名辞書順の 2 タイプを `/` で連結した文字列とする。
77067
+ *
77068
+ * `examplePokemon` 用の代表ポケモンも同時に収集する:
77069
+ * - メガ進化・リージョンフォーム等の派生フォーム(`baseSpecies !== null`)は後置し、
77070
+ * ベース種族を優先表示する(同じ実体の重複を避けるため)
77071
+ * - 同一優先度内では英名の辞書順で安定化
77072
+ * - 先頭 `MAX_EXAMPLE_POKEMON` 件を採用
77073
+ */
77074
+ function buildRealDualTypeMap(pokemon) {
77075
+ const accumulator = /* @__PURE__ */ new Map();
77076
+ for (const entry of pokemon) {
77077
+ if (entry.types.length !== DUAL_TYPE_COUNT) continue;
77078
+ const sortedTypes = [...entry.types].sort((a, b) => a.localeCompare(b));
77079
+ const key = `${sortedTypes[0]}${DUAL_TYPE_KEY_SEPARATOR}${sortedTypes[1]}`;
77080
+ const existing = accumulator.get(key);
77081
+ if (existing === void 0) accumulator.set(key, {
77082
+ types: sortedTypes,
77083
+ entries: [entry]
77084
+ });
77085
+ else existing.entries.push(entry);
77086
+ }
77087
+ const result = /* @__PURE__ */ new Map();
77088
+ for (const [key, { types, entries }] of accumulator) {
77089
+ const examplePokemon = [...entries].sort((a, b) => {
77090
+ const aIsForme = a.baseSpecies !== null ? 1 : 0;
77091
+ const bIsForme = b.baseSpecies !== null ? 1 : 0;
77092
+ if (aIsForme !== bIsForme) return aIsForme - bIsForme;
77093
+ return a.name.localeCompare(b.name);
77094
+ }).slice(0, MAX_EXAMPLE_POKEMON).map((entry) => pokemonNameResolver.toJapanese(entry.name) ?? entry.name);
77095
+ result.set(key, {
77096
+ types,
77097
+ examplePokemon
77098
+ });
77099
+ }
77100
+ return result;
77101
+ }
77102
+ /**
77103
+ * 候補の attacker で `bestAttackers` を更新する共通ロジック。
77104
+ *
77105
+ * - `candidate.multiplier > currentMax` の場合は bestAttackers をクリアして入れ替え、新しい max を返す
77106
+ * - タイの場合は同一ポケモンが未登録であれば追加する(multiplier > 0 のときのみ、0 倍無効は列挙しない)
77107
+ * - それ以外は現状維持
77108
+ *
77109
+ * bestAttackers は in-place で更新する。maxMultiplier は戻り値として返す。
77110
+ */
77111
+ function updateBestAttackers(currentMax, bestAttackers, candidate) {
77112
+ if (candidate.multiplier > currentMax) {
77113
+ bestAttackers.length = 0;
77114
+ bestAttackers.push(candidate);
77115
+ return candidate.multiplier;
77116
+ }
77117
+ if (candidate.multiplier === currentMax && candidate.multiplier > 0) {
77118
+ if (!bestAttackers.some((ba) => ba.pokemon === candidate.pokemon)) bestAttackers.push(candidate);
77119
+ }
77120
+ return currentMax;
77121
+ }
77122
+ /**
77123
+ * パーティの攻撃カバレッジを計算する純関数。
77124
+ * MCP tool handler からも直接テストからも呼び出せる。
77125
+ */
77126
+ function analyzePartyCoverage(args) {
77127
+ const gen = import_dist.Generations.get(CHAMPIONS_GEN_NUM$9);
77128
+ const movesMap = normalizeMovesMap(args.moves);
77129
+ const members = [];
77130
+ const attackingTypesSet = /* @__PURE__ */ new Set();
77131
+ for (const member of args.myParty) {
77132
+ const entry = resolvePokemonEntry$4(member.name);
77133
+ const rawAttackingMoves = resolveAttackingMoveIds(entry, movesMap.get(entry.id));
77134
+ const ability = resolveOptionalName$1(abilityNameResolver, member.ability);
77135
+ const attackingMoves = [];
77136
+ for (const move of rawAttackingMoves) {
77137
+ const effectiveType = applyOffensiveTypeOverride(move.type, move.category, ability);
77138
+ attackingTypesSet.add(effectiveType);
77139
+ attackingMoves.push({
77140
+ move,
77141
+ effectiveType
77142
+ });
77143
+ }
77144
+ members.push({
77145
+ entry,
77146
+ attackingMoves
77147
+ });
77148
+ }
77149
+ const attackingTypes = [];
77150
+ const typeJaMap = new Map(championsTypes.map((t) => [t.name, t.nameJa]));
77151
+ for (const typeName of attackingTypesSet) attackingTypes.push({
77152
+ type: typeName,
77153
+ nameJa: typeJaMap.get(typeName) ?? typeName
77154
+ });
77155
+ attackingTypes.sort((a, b) => a.type.localeCompare(b.type));
77156
+ const coverage = [];
77157
+ const uncoveredTypes = [];
77158
+ for (const defenderType of championsTypes) {
77159
+ let maxMultiplier = 0;
77160
+ const bestAttackers = [];
77161
+ for (const member of members) for (const { move, effectiveType } of member.attackingMoves) {
77162
+ const multiplier = getEffectivenessForDefenderType(effectiveType, defenderType.name, gen);
77163
+ const attacker = {
77164
+ pokemon: member.entry.name,
77165
+ move: move.name,
77166
+ multiplier
77167
+ };
77168
+ if (effectiveType !== move.type) attacker.effectiveType = effectiveType;
77169
+ maxMultiplier = updateBestAttackers(maxMultiplier, bestAttackers, attacker);
77170
+ }
77171
+ coverage.push({
77172
+ defenderType: defenderType.name,
77173
+ defenderTypeJa: defenderType.nameJa,
77174
+ maxMultiplier,
77175
+ bestAttackers
77176
+ });
77177
+ if (maxMultiplier <= 1) uncoveredTypes.push({
77178
+ type: defenderType.name,
77179
+ nameJa: defenderType.nameJa
77180
+ });
77181
+ }
77182
+ const dualTypeMap = buildRealDualTypeMap(championsPokemon);
77183
+ const dualTypeCoverage = [];
77184
+ let dualTypeUncoveredCount = 0;
77185
+ for (const { types, examplePokemon } of dualTypeMap.values()) {
77186
+ let maxMultiplier = 0;
77187
+ const bestAttackers = [];
77188
+ for (const member of members) for (const { move, effectiveType } of member.attackingMoves) {
77189
+ const multiplier = getEffectivenessForDualTypes(effectiveType, types, gen);
77190
+ const attacker = {
77191
+ pokemon: member.entry.name,
77192
+ move: move.name,
77193
+ multiplier
77194
+ };
77195
+ if (effectiveType !== move.type) attacker.effectiveType = effectiveType;
77196
+ maxMultiplier = updateBestAttackers(maxMultiplier, bestAttackers, attacker);
77197
+ }
77198
+ dualTypeCoverage.push({
77199
+ defenderTypes: types,
77200
+ defenderTypesJa: [typeJaMap.get(types[0]) ?? types[0], typeJaMap.get(types[1]) ?? types[1]],
77201
+ maxMultiplier,
77202
+ bestAttackers,
77203
+ examplePokemon
77204
+ });
77205
+ if (maxMultiplier <= 1) dualTypeUncoveredCount += 1;
77206
+ }
77207
+ dualTypeCoverage.sort((a, b) => {
77208
+ if (a.maxMultiplier !== b.maxMultiplier) return a.maxMultiplier - b.maxMultiplier;
77209
+ if (a.defenderTypes[0] !== b.defenderTypes[0]) return a.defenderTypes[0].localeCompare(b.defenderTypes[0]);
77210
+ return a.defenderTypes[1].localeCompare(b.defenderTypes[1]);
77211
+ });
77212
+ return {
77213
+ attackingTypes,
77214
+ coverage,
77215
+ uncoveredTypes,
77216
+ dualTypeCoverage,
77217
+ dualTypeUncoveredCount
77218
+ };
77219
+ }
77220
+ function registerPartyCoverageTool(server) {
77221
+ server.tool(TOOL_NAME$19, TOOL_DESCRIPTION$19, inputSchema$16, async (args) => {
77222
+ try {
77223
+ const output = analyzePartyCoverage(args);
77224
+ return { content: [{
77225
+ type: "text",
77226
+ text: JSON.stringify(output)
77227
+ }] };
77228
+ } catch (error) {
77229
+ const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
77230
+ return {
77231
+ content: [{
77232
+ type: "text",
77233
+ text: JSON.stringify({ error: message })
77234
+ }],
77235
+ isError: true
77236
+ };
77237
+ }
77238
+ });
77239
+ }
77240
+ //#endregion
77241
+ //#region src/tools/analysis/compare-parties.ts
77242
+ const CHAMPIONS_GEN_NUM$8 = 0;
77243
+ /** 対戦に組めるパーティメンバーの上限 (ポケモンチャンピオンズ仕様) */
77244
+ const MAX_PARTY_SIZE = 6;
77245
+ /** 性格未指定時の既定 (無補正性格) */
77246
+ const DEFAULT_NATURE_EN$1 = "Serious";
77247
+ const TOOL_NAME$18 = "compare_parties";
77248
+ const TOOL_DESCRIPTION$18 = "2 つのパーティ (A / B) の統計差分を比較する。メンバー差分・タイプ分布・弱点/耐性/カバレッジ集合・素早さ分布・種族値合計の構造化データを 1 コールで返す。 パーティ改修案の比較や入れ替え検討に使用する。優劣判定は行わず、差分データのみを返す (解釈は AI 側の責務)。 moves は指定できないため、カバレッジ差分は learnset 全攻撃技ベースで評価される。ポケモンチャンピオンズ対応。";
77249
+ const labelsSchema = z.object({
77250
+ partyA: z.string().optional(),
77251
+ partyB: z.string().optional()
77252
+ }).optional().describe("表示用ラベル (例: { partyA: '現行', partyB: '改修案' })");
77253
+ const inputSchema$15 = {
77254
+ partyA: z.array(pokemonSchema).min(1).max(MAX_PARTY_SIZE).describe("比較対象のパーティ A"),
77255
+ partyB: z.array(pokemonSchema).min(1).max(MAX_PARTY_SIZE).describe("比較対象のパーティ B"),
77256
+ labels: labelsSchema
77257
+ };
77258
+ /**
77259
+ * ポケモン名を pokemon.json のエントリに解決する。
77260
+ * 未登録名は類似候補付きエラーを投げる。
77261
+ */
77262
+ function resolvePokemonEntry$3(name) {
77263
+ const englishName = pokemonNameResolver.toEnglish(name) ?? (pokemonNameResolver.hasEnglishName(name) ? name : null);
77264
+ if (englishName === null) {
77265
+ const suggestions = pokemonNameResolver.suggestSimilar(name);
77266
+ const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
77267
+ throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
77268
+ }
77269
+ const entry = pokemonById.get(toDataId(englishName));
77270
+ if (entry === void 0) throw new Error(`ポケモン「${name}」のデータが見つかりません。`);
77271
+ return entry;
77272
+ }
77273
+ /**
77274
+ * 性格名を英語に解決する。省略時は無補正性格。
77275
+ */
77276
+ function resolveNatureName$1(nature) {
77277
+ if (nature === void 0) return DEFAULT_NATURE_EN$1;
77278
+ const englishName = natureNameResolver.toEnglish(nature);
77279
+ if (englishName !== void 0) return englishName;
77280
+ if (natureNameResolver.hasEnglishName(nature)) return nature;
77281
+ const suggestions = natureNameResolver.suggestSimilar(nature);
77282
+ const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
77283
+ throw new Error(`性格「${nature}」が見つかりません。${suggestionMessage}`);
77284
+ }
77285
+ /**
77286
+ * pokemon.json のエントリから @smogon/calc 用 overrides を組み立てる。
77287
+ */
77288
+ function buildSpeciesOverrides$1(entry) {
77289
+ return {
77290
+ types: entry.types,
77291
+ baseStats: entry.baseStats
77292
+ };
77293
+ }
77294
+ /**
77295
+ * 入力ポケモンの素早さ実数値を @smogon/calc で算出する。
77296
+ * ランク補正・状態異常は加味しない (build としての素早さ比較が目的のため)。
77297
+ */
77298
+ function calculateMemberSpeed(input, entry, gen) {
77299
+ const natureEn = resolveNatureName$1(input.nature);
77300
+ return new import_dist.Pokemon(gen, entry.name, {
77301
+ nature: natureEn,
77302
+ evs: { spe: input.evs?.spe ?? 0 },
77303
+ overrides: buildSpeciesOverrides$1(entry)
77304
+ }).stats.spe;
77305
+ }
77306
+ function toMemberRef(entry) {
77307
+ return {
77308
+ name: entry.name,
77309
+ nameJa: entry.nameJa ?? entry.name,
77310
+ types: [...entry.types],
77311
+ baseStatsTotal: baseStatsTotal(entry.baseStats)
77312
+ };
77313
+ }
77314
+ function resolveMembers(party) {
77315
+ return party.map((input) => {
77316
+ const entry = resolvePokemonEntry$3(input.name);
77317
+ return {
77318
+ input,
77319
+ entry,
77320
+ memberRef: toMemberRef(entry)
77321
+ };
77322
+ });
77323
+ }
77324
+ function partyBaseStatsTotal(members) {
77325
+ let total = 0;
77326
+ for (const m of members) total += m.memberRef.baseStatsTotal;
77327
+ return total;
77328
+ }
77329
+ function buildPartySummary(members, label, gen) {
77330
+ const speeds = members.map((m) => calculateMemberSpeed(m.input, m.entry, gen));
77331
+ return {
77332
+ label: label ?? null,
77333
+ members: members.map((m) => m.memberRef),
77334
+ baseStatsTotal: partyBaseStatsTotal(members),
77335
+ speedStats: computeNumericStats(speeds)
77336
+ };
77337
+ }
77338
+ function computeMemberDifferences(membersA, membersB) {
77339
+ const idsA = /* @__PURE__ */ new Map();
77340
+ for (const m of membersA) idsA.set(m.entry.id, m);
77341
+ const idsB = /* @__PURE__ */ new Map();
77342
+ for (const m of membersB) idsB.set(m.entry.id, m);
77343
+ const partyAOnly = [];
77344
+ const partyBOnly = [];
77345
+ const shared = [];
77346
+ for (const [id, member] of idsA) if (idsB.has(id)) shared.push(member.memberRef);
77347
+ else partyAOnly.push(member.memberRef);
77348
+ for (const [id, member] of idsB) if (!idsA.has(id)) partyBOnly.push(member.memberRef);
77349
+ return {
77350
+ partyAOnly,
77351
+ partyBOnly,
77352
+ shared
77353
+ };
77354
+ }
77355
+ function countTypes(members) {
77356
+ const counts = /* @__PURE__ */ new Map();
77357
+ for (const m of members) for (const t of m.entry.types) counts.set(t, (counts.get(t) ?? 0) + 1);
77358
+ return counts;
77359
+ }
77360
+ function computeTypeDistributionChanges(membersA, membersB) {
77361
+ const countsA = countTypes(membersA);
77362
+ const countsB = countTypes(membersB);
77363
+ const changes = [];
77364
+ for (const t of championsTypes) {
77365
+ const countA = countsA.get(t.name) ?? 0;
77366
+ const countB = countsB.get(t.name) ?? 0;
77367
+ changes.push({
77368
+ type: t.name,
77369
+ nameJa: t.nameJa,
77370
+ countA,
77371
+ countB,
77372
+ diff: countB - countA
77373
+ });
77374
+ }
77375
+ return changes;
77376
+ }
77377
+ function diffTypeSets(setA, setB) {
77378
+ const partyAOnly = [];
77379
+ const partyBOnly = [];
77380
+ const both = [];
77381
+ for (const type of setA) if (setB.has(type)) both.push(type);
77382
+ else partyAOnly.push(type);
77383
+ for (const type of setB) if (!setA.has(type)) partyBOnly.push(type);
77384
+ partyAOnly.sort();
77385
+ partyBOnly.sort();
77386
+ both.sort();
77387
+ return {
77388
+ partyAOnly,
77389
+ partyBOnly,
77390
+ both
77391
+ };
77392
+ }
77393
+ /**
77394
+ * パーティが抜群 (> 1 倍) を取れる防御タイプ集合。
77395
+ */
77396
+ function collectCoveredDefenderTypes(party) {
77397
+ const result = /* @__PURE__ */ new Set();
77398
+ const output = analyzePartyCoverage({ myParty: [...party] });
77399
+ for (const entry of output.coverage) if (entry.maxMultiplier > 1) result.add(entry.defenderType);
77400
+ return result;
77401
+ }
77402
+ function computeCoverageDiff(partyA, partyB) {
77403
+ const coveredA = collectCoveredDefenderTypes(partyA);
77404
+ const coveredB = collectCoveredDefenderTypes(partyB);
77405
+ const symmetric = diffTypeSets(coveredA, coveredB);
77406
+ const neither = [];
77407
+ for (const t of championsTypes) if (!coveredA.has(t.name) && !coveredB.has(t.name)) neither.push(t.name);
77408
+ neither.sort();
77409
+ return {
77410
+ ...symmetric,
77411
+ neither
77412
+ };
77413
+ }
77414
+ /**
77415
+ * パーティ比較の純関数。MCP ツールハンドラとテストから共通で利用する。
77416
+ */
77417
+ function comparePartiesAnalysis(args) {
77418
+ const gen = import_dist.Generations.get(CHAMPIONS_GEN_NUM$8);
77419
+ const membersA = resolveMembers(args.partyA);
77420
+ const membersB = resolveMembers(args.partyB);
77421
+ const partyASummary = buildPartySummary(membersA, args.labels?.partyA, gen);
77422
+ const partyBSummary = buildPartySummary(membersB, args.labels?.partyB, gen);
77423
+ const memberTypesA = membersA.map((m) => m.entry.types);
77424
+ const memberTypesB = membersB.map((m) => m.entry.types);
77425
+ const weaknessesA = collectPartyWeaknessTypes(memberTypesA, gen);
77426
+ const weaknessesB = collectPartyWeaknessTypes(memberTypesB, gen);
77427
+ const resistancesA = collectPartyResistanceTypes(memberTypesA, gen);
77428
+ const resistancesB = collectPartyResistanceTypes(memberTypesB, gen);
77429
+ return {
77430
+ partyA: partyASummary,
77431
+ partyB: partyBSummary,
77432
+ differences: {
77433
+ memberDifferences: computeMemberDifferences(membersA, membersB),
77434
+ typeDistribution: { changes: computeTypeDistributionChanges(membersA, membersB) },
77435
+ weaknesses: diffTypeSets(weaknessesA, weaknessesB),
77436
+ resistances: diffTypeSets(resistancesA, resistancesB),
77437
+ coverage: computeCoverageDiff(args.partyA, args.partyB),
77438
+ speedDistribution: {
77439
+ partyA: partyASummary.speedStats,
77440
+ partyB: partyBSummary.speedStats
77441
+ },
77442
+ baseStatsTotal: {
77443
+ partyA: partyASummary.baseStatsTotal,
77444
+ partyB: partyBSummary.baseStatsTotal,
77445
+ diff: partyBSummary.baseStatsTotal - partyASummary.baseStatsTotal
77446
+ }
77447
+ }
77448
+ };
77449
+ }
77450
+ function registerComparePartiesTool(server) {
77451
+ server.tool(TOOL_NAME$18, TOOL_DESCRIPTION$18, inputSchema$15, async (args) => {
77452
+ try {
77453
+ const output = comparePartiesAnalysis(args);
77454
+ return { content: [{
77455
+ type: "text",
77456
+ text: JSON.stringify(output)
77457
+ }] };
77458
+ } catch (error) {
77459
+ const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
77460
+ return {
77461
+ content: [{
77462
+ type: "text",
77463
+ text: JSON.stringify({ error: message })
77464
+ }],
77465
+ isError: true
77466
+ };
77467
+ }
77468
+ });
77469
+ }
77470
+ //#endregion
76553
77471
  //#region src/tools/info/condition-info.ts
76554
77472
  const TOOL_NAME$17 = "get_condition_info";
76555
77473
  const TOOL_DESCRIPTION$17 = "バトル条件(天候・フィールド・状態異常・サイド効果)の情報を取得する。category と name で絞り込める。省略時は全カテゴリ・全件を返す。ポケモンチャンピオンズ対応。";
@@ -76610,16 +77528,16 @@ const damageCalcInputSchema = {
76610
77528
  conditions: conditionsSchema.optional().describe("バトル条件")
76611
77529
  };
76612
77530
  const SINGLE_TOOL_NAME = "calculate_damage_single";
76613
- const SINGLE_TOOL_DESCRIPTION = "ポケモンのダメージ計算を行うツール。攻撃側ポケモンの指定した1技が防御側ポケモンに与えるダメージを計算する。ポケモンチャンピオンズ (Pokemon Champions) の対戦仕様に対応。重要: 能力ポイント(evs) は各ステ 0-32・合計 0-66 で指定すること (従来の努力値 252/510 上限ではない)。レベル 50・個体値 31 固定。育成データは省略可能で、省略時はデフォルト値で計算される。";
77531
+ const SINGLE_TOOL_DESCRIPTION = "ポケモンのダメージ計算を行うツール。攻撃側ポケモンの指定した1技が防御側ポケモンに与えるダメージを計算する。ポケモンチャンピオンズ (Pokemon Champions) の対戦仕様に対応。重要: 能力ポイント(evs) は各ステ 0-32・合計 0-66 で指定すること (従来の努力値 252/510 上限ではない)。レベル 50・個体値 31 固定。育成データは省略可能で、省略時はデフォルト値で計算される。正確な計算のため攻撃側・防御側の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
76614
77532
  const ALL_MOVES_TOOL_NAME = "calculate_damage_all_moves";
76615
- const ALL_MOVES_TOOL_DESCRIPTION = "ポケモン対戦で攻撃側ポケモンの全攻撃技のダメージを一括計算する。どの技が最も有効かを比較するときに使用する。ポケモンチャンピオンズ対応。";
77533
+ const ALL_MOVES_TOOL_DESCRIPTION = "ポケモン対戦で攻撃側ポケモンの全攻撃技のダメージを一括計算する。どの技が最も有効かを比較するときに使用する。ポケモンチャンピオンズ対応。正確な計算のため攻撃側・防御側の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
76616
77534
  const allMovesInputSchema = {
76617
77535
  attacker: pokemonSchema.describe("攻撃側ポケモン"),
76618
77536
  defender: pokemonSchema.describe("防御側ポケモン"),
76619
77537
  conditions: conditionsSchema.optional().describe("バトル条件")
76620
77538
  };
76621
77539
  const PARTY_MATCHUP_TOOL_NAME = "calculate_damage_party_matchup";
76622
- const PARTY_MATCHUP_TOOL_DESCRIPTION = "パーティ対パーティの全組み合わせダメージ計算を行う。6vs6の全対面での火力関係を一覧する。ポケモン対戦の選出判断やパーティ構築の検討に使用する。";
77540
+ const PARTY_MATCHUP_TOOL_DESCRIPTION = "パーティ対パーティの全組み合わせダメージ計算を行う。6vs6の全対面での火力関係を一覧する。ポケモン対戦の選出判断やパーティ構築の検討に使用する。正確な計算のため各ポケモンの ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
76623
77541
  const partyMatchupInputSchema = {
76624
77542
  myParty: z.array(pokemonSchema).describe("自分のパーティ"),
76625
77543
  opponentParty: z.array(pokemonSchema).describe("相手のパーティ"),
@@ -76746,7 +77664,7 @@ function registerDamageCalculationTools(server) {
76746
77664
  const SP_COARSE_STEP = 4;
76747
77665
  const SP_FINE_STEP = 1;
76748
77666
  const TOOL_NAME$16 = "analyze_damage_range";
76749
- const TOOL_DESCRIPTION$16 = "ダメージ計算を逆引きして、防御側を耐えさせるために必要な最小 SP 配分を探索する。`damage` には min/max ダメージと % を、`nHitKo` には確定 X 発の数を、`survivalSpConfig` には確定耐えに必要な最小 SP 配分を返す。ポケモンチャンピオンズ仕様(SP 各 0-32 / 合計 0-66)で計算。";
77667
+ const TOOL_DESCRIPTION$16 = "ダメージ計算を逆引きして、防御側を耐えさせるために必要な最小 SP 配分を探索する。`damage` には min/max ダメージと % を、`nHitKo` には確定 X 発の数を、`survivalSpConfig` には確定耐えに必要な最小 SP 配分を返す。ポケモンチャンピオンズ仕様(SP 各 0-32 / 合計 0-66)で計算。正確な計算のため攻撃側・防御側の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
76750
77668
  const inputSchema$13 = {
76751
77669
  attacker: pokemonSchema.describe("攻撃側ポケモン"),
76752
77670
  defender: pokemonSchema.describe("防御側ポケモン"),
@@ -76957,38 +77875,47 @@ function registerDamageRangeTool(server) {
76957
77875
  }
76958
77876
  //#endregion
76959
77877
  //#region src/tools/analysis/find-counters.ts
76960
- const CHAMPIONS_GEN_NUM$8 = 0;
76961
- /** 結果の最大件数 */
76962
- const TOP_N = 10;
76963
- /** スコア重み */
76964
- const SCORE_TYPE_ADVANTAGE = 5;
76965
- const SCORE_SPEED_WIN = 3;
76966
- const SCORE_LOW_INCOMING_DAMAGE = 3;
76967
- const SCORE_OHKO = 5;
76968
- const SCORE_2HKO = 2;
76969
- /** タイプ相性しきい値 */
77878
+ const CHAMPIONS_GEN_NUM$7 = 0;
77879
+ /** 弱点タイプ判定のしきい値(候補プール抽出で使用) */
76970
77880
  const SUPER_EFFECTIVE_MIN = 2;
76971
- const HALF_EFFECTIVE_MAX = .5;
76972
- const IMMUNITY_MULTIPLIER$2 = 0;
76973
- /** ダメージ割合(%)のしきい値 */
76974
- const LOW_INCOMING_DAMAGE_PERCENT_MAX = 30;
76975
- const OHKO_PERCENT_MIN = 100;
76976
- const TWO_HKO_PERCENT_MIN = 50;
76977
- /** 4 倍耐性以上(強耐性)しきい値: 0.25 */
76978
- const STRONG_RESIST_MAX = .25;
76979
77881
  /** Status 技 */
76980
- const STATUS_CATEGORY$3 = "Status";
77882
+ const STATUS_CATEGORY$2 = "Status";
76981
77883
  const TOOL_NAME$15 = "find_counters";
76982
- const TOOL_DESCRIPTION$15 = "指定したポケモンの対策候補を検索する。候補プール全体に対してダメ計と素早さ比較を行い、スコア順に上位 10 件を返す。`strategy` で対策パターン (speed_kill / tank_then_kill / type_wall) を識別する。ポケモンチャンピオンズ対応。";
77884
+ const TOOL_DESCRIPTION$15 = "target の弱点タイプ攻撃技を持つポケモンを候補プールとして抽出し、各候補の双方向ダメ計・素早さ・タイプ相性を返す。`candidatePool` は文字列(名前のみ)と PokemonInput オブジェクト(ability / item / nature / evs 指定)を混在可能で、同一ポケモンの build 違い比較にも対応する。正確な計算のため target 側の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。判断(受け型か速度勝ち型か等)は AI が行う前提。ポケモンチャンピオンズ対応。";
77885
+ const battleFormatValues = ["singles", "doubles"];
77886
+ const candidatePoolItemSchema = z.union([z.string(), pokemonSchema]);
76983
77887
  const inputSchema$12 = {
76984
77888
  target: pokemonSchema.describe("対策したい相手ポケモン"),
76985
- candidatePool: z.array(z.string()).optional().describe("候補プール(ポケモン名リスト)。未指定時は target の弱点タイプ攻撃技を覚える Champions 全ポケモンから選定。"),
76986
- battleFormat: z.enum(["singles", "doubles"]).optional().describe("対戦形式(省略時: singles)")
77889
+ candidatePool: z.array(candidatePoolItemSchema).optional().describe("候補プール。各要素は「ポケモン名の文字列(簡易指定、デフォルト build で評価)」または「PokemonInput オブジェクト(name に加え ability / item / nature / evs / boosts / status を指定可能)」。同じポケモン名でも build 違いを並列で比較できる。未指定時は target の弱点タイプ攻撃技を覚える Champions 全ポケモンから自動選定(デフォルト build 評価)。"),
77890
+ battleFormat: z.enum(battleFormatValues).optional().describe("対戦形式(省略時: singles)")
76987
77891
  };
76988
77892
  /**
77893
+ * extractPriorityMoves 用の move 解決。learnset ID から MoveEntry を引く。
77894
+ */
77895
+ function resolveMoveForPriority$1(id) {
77896
+ return movesById.get(id);
77897
+ }
77898
+ /**
77899
+ * extractPriorityMoves 用の日本語名解決。
77900
+ */
77901
+ function moveToJapanese$1(en) {
77902
+ return moveNameResolver.toJapanese(en);
77903
+ }
77904
+ /**
77905
+ * 指定ポケモン ID の learnset から先制技のみを抽出する。
77906
+ * learnset データが無い場合は空配列を返す。
77907
+ */
77908
+ function buildPriorityMoves(pokemonId) {
77909
+ return extractPriorityMoves({
77910
+ learnsetMoveIds: championsLearnsets[pokemonId] ?? [],
77911
+ resolveMove: resolveMoveForPriority$1,
77912
+ toJapanese: moveToJapanese$1
77913
+ });
77914
+ }
77915
+ /**
76989
77916
  * ポケモン名を pokemon.json のエントリに解決する。
76990
77917
  */
76991
- function resolvePokemonEntry$3(name) {
77918
+ function resolvePokemonEntry$2(name) {
76992
77919
  const englishName = pokemonNameResolver.toEnglish(name) ?? (pokemonNameResolver.hasEnglishName(name) ? name : null);
76993
77920
  if (englishName === null) {
76994
77921
  const suggestions = pokemonNameResolver.suggestSimilar(name);
@@ -77035,100 +77962,75 @@ function hasAttackingMoveOfAnyType(pokemonId, weaknessTypes) {
77035
77962
  for (const moveId of learnset) {
77036
77963
  const move = movesById.get(moveId);
77037
77964
  if (move === void 0) continue;
77038
- if (move.category === STATUS_CATEGORY$3) continue;
77965
+ if (move.category === STATUS_CATEGORY$2) continue;
77039
77966
  if (weaknessTypes.has(move.type)) return true;
77040
77967
  }
77041
77968
  return false;
77042
77969
  }
77043
77970
  /**
77044
- * DamageCalcResult 一覧から最大ダメ割合(max)の技を返す。
77045
- */
77046
- function pickBestMove(results) {
77047
- if (results.length === 0) return void 0;
77048
- let best = results[0];
77049
- for (const r of results) if (r.max > best.max) best = r;
77050
- return best;
77051
- }
77052
- /**
77053
- * 指定ポケモンの learnset に含まれる技 ID セットを取得する。
77054
- * 未登録のポケモンは空 Set を返す。
77055
- */
77056
- function getLearnsetMoveIdSet(pokemonId) {
77057
- const learnset = championsLearnsets[pokemonId];
77058
- if (learnset === void 0) return /* @__PURE__ */ new Set();
77059
- return new Set(learnset);
77060
- }
77061
- /**
77062
- * calculateAllMoves の結果を attacker の learnset で絞り込む。
77063
- * @smogon/calc は全技を走査するため、実際に覚えない技で過大評価しないようにフィルタする。
77064
- */
77065
- function filterResultsByLearnset(results, attackerPokemonId) {
77066
- const learnsetIds = getLearnsetMoveIdSet(attackerPokemonId);
77067
- if (learnsetIds.size === 0) return [...results];
77068
- return results.filter((r) => learnsetIds.has(toDataId(r.move)));
77069
- }
77070
- /**
77071
- * 被ダメージ % の最大値を元に LowIncoming 判定する。
77072
- */
77073
- function isLowIncomingDamage(incomingMaxPercent) {
77074
- return incomingMaxPercent <= LOW_INCOMING_DAMAGE_PERCENT_MAX;
77075
- }
77076
- /**
77077
- * 対策スコアを計算する。設計書の重みに従う。
77971
+ * ターゲットのタイプに対して弱点となるタイプ集合を算出する。
77078
77972
  */
77079
- function calcCounterScore(args) {
77080
- let score = 0;
77081
- if (args.typeAdvantage) score += SCORE_TYPE_ADVANTAGE;
77082
- if (args.speedAdvantage === "faster") score += SCORE_SPEED_WIN;
77083
- if (args.incomingMaxPercent !== null && isLowIncomingDamage(args.incomingMaxPercent)) score += SCORE_LOW_INCOMING_DAMAGE;
77084
- if (args.outgoingMaxPercent !== null) {
77085
- if (args.outgoingMaxPercent >= OHKO_PERCENT_MIN) score += SCORE_OHKO;
77086
- else if (args.outgoingMaxPercent >= TWO_HKO_PERCENT_MIN) score += SCORE_2HKO;
77087
- }
77088
- return score;
77973
+ function buildWeaknessTypeSet(targetTypes, gen) {
77974
+ const set = /* @__PURE__ */ new Set();
77975
+ for (const attackerType of championsTypes) if (calcMultiplier(attackerType.name, targetTypes, gen) >= SUPER_EFFECTIVE_MIN) set.add(attackerType.name);
77976
+ return set;
77089
77977
  }
77090
77978
  /**
77091
- * 戦略カテゴリを判定する。優先順: type_wall > speed_kill > tank_then_kill
77092
- * - type_wall: target からの攻撃を無効化 or 0.25 倍以下で受ける
77093
- * - speed_kill: 自分が先制 + 2 発以内で倒せる(OHKO or 2HKO)
77094
- * - tank_then_kill: 半減以下で受け + OHKO/2HKO
77095
- * それ以外はデフォルトで tank_then_kill 扱い(type_wall 未満の耐性 + 倒しきれる想定)。
77979
+ * PokemonInput から build 部分(name 以外)を抽出する。
77980
+ * 省略されたフィールドは含めない。
77096
77981
  */
77097
- function classifyStrategy(args) {
77098
- const canKillIn2 = args.outgoingMaxPercent !== null && args.outgoingMaxPercent >= TWO_HKO_PERCENT_MIN;
77099
- if (args.incomingMultiplier === IMMUNITY_MULTIPLIER$2 || args.incomingMultiplier <= STRONG_RESIST_MAX) return "type_wall";
77100
- if (args.speedAdvantage === "faster" && canKillIn2) return "speed_kill";
77101
- if (args.incomingMultiplier <= HALF_EFFECTIVE_MAX && canKillIn2) return "tank_then_kill";
77102
- return "tank_then_kill";
77982
+ function extractBuildInfo(input) {
77983
+ const build = {};
77984
+ if (input.ability !== void 0) build.ability = input.ability;
77985
+ if (input.item !== void 0) build.item = input.item;
77986
+ if (input.nature !== void 0) build.nature = input.nature;
77987
+ if (input.evs !== void 0) build.evs = input.evs;
77988
+ if (input.boosts !== void 0) build.boosts = input.boosts;
77989
+ if (input.status !== void 0) build.status = input.status;
77990
+ return build;
77103
77991
  }
77104
77992
  /**
77105
- * ターゲットのタイプに対して弱点となるタイプ集合を算出する。
77993
+ * 候補のソート用 tiebreaker として使う安定的な署名を生成する。
77994
+ * 同名ポケモンの build 違いを区別する。build 未指定(string or 自動選定)は "default" 扱い。
77106
77995
  */
77107
- function buildWeaknessTypeSet(targetTypes, gen) {
77108
- const set = /* @__PURE__ */ new Set();
77109
- for (const attackerType of championsTypes) if (calcMultiplier(attackerType.name, targetTypes, gen) >= SUPER_EFFECTIVE_MIN) set.add(attackerType.name);
77110
- return set;
77996
+ function buildSignature(candidate) {
77997
+ if (!candidate.hasExplicitBuild) return "default";
77998
+ return JSON.stringify(extractBuildInfo(candidate.input));
77111
77999
  }
77112
78000
  /**
77113
78001
  * 候補プールを決定する。
77114
- * - candidatePool 指定時: 名前解決して PokemonEntry 配列を返す。
77115
- * - 未指定時: target のタイプ弱点を攻撃技として持つ全 Champions ポケモンに絞る。
78002
+ * - candidatePool 指定時: 各要素(string or PokemonInput)を正規化して CandidateBuild 配列で返す。
78003
+ * - 未指定時: target のタイプ弱点を攻撃技として持つ全 Champions ポケモンに絞る(デフォルト build)。
77116
78004
  */
77117
78005
  function buildCandidateEntries(candidatePool, target, gen) {
77118
78006
  if (candidatePool !== void 0) {
77119
- const entries = [];
77120
- for (const name of candidatePool) entries.push(resolvePokemonEntry$3(name));
77121
- return entries;
78007
+ const candidates = [];
78008
+ for (const item of candidatePool) if (typeof item === "string") {
78009
+ const entry = resolvePokemonEntry$2(item);
78010
+ candidates.push({
78011
+ entry,
78012
+ input: { name: entry.name },
78013
+ hasExplicitBuild: false
78014
+ });
78015
+ } else {
78016
+ const entry = resolvePokemonEntry$2(item.name);
78017
+ candidates.push({
78018
+ entry,
78019
+ input: {
78020
+ ...item,
78021
+ name: entry.name
78022
+ },
78023
+ hasExplicitBuild: true
78024
+ });
78025
+ }
78026
+ return candidates;
77122
78027
  }
77123
78028
  const weaknessTypes = buildWeaknessTypeSet(target.types, gen);
77124
- if (weaknessTypes.size === 0) return [...championsPokemon].filter((p) => p.id !== target.id);
77125
- const candidates = [];
77126
- for (const entry of championsPokemon) {
77127
- if (entry.id === target.id) continue;
77128
- if (!hasAttackingMoveOfAnyType(entry.id, weaknessTypes)) continue;
77129
- candidates.push(entry);
77130
- }
77131
- return candidates;
78029
+ return (weaknessTypes.size === 0 ? [...championsPokemon].filter((p) => p.id !== target.id) : championsPokemon.filter((p) => p.id !== target.id && hasAttackingMoveOfAnyType(p.id, weaknessTypes))).map((entry) => ({
78030
+ entry,
78031
+ input: { name: entry.name },
78032
+ hasExplicitBuild: false
78033
+ }));
77132
78034
  }
77133
78035
  function registerFindCountersTool(server) {
77134
78036
  const calculator = new DamageCalculatorAdapter({
@@ -77140,8 +78042,9 @@ function registerFindCountersTool(server) {
77140
78042
  }, pokemonEntryProvider);
77141
78043
  server.tool(TOOL_NAME$15, TOOL_DESCRIPTION$15, inputSchema$12, async (args) => {
77142
78044
  try {
77143
- const gen = import_dist.Generations.get(CHAMPIONS_GEN_NUM$8);
77144
- const targetEntry = resolvePokemonEntry$3(args.target.name);
78045
+ const gen = import_dist.Generations.get(CHAMPIONS_GEN_NUM$7);
78046
+ const damageConditions = { battleFormat: args.battleFormat };
78047
+ const targetEntry = resolvePokemonEntry$2(args.target.name);
77145
78048
  const { pokemon: targetObj, resolvedName: targetName } = calculator.createPokemonObject(args.target);
77146
78049
  const targetNameJa = pokemonNameResolver.toJapanese(targetName) ?? targetName;
77147
78050
  const typeWeaknesses = findTypeWeaknesses(targetEntry.types, gen);
@@ -77153,10 +78056,11 @@ function registerFindCountersTool(server) {
77153
78056
  spd: targetObj.stats.spd,
77154
78057
  spe: targetObj.stats.spe
77155
78058
  };
77156
- const candidateEntries = buildCandidateEntries(args.candidatePool, targetEntry, gen);
78059
+ const candidateBuilds = buildCandidateEntries(args.candidatePool, targetEntry, gen);
77157
78060
  const counterEntries = [];
77158
- for (const candidate of candidateEntries) {
77159
- const candidateInput = { name: candidate.name };
78061
+ for (const candidate of candidateBuilds) {
78062
+ const candidateEntry = candidate.entry;
78063
+ const candidateInput = candidate.input;
77160
78064
  let candidateObj;
77161
78065
  try {
77162
78066
  candidateObj = calculator.createPokemonObject(candidateInput).pokemon;
@@ -77168,101 +78072,55 @@ function registerFindCountersTool(server) {
77168
78072
  try {
77169
78073
  outgoing = filterResultsByLearnset(calculator.calculateAllMoves({
77170
78074
  attacker: candidateInput,
77171
- defender: args.target
77172
- }), candidate.id);
78075
+ defender: args.target,
78076
+ conditions: damageConditions
78077
+ }), getLearnsetMoveIdSet(candidateEntry.id), toDataId);
77173
78078
  } catch {
77174
78079
  outgoing = [];
77175
78080
  }
77176
78081
  try {
77177
78082
  incoming = filterResultsByLearnset(calculator.calculateAllMoves({
77178
78083
  attacker: args.target,
77179
- defender: candidateInput
77180
- }), targetEntry.id);
78084
+ defender: candidateInput,
78085
+ conditions: damageConditions
78086
+ }), getLearnsetMoveIdSet(targetEntry.id), toDataId);
77181
78087
  } catch {
77182
78088
  incoming = [];
77183
78089
  }
77184
- const bestOutgoing = pickBestMove(outgoing);
77185
- const bestIncoming = pickBestMove(incoming);
77186
- const speedAdvantage = compareSpeed(candidateObj.stats.spe, targetObj.stats.spe);
77187
- const outgoingMaxPercent = bestOutgoing !== void 0 ? bestOutgoing.maxPercent : null;
77188
- const incomingMaxPercent = bestIncoming !== void 0 ? bestIncoming.maxPercent : null;
77189
- let typeAdvantage = false;
77190
- if (bestOutgoing !== void 0) {
77191
- const outMoveEntry = movesById.get(toDataId(bestOutgoing.move));
77192
- if (outMoveEntry !== void 0) {
77193
- if (calcMultiplier(outMoveEntry.type, targetEntry.types, gen) >= SUPER_EFFECTIVE_MIN) typeAdvantage = true;
77194
- }
77195
- }
77196
- let incomingMultiplier = 1;
77197
- if (bestIncoming !== void 0) {
77198
- const inMoveEntry = movesById.get(toDataId(bestIncoming.move));
77199
- if (inMoveEntry !== void 0) incomingMultiplier = calcMultiplier(inMoveEntry.type, candidate.types, gen);
77200
- }
77201
- const score = calcCounterScore({
77202
- typeAdvantage,
77203
- speedAdvantage,
77204
- incomingMaxPercent,
77205
- outgoingMaxPercent
77206
- });
77207
- const strategy = classifyStrategy({
77208
- incomingMultiplier,
77209
- outgoingMaxPercent,
77210
- speedAdvantage
77211
- });
77212
- const nameJa = candidate.nameJa ?? candidate.name;
77213
- const details = { speedAdvantage };
77214
- if (bestOutgoing !== void 0) {
77215
- const outMoveEntry = movesById.get(toDataId(bestOutgoing.move));
77216
- const outNameJa = moveNameResolver.toJapanese(bestOutgoing.move) ?? bestOutgoing.move;
77217
- details.bestMove = {
77218
- name: bestOutgoing.move,
77219
- nameJa: outNameJa,
77220
- type: outMoveEntry?.type ?? "",
77221
- expectedDamagePercent: {
77222
- min: bestOutgoing.minPercent,
77223
- max: bestOutgoing.maxPercent
77224
- }
77225
- };
77226
- }
77227
- if (bestIncoming !== void 0) {
77228
- const inMoveEntry = movesById.get(toDataId(bestIncoming.move));
77229
- const inNameJa = moveNameResolver.toJapanese(bestIncoming.move) ?? bestIncoming.move;
77230
- details.incomingBestMove = {
77231
- name: bestIncoming.move,
77232
- nameJa: inNameJa,
77233
- type: inMoveEntry?.type ?? "",
77234
- receivedDamagePercent: {
77235
- min: bestIncoming.minPercent,
77236
- max: bestIncoming.maxPercent
77237
- }
77238
- };
77239
- }
78090
+ const speedCompare = compareSpeed(candidateObj.stats.spe, targetObj.stats.spe);
78091
+ const nameJa = candidateEntry.nameJa ?? candidateEntry.name;
78092
+ const pokemonProfile = {
78093
+ id: candidateEntry.id,
78094
+ name: candidateEntry.name,
78095
+ nameJa,
78096
+ types: [...candidateEntry.types],
78097
+ baseStats: { ...candidateEntry.baseStats },
78098
+ abilities: [...candidateEntry.abilities]
78099
+ };
78100
+ if (candidate.hasExplicitBuild) pokemonProfile.build = extractBuildInfo(candidateInput);
77240
78101
  counterEntries.push({
77241
- pokemon: {
77242
- id: candidate.id,
77243
- name: candidate.name,
77244
- nameJa,
77245
- types: [...candidate.types],
77246
- baseStats: { ...candidate.baseStats },
77247
- abilities: [...candidate.abilities]
77248
- },
77249
- strategy,
77250
- score,
77251
- details
78102
+ pokemon: pokemonProfile,
78103
+ speedCompare,
78104
+ outgoing,
78105
+ incoming,
78106
+ priorityMoves: buildPriorityMoves(candidateEntry.id),
78107
+ sortKey: buildSignature(candidate)
77252
78108
  });
77253
78109
  }
77254
78110
  counterEntries.sort((a, b) => {
77255
- if (b.score !== a.score) return b.score - a.score;
77256
- return a.pokemon.name.localeCompare(b.pokemon.name);
78111
+ const nameOrder = a.pokemon.name.localeCompare(b.pokemon.name);
78112
+ if (nameOrder !== 0) return nameOrder;
78113
+ return a.sortKey.localeCompare(b.sortKey);
77257
78114
  });
77258
78115
  const output = {
77259
78116
  target: {
77260
78117
  name: targetName,
77261
78118
  nameJa: targetNameJa,
77262
78119
  stats: targetStats,
77263
- typeWeaknesses
78120
+ typeWeaknesses,
78121
+ priorityMoves: buildPriorityMoves(targetEntry.id)
77264
78122
  },
77265
- counters: counterEntries.slice(0, TOP_N)
78123
+ counters: counterEntries.map(({ sortKey: _sortKey, ...rest }) => rest)
77266
78124
  };
77267
78125
  return { content: [{
77268
78126
  type: "text",
@@ -77281,10 +78139,864 @@ function registerFindCountersTool(server) {
77281
78139
  });
77282
78140
  }
77283
78141
  //#endregion
78142
+ //#region src/party-store.ts
78143
+ /** ai-rotom の永続化用ディレクトリ名 (ホーム直下)。 */
78144
+ const AI_ROTOM_DIR_NAME = ".ai-rotom";
78145
+ /** パーティ永続化ファイル名。 */
78146
+ const PARTIES_FILE_NAME = "parties.json";
78147
+ /** atomic write 用の一時ファイル拡張子。 */
78148
+ const TEMP_FILE_EXT = ".tmp";
78149
+ /** JSON.stringify の indent。 */
78150
+ const JSON_INDENT = 2;
78151
+ /** 一時ファイル名用のランダムサフィックスバイト数。 */
78152
+ const TEMP_SUFFIX_BYTES = 8;
78153
+ /**
78154
+ * 永続化ファイル (`~/.ai-rotom/parties.json`) の絶対パスを返す。
78155
+ * ホームディレクトリが解決できない場合はエラーを投げる。
78156
+ */
78157
+ function resolvePartiesFilePath() {
78158
+ const home = homedir();
78159
+ if (home === "" || home === void 0 || home === null) throw new Error("ホームディレクトリが解決できませんでした。$HOME 環境変数を確認してください。");
78160
+ return join(home, AI_ROTOM_DIR_NAME, PARTIES_FILE_NAME);
78161
+ }
78162
+ /**
78163
+ * 永続化ファイルの読み込み結果。
78164
+ * 存在しない場合は空の PartiesFile を返す。
78165
+ * 破損・権限・schemaVersion 不整合の場合はエラーを投げる。
78166
+ */
78167
+ function loadPartiesFile(filePath = resolvePartiesFilePath()) {
78168
+ let raw;
78169
+ try {
78170
+ raw = readFileSync(filePath, { encoding: "utf-8" });
78171
+ } catch (error) {
78172
+ if (isNodeErrnoException(error) && error.code === "ENOENT") return {
78173
+ schemaVersion: 1,
78174
+ parties: []
78175
+ };
78176
+ throw wrapIoError("パーティファイルの読み込みに失敗しました", error);
78177
+ }
78178
+ let parsed;
78179
+ try {
78180
+ parsed = JSON.parse(raw);
78181
+ } catch (error) {
78182
+ const cause = error instanceof Error ? error.message : String(error);
78183
+ throw new Error(`パーティファイル (${filePath}) の JSON パースに失敗しました: ${cause}`);
78184
+ }
78185
+ const result = partiesFileSchema.safeParse(parsed);
78186
+ if (!result.success) {
78187
+ const issues = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
78188
+ throw new Error(`パーティファイル (${filePath}) のスキーマ検証に失敗しました: ${issues}`);
78189
+ }
78190
+ if (result.data.schemaVersion !== 1) throw new Error(`未対応の schemaVersion (${result.data.schemaVersion}) です。現行は 1 です。`);
78191
+ return result.data;
78192
+ }
78193
+ /**
78194
+ * 永続化ファイルを atomic に書き込む。
78195
+ * 親ディレクトリが存在しない場合は作成する。
78196
+ * 一時ファイル → rename で置き換えるため、途中失敗でも元ファイルは壊れない。
78197
+ */
78198
+ function savePartiesFile(data, filePath = resolvePartiesFilePath()) {
78199
+ const validated = partiesFileSchema.parse(data);
78200
+ const dir = dirname(filePath);
78201
+ try {
78202
+ mkdirSync(dir, { recursive: true });
78203
+ } catch (error) {
78204
+ throw wrapIoError(`パーティ保存ディレクトリ (${dir}) の作成に失敗しました`, error);
78205
+ }
78206
+ const tempPath = `${filePath}.${randomBytes(TEMP_SUFFIX_BYTES).toString("hex")}${TEMP_FILE_EXT}`;
78207
+ const serialized = JSON.stringify(validated, null, JSON_INDENT);
78208
+ try {
78209
+ writeFileSync(tempPath, serialized, {
78210
+ encoding: "utf-8",
78211
+ mode: 384
78212
+ });
78213
+ renameSync(tempPath, filePath);
78214
+ } catch (error) {
78215
+ try {
78216
+ rmSync(tempPath, { force: true });
78217
+ } catch {}
78218
+ throw wrapIoError(`パーティファイル (${filePath}) の保存に失敗しました`, error);
78219
+ }
78220
+ }
78221
+ function isNodeErrnoException(value) {
78222
+ return value instanceof Error && typeof value.code === "string";
78223
+ }
78224
+ function wrapIoError(prefix, error) {
78225
+ const message = error instanceof Error ? error.message : String(error);
78226
+ const code = isNodeErrnoException(error) && error.code !== void 0 ? ` [${error.code}]` : "";
78227
+ return /* @__PURE__ */ new Error(`${prefix}${code}: ${message}`);
78228
+ }
78229
+ //#endregion
78230
+ //#region ../../node_modules/@pokesol/pokesol-text-parser-ts/dist/parser.js
78231
+ var ASTKinds;
78232
+ (function(ASTKinds) {
78233
+ ASTKinds["POKESOL_TEXT"] = "POKESOL_TEXT";
78234
+ ASTKinds["POKESOL_TEXT_$0_1"] = "POKESOL_TEXT_$0_1";
78235
+ ASTKinds["POKESOL_TEXT_$0_2"] = "POKESOL_TEXT_$0_2";
78236
+ ASTKinds["POKESOL_TEXT_$1"] = "POKESOL_TEXT_$1";
78237
+ ASTKinds["POKESOL_TEXT_$2"] = "POKESOL_TEXT_$2";
78238
+ ASTKinds["POKESOL_TEXT_$3"] = "POKESOL_TEXT_$3";
78239
+ ASTKinds["POKEMON_AND_ITEM_LINE"] = "POKEMON_AND_ITEM_LINE";
78240
+ ASTKinds["POKEMON_LINE"] = "POKEMON_LINE";
78241
+ ASTKinds["POKEMON_VALUE"] = "POKEMON_VALUE";
78242
+ ASTKinds["ITEM_VALUE"] = "ITEM_VALUE";
78243
+ ASTKinds["TERATYPE_LINE"] = "TERATYPE_LINE";
78244
+ ASTKinds["TERATYPE_VALUE"] = "TERATYPE_VALUE";
78245
+ ASTKinds["ABILITY_LINE"] = "ABILITY_LINE";
78246
+ ASTKinds["ABILITY_LINE_$0"] = "ABILITY_LINE_$0";
78247
+ ASTKinds["ABILITY_VALUE"] = "ABILITY_VALUE";
78248
+ ASTKinds["NATURE_LINE"] = "NATURE_LINE";
78249
+ ASTKinds["NATURE_VALUE"] = "NATURE_VALUE";
78250
+ ASTKinds["STATS_LINE"] = "STATS_LINE";
78251
+ ASTKinds["STATS"] = "STATS";
78252
+ ASTKinds["STAT_1"] = "STAT_1";
78253
+ ASTKinds["STAT_2"] = "STAT_2";
78254
+ ASTKinds["ACTUAL_AND_EFFORT"] = "ACTUAL_AND_EFFORT";
78255
+ ASTKinds["ACTUAL"] = "ACTUAL";
78256
+ ASTKinds["ACTUAL_VALUE"] = "ACTUAL_VALUE";
78257
+ ASTKinds["EFFORT_VALUE"] = "EFFORT_VALUE";
78258
+ ASTKinds["MOVES_LINE_1"] = "MOVES_LINE_1";
78259
+ ASTKinds["MOVES_LINE_2"] = "MOVES_LINE_2";
78260
+ ASTKinds["MOVES_LINE_3"] = "MOVES_LINE_3";
78261
+ ASTKinds["MOVES_LINE_4"] = "MOVES_LINE_4";
78262
+ ASTKinds["MOVES_FOUR"] = "MOVES_FOUR";
78263
+ ASTKinds["MOVES_THREE"] = "MOVES_THREE";
78264
+ ASTKinds["MOVES_TWO"] = "MOVES_TWO";
78265
+ ASTKinds["MOVES_ONE"] = "MOVES_ONE";
78266
+ ASTKinds["MOVE_VALUE"] = "MOVE_VALUE";
78267
+ ASTKinds["_"] = "_";
78268
+ })(ASTKinds || (ASTKinds = {}));
78269
+ var Parser = class {
78270
+ input;
78271
+ pos;
78272
+ negating = false;
78273
+ memoSafe = true;
78274
+ constructor(input) {
78275
+ this.pos = {
78276
+ overallPos: 0,
78277
+ line: 1,
78278
+ offset: 0
78279
+ };
78280
+ this.input = input;
78281
+ }
78282
+ reset(pos) {
78283
+ this.pos = pos;
78284
+ }
78285
+ finished() {
78286
+ return this.pos.overallPos === this.input.length;
78287
+ }
78288
+ clearMemos() {}
78289
+ matchPOKESOL_TEXT($$dpth, $$cr) {
78290
+ return this.run($$dpth, () => {
78291
+ let $scope$line1;
78292
+ let $scope$line2;
78293
+ let $scope$line3;
78294
+ let $scope$line4;
78295
+ let $scope$line5;
78296
+ let $scope$line6;
78297
+ let $$res = null;
78298
+ if (($scope$line1 = this.matchPOKESOL_TEXT_$0($$dpth + 1, $$cr)) !== null && this.regexAccept(String.raw`(?:\n+)`, "", $$dpth + 1, $$cr) !== null && (($scope$line2 = this.matchPOKESOL_TEXT_$1($$dpth + 1, $$cr)) || true) && ($scope$line3 = this.matchABILITY_LINE($$dpth + 1, $$cr)) !== null && this.regexAccept(String.raw`(?:\n+)`, "", $$dpth + 1, $$cr) !== null && ($scope$line4 = this.matchNATURE_LINE($$dpth + 1, $$cr)) !== null && (($scope$line5 = this.matchPOKESOL_TEXT_$2($$dpth + 1, $$cr)) || true) && (($scope$line6 = this.matchPOKESOL_TEXT_$3($$dpth + 1, $$cr)) || true)) $$res = {
78299
+ kind: ASTKinds.POKESOL_TEXT,
78300
+ line1: $scope$line1,
78301
+ line2: $scope$line2,
78302
+ line3: $scope$line3,
78303
+ line4: $scope$line4,
78304
+ line5: $scope$line5,
78305
+ line6: $scope$line6
78306
+ };
78307
+ return $$res;
78308
+ });
78309
+ }
78310
+ matchPOKESOL_TEXT_$0($$dpth, $$cr) {
78311
+ return this.choice([() => this.matchPOKESOL_TEXT_$0_1($$dpth + 1, $$cr), () => this.matchPOKESOL_TEXT_$0_2($$dpth + 1, $$cr)]);
78312
+ }
78313
+ matchPOKESOL_TEXT_$0_1($$dpth, $$cr) {
78314
+ return this.matchPOKEMON_AND_ITEM_LINE($$dpth + 1, $$cr);
78315
+ }
78316
+ matchPOKESOL_TEXT_$0_2($$dpth, $$cr) {
78317
+ return this.matchPOKEMON_LINE($$dpth + 1, $$cr);
78318
+ }
78319
+ matchPOKESOL_TEXT_$1($$dpth, $$cr) {
78320
+ return this.run($$dpth, () => {
78321
+ let $scope$body;
78322
+ let $$res = null;
78323
+ if (($scope$body = this.matchTERATYPE_LINE($$dpth + 1, $$cr)) !== null && this.regexAccept(String.raw`(?:\n+)`, "", $$dpth + 1, $$cr) !== null) $$res = {
78324
+ kind: ASTKinds.POKESOL_TEXT_$1,
78325
+ body: $scope$body
78326
+ };
78327
+ return $$res;
78328
+ });
78329
+ }
78330
+ matchPOKESOL_TEXT_$2($$dpth, $$cr) {
78331
+ return this.run($$dpth, () => {
78332
+ let $scope$body;
78333
+ let $$res = null;
78334
+ if (this.regexAccept(String.raw`(?:\n+)`, "", $$dpth + 1, $$cr) !== null && ($scope$body = this.matchSTATS_LINE($$dpth + 1, $$cr)) !== null) $$res = {
78335
+ kind: ASTKinds.POKESOL_TEXT_$2,
78336
+ body: $scope$body
78337
+ };
78338
+ return $$res;
78339
+ });
78340
+ }
78341
+ matchPOKESOL_TEXT_$3($$dpth, $$cr) {
78342
+ return this.run($$dpth, () => {
78343
+ let $scope$body;
78344
+ let $$res = null;
78345
+ if (this.regexAccept(String.raw`(?:\n+)`, "", $$dpth + 1, $$cr) !== null && ($scope$body = this.matchMOVES_LINE($$dpth + 1, $$cr)) !== null) $$res = {
78346
+ kind: ASTKinds.POKESOL_TEXT_$3,
78347
+ body: $scope$body
78348
+ };
78349
+ return $$res;
78350
+ });
78351
+ }
78352
+ matchPOKEMON_AND_ITEM_LINE($$dpth, $$cr) {
78353
+ return this.run($$dpth, () => {
78354
+ let $scope$pokemon;
78355
+ let $scope$item;
78356
+ let $$res = null;
78357
+ if (($scope$pokemon = this.matchPOKEMON_VALUE($$dpth + 1, $$cr)) !== null && this.match_($$dpth + 1, $$cr) !== null && this.regexAccept(String.raw`(?:@)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && ($scope$item = this.matchITEM_VALUE($$dpth + 1, $$cr)) !== null) $$res = {
78358
+ kind: ASTKinds.POKEMON_AND_ITEM_LINE,
78359
+ pokemon: $scope$pokemon,
78360
+ item: $scope$item
78361
+ };
78362
+ return $$res;
78363
+ });
78364
+ }
78365
+ matchPOKEMON_LINE($$dpth, $$cr) {
78366
+ return this.run($$dpth, () => {
78367
+ let $scope$pokemon;
78368
+ let $$res = null;
78369
+ if (($scope$pokemon = this.matchPOKEMON_VALUE($$dpth + 1, $$cr)) !== null) $$res = {
78370
+ kind: ASTKinds.POKEMON_LINE,
78371
+ pokemon: $scope$pokemon
78372
+ };
78373
+ return $$res;
78374
+ });
78375
+ }
78376
+ matchPOKEMON_VALUE($$dpth, $$cr) {
78377
+ return this.regexAccept(String.raw`(?:[0-90-9a-zA-ZA-Zぁ-んァ-ヶー一-龠・()♂♀%]+)`, "", $$dpth + 1, $$cr);
78378
+ }
78379
+ matchITEM_VALUE($$dpth, $$cr) {
78380
+ return this.regexAccept(String.raw`(?:[ぁ-んァ-ヶー]+)`, "", $$dpth + 1, $$cr);
78381
+ }
78382
+ matchTERATYPE_LINE($$dpth, $$cr) {
78383
+ return this.run($$dpth, () => {
78384
+ let $scope$teratype;
78385
+ let $$res = null;
78386
+ if (this.regexAccept(String.raw`(?:テラスタイプ)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && this.regexAccept(String.raw`(?::)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && ($scope$teratype = this.matchTERATYPE_VALUE($$dpth + 1, $$cr)) !== null) $$res = {
78387
+ kind: ASTKinds.TERATYPE_LINE,
78388
+ teratype: $scope$teratype
78389
+ };
78390
+ return $$res;
78391
+ });
78392
+ }
78393
+ matchTERATYPE_VALUE($$dpth, $$cr) {
78394
+ return this.regexAccept(String.raw`(?:[ぁ-んァ-ヶー]*)`, "", $$dpth + 1, $$cr);
78395
+ }
78396
+ matchABILITY_LINE($$dpth, $$cr) {
78397
+ return this.run($$dpth, () => {
78398
+ let $scope$ability;
78399
+ let $scope$preMega;
78400
+ let $$res = null;
78401
+ if (this.regexAccept(String.raw`(?:特性)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && this.regexAccept(String.raw`(?::)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && (($scope$ability = this.matchABILITY_VALUE($$dpth + 1, $$cr)) || true) && this.match_($$dpth + 1, $$cr) !== null && (($scope$preMega = this.matchABILITY_LINE_$0($$dpth + 1, $$cr)) || true)) $$res = {
78402
+ kind: ASTKinds.ABILITY_LINE,
78403
+ ability: $scope$ability,
78404
+ preMega: $scope$preMega
78405
+ };
78406
+ return $$res;
78407
+ });
78408
+ }
78409
+ matchABILITY_LINE_$0($$dpth, $$cr) {
78410
+ return this.run($$dpth, () => {
78411
+ let $scope$body;
78412
+ let $$res = null;
78413
+ if (this.regexAccept(String.raw`(?:\()`, "", $$dpth + 1, $$cr) !== null && ($scope$body = this.matchABILITY_VALUE($$dpth + 1, $$cr)) !== null && this.regexAccept(String.raw`(?:\))`, "", $$dpth + 1, $$cr) !== null) $$res = {
78414
+ kind: ASTKinds.ABILITY_LINE_$0,
78415
+ body: $scope$body
78416
+ };
78417
+ return $$res;
78418
+ });
78419
+ }
78420
+ matchABILITY_VALUE($$dpth, $$cr) {
78421
+ return this.regexAccept(String.raw`(?:[ぁ-んァ-ヶー]+)`, "", $$dpth + 1, $$cr);
78422
+ }
78423
+ matchNATURE_LINE($$dpth, $$cr) {
78424
+ return this.run($$dpth, () => {
78425
+ let $scope$nature;
78426
+ let $$res = null;
78427
+ if (this.regexAccept(String.raw`(?:能力補正)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && this.regexAccept(String.raw`(?::)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && (($scope$nature = this.matchNATURE_VALUE($$dpth + 1, $$cr)) || true)) $$res = {
78428
+ kind: ASTKinds.NATURE_LINE,
78429
+ nature: $scope$nature
78430
+ };
78431
+ return $$res;
78432
+ });
78433
+ }
78434
+ matchNATURE_VALUE($$dpth, $$cr) {
78435
+ return this.regexAccept(String.raw`(?:[ぁ-ん]+)`, "", $$dpth + 1, $$cr);
78436
+ }
78437
+ matchSTATS_LINE($$dpth, $$cr) {
78438
+ return this.run($$dpth, () => {
78439
+ let $scope$stats;
78440
+ let $$res = null;
78441
+ if (($scope$stats = this.matchSTATS($$dpth + 1, $$cr)) !== null) $$res = {
78442
+ kind: ASTKinds.STATS_LINE,
78443
+ stats: $scope$stats
78444
+ };
78445
+ return $$res;
78446
+ });
78447
+ }
78448
+ matchSTATS($$dpth, $$cr) {
78449
+ return this.run($$dpth, () => {
78450
+ let $scope$h;
78451
+ let $scope$a;
78452
+ let $scope$b;
78453
+ let $scope$c;
78454
+ let $scope$d;
78455
+ let $scope$s;
78456
+ let $$res = null;
78457
+ if (($scope$h = this.matchSTAT($$dpth + 1, $$cr)) !== null && this.regexAccept(String.raw`(?:-)`, "", $$dpth + 1, $$cr) !== null && ($scope$a = this.matchSTAT($$dpth + 1, $$cr)) !== null && this.regexAccept(String.raw`(?:-)`, "", $$dpth + 1, $$cr) !== null && ($scope$b = this.matchSTAT($$dpth + 1, $$cr)) !== null && this.regexAccept(String.raw`(?:-)`, "", $$dpth + 1, $$cr) !== null && ($scope$c = this.matchSTAT($$dpth + 1, $$cr)) !== null && this.regexAccept(String.raw`(?:-)`, "", $$dpth + 1, $$cr) !== null && ($scope$d = this.matchSTAT($$dpth + 1, $$cr)) !== null && this.regexAccept(String.raw`(?:-)`, "", $$dpth + 1, $$cr) !== null && ($scope$s = this.matchSTAT($$dpth + 1, $$cr)) !== null) $$res = {
78458
+ kind: ASTKinds.STATS,
78459
+ h: $scope$h,
78460
+ a: $scope$a,
78461
+ b: $scope$b,
78462
+ c: $scope$c,
78463
+ d: $scope$d,
78464
+ s: $scope$s
78465
+ };
78466
+ return $$res;
78467
+ });
78468
+ }
78469
+ matchSTAT($$dpth, $$cr) {
78470
+ return this.choice([() => this.matchSTAT_1($$dpth + 1, $$cr), () => this.matchSTAT_2($$dpth + 1, $$cr)]);
78471
+ }
78472
+ matchSTAT_1($$dpth, $$cr) {
78473
+ return this.matchACTUAL_AND_EFFORT($$dpth + 1, $$cr);
78474
+ }
78475
+ matchSTAT_2($$dpth, $$cr) {
78476
+ return this.matchACTUAL($$dpth + 1, $$cr);
78477
+ }
78478
+ matchACTUAL_AND_EFFORT($$dpth, $$cr) {
78479
+ return this.run($$dpth, () => {
78480
+ let $scope$actual;
78481
+ let $scope$effort;
78482
+ let $$res = null;
78483
+ if (($scope$actual = this.matchACTUAL_VALUE($$dpth + 1, $$cr)) !== null && this.regexAccept(String.raw`(?:\()`, "", $$dpth + 1, $$cr) !== null && ($scope$effort = this.matchEFFORT_VALUE($$dpth + 1, $$cr)) !== null && this.regexAccept(String.raw`(?:\))`, "", $$dpth + 1, $$cr) !== null) $$res = {
78484
+ kind: ASTKinds.ACTUAL_AND_EFFORT,
78485
+ actual: $scope$actual,
78486
+ effort: $scope$effort
78487
+ };
78488
+ return $$res;
78489
+ });
78490
+ }
78491
+ matchACTUAL($$dpth, $$cr) {
78492
+ return this.run($$dpth, () => {
78493
+ let $scope$actual;
78494
+ let $$res = null;
78495
+ if (($scope$actual = this.matchACTUAL_VALUE($$dpth + 1, $$cr)) !== null) $$res = {
78496
+ kind: ASTKinds.ACTUAL,
78497
+ actual: $scope$actual
78498
+ };
78499
+ return $$res;
78500
+ });
78501
+ }
78502
+ matchACTUAL_VALUE($$dpth, $$cr) {
78503
+ return this.regexAccept(String.raw`(?:[1-9][0-9]*)`, "", $$dpth + 1, $$cr);
78504
+ }
78505
+ matchEFFORT_VALUE($$dpth, $$cr) {
78506
+ return this.regexAccept(String.raw`(?:[1-9][0-9]*)`, "", $$dpth + 1, $$cr);
78507
+ }
78508
+ matchMOVES_LINE($$dpth, $$cr) {
78509
+ return this.choice([
78510
+ () => this.matchMOVES_LINE_1($$dpth + 1, $$cr),
78511
+ () => this.matchMOVES_LINE_2($$dpth + 1, $$cr),
78512
+ () => this.matchMOVES_LINE_3($$dpth + 1, $$cr),
78513
+ () => this.matchMOVES_LINE_4($$dpth + 1, $$cr)
78514
+ ]);
78515
+ }
78516
+ matchMOVES_LINE_1($$dpth, $$cr) {
78517
+ return this.matchMOVES_FOUR($$dpth + 1, $$cr);
78518
+ }
78519
+ matchMOVES_LINE_2($$dpth, $$cr) {
78520
+ return this.matchMOVES_THREE($$dpth + 1, $$cr);
78521
+ }
78522
+ matchMOVES_LINE_3($$dpth, $$cr) {
78523
+ return this.matchMOVES_TWO($$dpth + 1, $$cr);
78524
+ }
78525
+ matchMOVES_LINE_4($$dpth, $$cr) {
78526
+ return this.matchMOVES_ONE($$dpth + 1, $$cr);
78527
+ }
78528
+ matchMOVES_FOUR($$dpth, $$cr) {
78529
+ return this.run($$dpth, () => {
78530
+ let $scope$move1;
78531
+ let $scope$move2;
78532
+ let $scope$move3;
78533
+ let $scope$move4;
78534
+ let $$res = null;
78535
+ if (($scope$move1 = this.matchMOVE_VALUE($$dpth + 1, $$cr)) !== null && this.match_($$dpth + 1, $$cr) !== null && this.regexAccept(String.raw`(?:/)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && ($scope$move2 = this.matchMOVE_VALUE($$dpth + 1, $$cr)) !== null && this.match_($$dpth + 1, $$cr) !== null && this.regexAccept(String.raw`(?:/)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && ($scope$move3 = this.matchMOVE_VALUE($$dpth + 1, $$cr)) !== null && this.match_($$dpth + 1, $$cr) !== null && this.regexAccept(String.raw`(?:/)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && ($scope$move4 = this.matchMOVE_VALUE($$dpth + 1, $$cr)) !== null) $$res = {
78536
+ kind: ASTKinds.MOVES_FOUR,
78537
+ move1: $scope$move1,
78538
+ move2: $scope$move2,
78539
+ move3: $scope$move3,
78540
+ move4: $scope$move4
78541
+ };
78542
+ return $$res;
78543
+ });
78544
+ }
78545
+ matchMOVES_THREE($$dpth, $$cr) {
78546
+ return this.run($$dpth, () => {
78547
+ let $scope$move1;
78548
+ let $scope$move2;
78549
+ let $scope$move3;
78550
+ let $$res = null;
78551
+ if (($scope$move1 = this.matchMOVE_VALUE($$dpth + 1, $$cr)) !== null && this.match_($$dpth + 1, $$cr) !== null && this.regexAccept(String.raw`(?:/)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && ($scope$move2 = this.matchMOVE_VALUE($$dpth + 1, $$cr)) !== null && this.match_($$dpth + 1, $$cr) !== null && this.regexAccept(String.raw`(?:/)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && ($scope$move3 = this.matchMOVE_VALUE($$dpth + 1, $$cr)) !== null) $$res = {
78552
+ kind: ASTKinds.MOVES_THREE,
78553
+ move1: $scope$move1,
78554
+ move2: $scope$move2,
78555
+ move3: $scope$move3
78556
+ };
78557
+ return $$res;
78558
+ });
78559
+ }
78560
+ matchMOVES_TWO($$dpth, $$cr) {
78561
+ return this.run($$dpth, () => {
78562
+ let $scope$move1;
78563
+ let $scope$move2;
78564
+ let $$res = null;
78565
+ if (($scope$move1 = this.matchMOVE_VALUE($$dpth + 1, $$cr)) !== null && this.match_($$dpth + 1, $$cr) !== null && this.regexAccept(String.raw`(?:/)`, "", $$dpth + 1, $$cr) !== null && this.match_($$dpth + 1, $$cr) !== null && ($scope$move2 = this.matchMOVE_VALUE($$dpth + 1, $$cr)) !== null) $$res = {
78566
+ kind: ASTKinds.MOVES_TWO,
78567
+ move1: $scope$move1,
78568
+ move2: $scope$move2
78569
+ };
78570
+ return $$res;
78571
+ });
78572
+ }
78573
+ matchMOVES_ONE($$dpth, $$cr) {
78574
+ return this.run($$dpth, () => {
78575
+ let $scope$move1;
78576
+ let $$res = null;
78577
+ if (($scope$move1 = this.matchMOVE_VALUE($$dpth + 1, $$cr)) !== null) $$res = {
78578
+ kind: ASTKinds.MOVES_ONE,
78579
+ move1: $scope$move1
78580
+ };
78581
+ return $$res;
78582
+ });
78583
+ }
78584
+ matchMOVE_VALUE($$dpth, $$cr) {
78585
+ return this.regexAccept(String.raw`(?:[0-9A-Zぁ-んァ-ヶー・]+)`, "", $$dpth + 1, $$cr);
78586
+ }
78587
+ match_($$dpth, $$cr) {
78588
+ return this.regexAccept(String.raw`(?:[ \t]*)`, "", $$dpth + 1, $$cr);
78589
+ }
78590
+ test() {
78591
+ const mrk = this.mark();
78592
+ const ans = this.matchPOKESOL_TEXT(0) !== null;
78593
+ this.reset(mrk);
78594
+ return ans;
78595
+ }
78596
+ parse() {
78597
+ const mrk = this.mark();
78598
+ const res = this.matchPOKESOL_TEXT(0);
78599
+ if (res) return {
78600
+ ast: res,
78601
+ errs: []
78602
+ };
78603
+ this.reset(mrk);
78604
+ const rec = new ErrorTracker();
78605
+ this.clearMemos();
78606
+ this.matchPOKESOL_TEXT(0, rec);
78607
+ const err = rec.getErr();
78608
+ return {
78609
+ ast: res,
78610
+ errs: err !== null ? [err] : []
78611
+ };
78612
+ }
78613
+ mark() {
78614
+ return this.pos;
78615
+ }
78616
+ loopPlus(func) {
78617
+ return this.loop(func, 1, -1);
78618
+ }
78619
+ loop(func, lb, ub) {
78620
+ const mrk = this.mark();
78621
+ const res = [];
78622
+ while (ub === -1 || res.length < ub) {
78623
+ const preMrk = this.mark();
78624
+ const t = func();
78625
+ if (t === null || this.pos.overallPos === preMrk.overallPos) break;
78626
+ res.push(t);
78627
+ }
78628
+ if (res.length >= lb) return res;
78629
+ this.reset(mrk);
78630
+ return null;
78631
+ }
78632
+ run($$dpth, fn) {
78633
+ const mrk = this.mark();
78634
+ const res = fn();
78635
+ if (res !== null) return res;
78636
+ this.reset(mrk);
78637
+ return null;
78638
+ }
78639
+ choice(fns) {
78640
+ for (const f of fns) {
78641
+ const res = f();
78642
+ if (res !== null) return res;
78643
+ }
78644
+ return null;
78645
+ }
78646
+ regexAccept(match, mods, dpth, cr) {
78647
+ return this.run(dpth, () => {
78648
+ const reg = new RegExp(match, "y" + mods);
78649
+ const mrk = this.mark();
78650
+ reg.lastIndex = mrk.overallPos;
78651
+ const res = this.tryConsume(reg);
78652
+ if (cr) cr.record(mrk, res, {
78653
+ kind: "RegexMatch",
78654
+ literal: match.substring(3, match.length - 1),
78655
+ negated: this.negating
78656
+ });
78657
+ return res;
78658
+ });
78659
+ }
78660
+ tryConsume(reg) {
78661
+ const res = reg.exec(this.input);
78662
+ if (res) {
78663
+ let lineJmp = 0;
78664
+ let lind = -1;
78665
+ for (let i = 0; i < res[0].length; ++i) if (res[0][i] === "\n") {
78666
+ ++lineJmp;
78667
+ lind = i;
78668
+ }
78669
+ this.pos = {
78670
+ overallPos: reg.lastIndex,
78671
+ line: this.pos.line + lineJmp,
78672
+ offset: lind === -1 ? this.pos.offset + res[0].length : res[0].length - lind - 1
78673
+ };
78674
+ return res[0];
78675
+ }
78676
+ return null;
78677
+ }
78678
+ noConsume(fn) {
78679
+ const mrk = this.mark();
78680
+ const res = fn();
78681
+ this.reset(mrk);
78682
+ return res;
78683
+ }
78684
+ negate(fn) {
78685
+ const mrk = this.mark();
78686
+ const oneg = this.negating;
78687
+ this.negating = !oneg;
78688
+ const res = fn();
78689
+ this.negating = oneg;
78690
+ this.reset(mrk);
78691
+ return res === null ? true : null;
78692
+ }
78693
+ memoise(rule, memo) {
78694
+ const $scope$pos = this.mark();
78695
+ const $scope$memoRes = memo.get($scope$pos.overallPos);
78696
+ if (this.memoSafe && $scope$memoRes !== void 0) {
78697
+ this.reset($scope$memoRes[1]);
78698
+ return $scope$memoRes[0];
78699
+ }
78700
+ const $scope$result = rule();
78701
+ if (this.memoSafe) memo.set($scope$pos.overallPos, [$scope$result, this.mark()]);
78702
+ return $scope$result;
78703
+ }
78704
+ };
78705
+ function parse$1(s) {
78706
+ return new Parser(s).parse();
78707
+ }
78708
+ var SyntaxErr = class {
78709
+ pos;
78710
+ expmatches;
78711
+ constructor(pos, expmatches) {
78712
+ this.pos = pos;
78713
+ this.expmatches = [...expmatches];
78714
+ }
78715
+ toString() {
78716
+ return `Syntax Error at line ${this.pos.line}:${this.pos.offset}. Expected one of ${this.expmatches.map((x) => x.kind === "EOF" ? " EOF" : ` ${x.negated ? "not " : ""}'${x.literal}'`)}`;
78717
+ }
78718
+ };
78719
+ var ErrorTracker = class {
78720
+ mxpos = {
78721
+ overallPos: -1,
78722
+ line: -1,
78723
+ offset: -1
78724
+ };
78725
+ regexset = /* @__PURE__ */ new Set();
78726
+ pmatches = [];
78727
+ record(pos, result, att) {
78728
+ if (result === null === att.negated) return;
78729
+ if (pos.overallPos > this.mxpos.overallPos) {
78730
+ this.mxpos = pos;
78731
+ this.pmatches = [];
78732
+ this.regexset.clear();
78733
+ }
78734
+ if (this.mxpos.overallPos === pos.overallPos) if (att.kind === "RegexMatch") {
78735
+ if (!this.regexset.has(att.literal)) this.pmatches.push(att);
78736
+ this.regexset.add(att.literal);
78737
+ } else this.pmatches.push(att);
78738
+ }
78739
+ getErr() {
78740
+ if (this.mxpos.overallPos !== -1) return new SyntaxErr(this.mxpos, this.pmatches);
78741
+ return null;
78742
+ }
78743
+ };
78744
+ //#endregion
78745
+ //#region ../../node_modules/@pokesol/pokesol-text-parser-ts/dist/index.js
78746
+ const parse = (pokesolText) => {
78747
+ const result = parse$1(chomp(pokesolText));
78748
+ if (!result.ast) throw new Error(`Failed to parse Pokesol Text: ${JSON.stringify(result.errs)}`);
78749
+ const pokemonName = result.ast.line1.pokemon;
78750
+ const itemName = result.ast.line1.kind === ASTKinds.POKEMON_AND_ITEM_LINE ? result.ast.line1.item : null;
78751
+ const terastalName = result.ast.line2?.body.teratype || null;
78752
+ const abilityName = result.ast.line3.ability || null;
78753
+ const preMegaAbilityName = result.ast.line3.preMega?.body || null;
78754
+ const natureName = result.ast.line4.nature || null;
78755
+ const evs = {
78756
+ hp: 0,
78757
+ attack: 0,
78758
+ defense: 0,
78759
+ specialAttack: 0,
78760
+ specialDefense: 0,
78761
+ speed: 0
78762
+ };
78763
+ const actualValue = {
78764
+ hp: null,
78765
+ attack: null,
78766
+ defense: null,
78767
+ specialAttack: null,
78768
+ specialDefense: null,
78769
+ speed: null
78770
+ };
78771
+ if (result.ast.line5 !== null) {
78772
+ evs.hp = result.ast.line5.body.stats.h.kind === ASTKinds.ACTUAL_AND_EFFORT ? Number(result.ast.line5.body.stats.h.effort) : 0;
78773
+ evs.attack = result.ast.line5.body.stats.a.kind === ASTKinds.ACTUAL_AND_EFFORT ? Number(result.ast.line5.body.stats.a.effort) : 0;
78774
+ evs.defense = result.ast.line5.body.stats.b.kind === ASTKinds.ACTUAL_AND_EFFORT ? Number(result.ast.line5.body.stats.b.effort) : 0;
78775
+ evs.specialAttack = result.ast.line5.body.stats.c.kind === ASTKinds.ACTUAL_AND_EFFORT ? Number(result.ast.line5.body.stats.c.effort) : 0;
78776
+ evs.specialDefense = result.ast.line5.body.stats.d.kind === ASTKinds.ACTUAL_AND_EFFORT ? Number(result.ast.line5.body.stats.d.effort) : 0;
78777
+ evs.speed = result.ast.line5.body.stats.s.kind === ASTKinds.ACTUAL_AND_EFFORT ? Number(result.ast.line5.body.stats.s.effort) : 0;
78778
+ actualValue.hp = Number(result.ast.line5.body.stats.h.actual);
78779
+ actualValue.attack = Number(result.ast.line5.body.stats.a.actual);
78780
+ actualValue.defense = Number(result.ast.line5.body.stats.b.actual);
78781
+ actualValue.specialAttack = Number(result.ast.line5.body.stats.c.actual);
78782
+ actualValue.specialDefense = Number(result.ast.line5.body.stats.d.actual);
78783
+ actualValue.speed = Number(result.ast.line5.body.stats.s.actual);
78784
+ }
78785
+ const moveNames = [];
78786
+ if (result.ast.line6 !== null) {
78787
+ if (result.ast.line6.body.kind === ASTKinds.MOVES_FOUR) {
78788
+ moveNames.push(result.ast.line6.body.move1);
78789
+ moveNames.push(result.ast.line6.body.move2);
78790
+ moveNames.push(result.ast.line6.body.move3);
78791
+ moveNames.push(result.ast.line6.body.move4);
78792
+ } else if (result.ast.line6.body.kind === ASTKinds.MOVES_THREE) {
78793
+ moveNames.push(result.ast.line6.body.move1);
78794
+ moveNames.push(result.ast.line6.body.move2);
78795
+ moveNames.push(result.ast.line6.body.move3);
78796
+ } else if (result.ast.line6.body.kind === ASTKinds.MOVES_TWO) {
78797
+ moveNames.push(result.ast.line6.body.move1);
78798
+ moveNames.push(result.ast.line6.body.move2);
78799
+ } else if (result.ast.line6.body.kind === ASTKinds.MOVES_ONE) moveNames.push(result.ast.line6.body.move1);
78800
+ }
78801
+ return {
78802
+ pokemonName,
78803
+ itemName,
78804
+ abilityName,
78805
+ preMegaAbilityName,
78806
+ terastalName,
78807
+ natureName,
78808
+ evs,
78809
+ actualValue,
78810
+ moveNames
78811
+ };
78812
+ };
78813
+ const chomp = (text) => {
78814
+ return text.split("\n").map((line) => line.split("//")[0]).map((line) => line.trim()).filter((line) => line.length > 0).join("\n");
78815
+ };
78816
+ //#endregion
78817
+ //#region src/party-text.ts
78818
+ /** ポケソルテキストで性格を省略した場合のデフォルト。 */
78819
+ const DEFAULT_NATURE_NAME = "まじめ";
78820
+ /**
78821
+ * ポケソルテキストを空行区切りで個別ブロックに分割する。
78822
+ * 改行 (LF / CRLF) のどちらにも対応する。
78823
+ * 空白のみのブロックは除外する。
78824
+ */
78825
+ function splitPokesolTextBlocks(text) {
78826
+ return text.replace(/\r\n/g, "\n").split(/\n\s*\n/).map((block) => block.trim()).filter((block) => block.length > 0);
78827
+ }
78828
+ /**
78829
+ * パーサー出力 (`PokesolTextParseReult`) を `PartyMember` に変換する。
78830
+ * - メガ前特性 (`preMegaAbilityName`) が存在すればそれを `ability` として保存
78831
+ * (通常状態の特性が基本。メガ進化時の特性変化は計算側の責務)
78832
+ * - `natureName` が null の場合は `DEFAULT_NATURE_NAME` で補完
78833
+ * - `terastalName` が存在する場合はポケチャン未対応のため無視
78834
+ * - `moveNames` が空配列の場合は `moves` フィールド自体を省く
78835
+ *
78836
+ * 補完・無視を行った場合はブロック番号付きの warnings を返す。
78837
+ */
78838
+ function mapPokesolResultToPartyMember(result, blockNumber) {
78839
+ const warnings = [];
78840
+ if (result.pokemonName === null || result.pokemonName === "") throw new Error(`ブロック ${blockNumber}: ポケモン名が読み取れませんでした。`);
78841
+ const member = { name: result.pokemonName };
78842
+ if (result.itemName !== null) member.item = result.itemName;
78843
+ if (result.preMegaAbilityName !== null) {
78844
+ member.ability = result.preMegaAbilityName;
78845
+ if (result.abilityName !== null && result.abilityName !== result.preMegaAbilityName) warnings.push(`ブロック ${blockNumber}: メガ進化特性「${result.abilityName}」は無視し、メガ前特性「${result.preMegaAbilityName}」を ability として保存しました。`);
78846
+ } else if (result.abilityName !== null) member.ability = result.abilityName;
78847
+ if (result.natureName !== null) member.nature = result.natureName;
78848
+ else {
78849
+ member.nature = DEFAULT_NATURE_NAME;
78850
+ warnings.push(`ブロック ${blockNumber}: 性格が省略されていたためデフォルト「${DEFAULT_NATURE_NAME}」を補完しました。`);
78851
+ }
78852
+ if (result.terastalName !== null && result.terastalName !== "") warnings.push(`ブロック ${blockNumber}: テラスタイプ「${result.terastalName}」はポケモンチャンピオンズ未対応のため無視しました。`);
78853
+ const evs = buildEvsFromResult(result.evs);
78854
+ if (evs !== void 0) member.evs = evs;
78855
+ if (result.moveNames.length > 0) member.moves = [...result.moveNames];
78856
+ else warnings.push(`ブロック ${blockNumber}: 技行が省略されていたため moves を空で登録しました。`);
78857
+ return {
78858
+ member,
78859
+ warnings
78860
+ };
78861
+ }
78862
+ /**
78863
+ * パーサー出力の SP (努力値フィールド) を `EvsInput` に変換する。
78864
+ * 全て 0 の場合は undefined を返し、`PartyMember.evs` を省く。
78865
+ */
78866
+ function buildEvsFromResult(parserEvs) {
78867
+ const mapped = {
78868
+ hp: parserEvs.hp,
78869
+ atk: parserEvs.attack,
78870
+ def: parserEvs.defense,
78871
+ spa: parserEvs.specialAttack,
78872
+ spd: parserEvs.specialDefense,
78873
+ spe: parserEvs.speed
78874
+ };
78875
+ return Object.values(mapped).some((value) => value !== void 0 && value !== 0) ? mapped : void 0;
78876
+ }
78877
+ //#endregion
78878
+ //#region src/tools/party/import-party-from-text.ts
78879
+ const TOOL_NAME$14 = "import_party_from_text";
78880
+ const TOOL_DESCRIPTION$14 = "ポケソルテキスト (Showdown 風に 1 匹あたり 3〜6 行・複数匹は空行区切り) からパーティを一括取り込みして保存する (upsert)。各メンバーはポケモン名 / 特性 / 性格 / 技 / 持ち物をポケチャン内の既知データと照合する。エラーがある場合は部分保存せず全体を失敗させる。";
78881
+ /** ポケソルテキスト入力の最大文字数 (6 匹 × 数百文字 + メモ想定)。 */
78882
+ const MAX_POKESOL_TEXT_LENGTH = 8e3;
78883
+ const defaultNowProvider$1 = () => /* @__PURE__ */ new Date();
78884
+ const defaultStoreIO$1 = {
78885
+ load: () => loadPartiesFile(),
78886
+ save: (data) => savePartiesFile(data)
78887
+ };
78888
+ const inputSchema$11 = {
78889
+ text: z.string().min(1, { message: "ポケソルテキストは 1 文字以上で指定してください。" }).max(MAX_POKESOL_TEXT_LENGTH, { message: `ポケソルテキストは ${MAX_POKESOL_TEXT_LENGTH} 文字以下で指定してください。` }).describe("ポケソルテキスト。1 匹あたり 3〜6 行 (ポケモン名[@持ち物] / テラスタイプ行 省略可 / 特性 / 能力補正 / 実数値(SP) 省略可 / 技 省略可)。複数匹は空行で区切る。"),
78890
+ name: z.string().min(1, { message: "パーティ名は 1 文字以上で指定してください。" }).max(50, { message: `パーティ名は 50 文字以下で指定してください。` }).describe("保存名 (識別子。同名は上書き)。"),
78891
+ memo: z.string().max(MAX_PARTY_MEMO_LENGTH, { message: `メモは ${MAX_PARTY_MEMO_LENGTH} 文字以下で指定してください。` }).optional().describe("構築メモ (自由記述)。")
78892
+ };
78893
+ function toErrorResponse$1(error) {
78894
+ const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
78895
+ return {
78896
+ content: [{
78897
+ type: "text",
78898
+ text: JSON.stringify({ error: message })
78899
+ }],
78900
+ isError: true
78901
+ };
78902
+ }
78903
+ function toTextResponse$1(value) {
78904
+ return { content: [{
78905
+ type: "text",
78906
+ text: JSON.stringify(value)
78907
+ }] };
78908
+ }
78909
+ /**
78910
+ * NameResolver の既知名 (日英どちらでも) として存在するかを判定する。
78911
+ * 未知の場合は類似候補付きのメッセージを投げる。
78912
+ */
78913
+ function assertKnownName(resolver, name, label, blockNumber) {
78914
+ if (resolver.hasJapaneseName(name) || resolver.hasEnglishName(name)) return;
78915
+ const suggestions = resolver.suggestSimilar(name, 3);
78916
+ const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
78917
+ throw new Error(`ブロック ${blockNumber}: ${label}「${name}」が見つかりません。${suggestionMessage}`);
78918
+ }
78919
+ /**
78920
+ * PartyMember の各名前フィールドを NameResolver で検証する。
78921
+ * 未知名があれば該当ブロックのエラーとして throw。
78922
+ */
78923
+ function validateMemberNames(member, blockNumber) {
78924
+ assertKnownName(pokemonNameResolver, member.name, "ポケモン名", blockNumber);
78925
+ if (member.nature !== void 0) assertKnownName(natureNameResolver, member.nature, "性格", blockNumber);
78926
+ if (member.ability !== void 0) assertKnownName(abilityNameResolver, member.ability, "特性", blockNumber);
78927
+ if (member.item !== void 0) assertKnownName(itemNameResolver, member.item, "持ち物", blockNumber);
78928
+ if (member.moves !== void 0) for (const move of member.moves) assertKnownName(moveNameResolver, move, "技", blockNumber);
78929
+ }
78930
+ /**
78931
+ * 本ツールの全処理 (split → parse → map → validate → persist) を実行する。
78932
+ * テストから直接呼び出せるようエクスポートする。
78933
+ */
78934
+ function runImportPartyFromText(input, deps = {}) {
78935
+ const storeIO = deps.storeIO ?? defaultStoreIO$1;
78936
+ const now = deps.now ?? defaultNowProvider$1;
78937
+ const blocks = splitPokesolTextBlocks(input.text);
78938
+ if (blocks.length < 1) throw new Error(`パーティには 1 匹以上を含めてください (検出: ${blocks.length} 匹)。`);
78939
+ if (blocks.length > 6) throw new Error(`パーティには 6 匹までしか含められません (検出: ${blocks.length} 匹)。`);
78940
+ const warnings = [];
78941
+ const members = [];
78942
+ blocks.forEach((block, index) => {
78943
+ const blockNumber = index + 1;
78944
+ let parsed;
78945
+ try {
78946
+ parsed = parse(block);
78947
+ } catch (error) {
78948
+ const reason = error instanceof Error ? error.message : String(error);
78949
+ throw new Error(`ブロック ${blockNumber} のパースに失敗しました: ${reason}`);
78950
+ }
78951
+ const mapped = mapPokesolResultToPartyMember(parsed, blockNumber);
78952
+ validateMemberNames(mapped.member, blockNumber);
78953
+ members.push(mapped.member);
78954
+ warnings.push(...mapped.warnings);
78955
+ });
78956
+ const file = storeIO.load();
78957
+ const existingIndex = file.parties.findIndex((p) => p.name === input.name);
78958
+ const nowIso = now().toISOString();
78959
+ const createdAt = existingIndex >= 0 ? file.parties[existingIndex].createdAt : nowIso;
78960
+ const party = {
78961
+ name: input.name,
78962
+ members,
78963
+ createdAt,
78964
+ updatedAt: nowIso
78965
+ };
78966
+ if (input.memo !== void 0) party.memo = input.memo;
78967
+ partySchema.parse(party);
78968
+ const nextParties = [...file.parties];
78969
+ if (existingIndex >= 0) nextParties[existingIndex] = party;
78970
+ else nextParties.push(party);
78971
+ storeIO.save({
78972
+ schemaVersion: 1,
78973
+ parties: nextParties
78974
+ });
78975
+ return {
78976
+ saved: true,
78977
+ party,
78978
+ warnings,
78979
+ filePath: resolvePartiesFilePath(),
78980
+ overwrote: existingIndex >= 0
78981
+ };
78982
+ }
78983
+ /**
78984
+ * import_party_from_text ツールをサーバーに登録する。
78985
+ */
78986
+ function registerImportPartyFromTextTool(server, deps = {}) {
78987
+ server.tool(TOOL_NAME$14, TOOL_DESCRIPTION$14, inputSchema$11, async (args) => {
78988
+ try {
78989
+ return toTextResponse$1(runImportPartyFromText(args, deps));
78990
+ } catch (error) {
78991
+ return toErrorResponse$1(error);
78992
+ }
78993
+ });
78994
+ }
78995
+ //#endregion
77284
78996
  //#region src/tools/info/item-info.ts
77285
- const TOOL_NAME$14 = "get_item_info";
77286
- const TOOL_DESCRIPTION$14 = "ポケモンの持ち物(アイテム)の詳細情報(効果説明、メガストーン情報)を取得する。ポケモンチャンピオンズで使える持ち物のみ返す。パーティ構築で持ち物を選ぶ際に使用する。";
77287
- const inputSchema$11 = { name: z.string().describe("持ち物名(日本語 or 英語)") };
78997
+ const TOOL_NAME$13 = "get_item_info";
78998
+ const TOOL_DESCRIPTION$13 = "ポケモンの持ち物(アイテム)の詳細情報(効果説明、メガストーン情報)を取得する。ポケモンチャンピオンズで使える持ち物のみ返す。パーティ構築で持ち物を選ぶ際に使用する。";
78999
+ const inputSchema$10 = { name: z.string().describe("持ち物名(日本語 or 英語)") };
77288
79000
  /**
77289
79001
  * 持ち物名を英語に解決する。日本語名・英語名どちらでも受け付ける。
77290
79002
  */
@@ -77297,7 +79009,7 @@ function resolveItemNameEn(input) {
77297
79009
  throw new Error(`持ち物「${input}」が見つかりません。${suggestionMessage}`);
77298
79010
  }
77299
79011
  function registerItemInfoTool(server) {
77300
- server.tool(TOOL_NAME$14, TOOL_DESCRIPTION$14, inputSchema$11, async (args) => {
79012
+ server.tool(TOOL_NAME$13, TOOL_DESCRIPTION$13, inputSchema$10, async (args) => {
77301
79013
  try {
77302
79014
  const itemId = toDataId(resolveItemNameEn(args.name));
77303
79015
  const entry = itemsById.get(itemId);
@@ -77330,9 +79042,9 @@ function registerItemInfoTool(server) {
77330
79042
  }
77331
79043
  //#endregion
77332
79044
  //#region src/tools/info/learnset.ts
77333
- const TOOL_NAME$13 = "get_learnset";
77334
- const TOOL_DESCRIPTION$13 = "ポケモンチャンピオンズで特定のポケモンが覚える技の一覧を取得する。パーティ構築や技構成の検討に使用する。チャンピオンズ固有の技プール変更(没収技等)を反映。";
77335
- const inputSchema$10 = { name: z.string().describe("ポケモン名(日本語 or 英語)") };
79045
+ const TOOL_NAME$12 = "get_learnset";
79046
+ const TOOL_DESCRIPTION$12 = "ポケモンチャンピオンズで特定のポケモンが覚える技の一覧を取得する。パーティ構築や技構成の検討に使用する。チャンピオンズ固有の技プール変更(没収技等)を反映。";
79047
+ const inputSchema$9 = { name: z.string().describe("ポケモン名(日本語 or 英語)") };
77336
79048
  /**
77337
79049
  * ポケモン名を英語に解決する。日本語名・英語名どちらでも受け付ける。
77338
79050
  */
@@ -77360,7 +79072,7 @@ function buildLearnsetMoveEntry(moveId) {
77360
79072
  };
77361
79073
  }
77362
79074
  function registerLearnsetTool(server) {
77363
- server.tool(TOOL_NAME$13, TOOL_DESCRIPTION$13, inputSchema$10, async (args) => {
79075
+ server.tool(TOOL_NAME$12, TOOL_DESCRIPTION$12, inputSchema$9, async (args) => {
77364
79076
  try {
77365
79077
  const englishName = resolvePokemonNameEn(args.name);
77366
79078
  const moveIds = championsLearnsets[toDataId(englishName)];
@@ -77388,13 +79100,40 @@ function registerLearnsetTool(server) {
77388
79100
  }
77389
79101
  //#endregion
77390
79102
  //#region src/tools/analysis/matchup.ts
77391
- const TOOL_NAME$12 = "analyze_matchup";
77392
- const TOOL_DESCRIPTION$12 = "ポケモン2体の対面を分析する。双方向のダメージ計算と素早さ比較を行い、どちらが有利かを判断するためのデータを提供する。ポケモン対戦の対面判断に使用する。";
79103
+ const TOOL_NAME$11 = "analyze_matchup";
79104
+ const TOOL_DESCRIPTION$11 = "ポケモン2体の対面を分析する。双方向のダメージ計算と素早さ比較を行い、どちらが有利かを判断するためのデータを提供する。ポケモン対戦の対面判断に使用する。pokemon1Faster は静的な素早さ実数値のみの比較のため、素早さ負けでも先制技で逆転できる判断は pokemon{1,2}PriorityMoves を併用すること。正確な計算のため双方の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
77393
79105
  const matchupInputSchema = {
77394
79106
  pokemon1: pokemonSchema.describe("ポケモン1"),
77395
79107
  pokemon2: pokemonSchema.describe("ポケモン2"),
77396
79108
  conditions: conditionsSchema.optional().describe("バトル条件")
77397
79109
  };
79110
+ function resolveMoveForPriority(id) {
79111
+ return movesById.get(id);
79112
+ }
79113
+ function moveToJapanese(en) {
79114
+ return moveNameResolver.toJapanese(en);
79115
+ }
79116
+ function priorityMovesFor(resolvedName) {
79117
+ return extractPriorityMoves({
79118
+ learnsetMoveIds: championsLearnsets[toDataId(resolvedName)] ?? [],
79119
+ resolveMove: resolveMoveForPriority,
79120
+ toJapanese: moveToJapanese
79121
+ });
79122
+ }
79123
+ /**
79124
+ * 攻撃側タイプ配列から防御側タイプ配列への最大相性倍率を返す。
79125
+ * 攻撃側は自身のタイプ(種族タイプ)の技を出せる前提で、その中の最大値。
79126
+ * 将来的に selection-analysis 側と共通化する予定(#14 スコープ外)。
79127
+ */
79128
+ function maxTypeMultiplier$1(attackerTypes, defenderTypes, gen) {
79129
+ let max = 0;
79130
+ const defenders = defenderTypes;
79131
+ for (const attackTypeName of attackerTypes) {
79132
+ const multiplier = calculateTypeEffectiveness(gen, attackTypeName, defenders);
79133
+ if (multiplier > max) max = multiplier;
79134
+ }
79135
+ return max;
79136
+ }
77398
79137
  function registerMatchupTool(server) {
77399
79138
  const calculator = new DamageCalculatorAdapter({
77400
79139
  pokemon: pokemonNameResolver,
@@ -77403,22 +79142,27 @@ function registerMatchupTool(server) {
77403
79142
  item: itemNameResolver,
77404
79143
  nature: natureNameResolver
77405
79144
  }, pokemonEntryProvider);
77406
- server.tool(TOOL_NAME$12, TOOL_DESCRIPTION$12, matchupInputSchema, async (args) => {
79145
+ server.tool(TOOL_NAME$11, TOOL_DESCRIPTION$11, matchupInputSchema, async (args) => {
77407
79146
  try {
77408
79147
  const { pokemon: p1, resolvedName: name1 } = calculator.createPokemonObject(args.pokemon1);
77409
79148
  const { pokemon: p2, resolvedName: name2 } = calculator.createPokemonObject(args.pokemon2);
77410
79149
  const nameJa1 = pokemonNameResolver.toJapanese(name1) ?? name1;
77411
79150
  const nameJa2 = pokemonNameResolver.toJapanese(name2) ?? name2;
77412
- const pokemon1Attacks = calculator.calculateAllMoves({
79151
+ const pokemon1Attacks = filterResultsByLearnset(calculator.calculateAllMoves({
77413
79152
  attacker: args.pokemon1,
77414
79153
  defender: args.pokemon2,
77415
79154
  conditions: args.conditions
77416
- });
77417
- const pokemon2Attacks = calculator.calculateAllMoves({
79155
+ }), getLearnsetMoveIdSet(toDataId(name1)), toDataId);
79156
+ const pokemon2Attacks = filterResultsByLearnset(calculator.calculateAllMoves({
77418
79157
  attacker: args.pokemon2,
77419
79158
  defender: args.pokemon1,
77420
79159
  conditions: args.conditions
77421
- });
79160
+ }), getLearnsetMoveIdSet(toDataId(name2)), toDataId);
79161
+ const gen = calculator.getGen();
79162
+ const typeSummary = {
79163
+ p1ToP2MaxByPokemonType: maxTypeMultiplier$1(p1.types, p2.types, gen),
79164
+ p2ToP1MaxByPokemonType: maxTypeMultiplier$1(p2.types, p1.types, gen)
79165
+ };
77422
79166
  const output = {
77423
79167
  pokemon1: {
77424
79168
  name: name1,
@@ -77432,7 +79176,10 @@ function registerMatchupTool(server) {
77432
79176
  },
77433
79177
  pokemon1Faster: compareSpeed(p1.stats.spe, p2.stats.spe) === "faster",
77434
79178
  pokemon1Attacks,
77435
- pokemon2Attacks
79179
+ pokemon2Attacks,
79180
+ pokemon1PriorityMoves: priorityMovesFor(name1),
79181
+ pokemon2PriorityMoves: priorityMovesFor(name2),
79182
+ typeSummary
77436
79183
  };
77437
79184
  return { content: [{
77438
79185
  type: "text",
@@ -77452,9 +79199,9 @@ function registerMatchupTool(server) {
77452
79199
  }
77453
79200
  //#endregion
77454
79201
  //#region src/tools/info/move-info.ts
77455
- const TOOL_NAME$11 = "get_move_info";
77456
- const TOOL_DESCRIPTION$11 = "ポケモンの技の詳細情報(タイプ・威力・命中率・分類・優先度・効果説明)を取得する。対戦で使う技の仕様を確認したいときに使用する。ポケモンチャンピオンズ対応。";
77457
- const inputSchema$9 = { name: z.string().describe("技名(日本語 or 英語)") };
79202
+ const TOOL_NAME$10 = "get_move_info";
79203
+ const TOOL_DESCRIPTION$10 = "ポケモンの技の詳細情報(タイプ・威力・命中率・分類・優先度・効果説明)を取得する。対戦で使う技の仕様を確認したいときに使用する。ポケモンチャンピオンズ対応。";
79204
+ const inputSchema$8 = { name: z.string().describe("技名(日本語 or 英語)") };
77458
79205
  /**
77459
79206
  * 技名を英語に解決する。日本語名・英語名どちらでも受け付ける。
77460
79207
  * 名前変換辞書には登録されているがチャンピオンズで使えない技の場合はエラー。
@@ -77475,7 +79222,7 @@ function normalizeBasePower(category, basePower) {
77475
79222
  return basePower;
77476
79223
  }
77477
79224
  function registerMoveInfoTool(server) {
77478
- server.tool(TOOL_NAME$11, TOOL_DESCRIPTION$11, inputSchema$9, async (args) => {
79225
+ server.tool(TOOL_NAME$10, TOOL_DESCRIPTION$10, inputSchema$8, async (args) => {
77479
79226
  try {
77480
79227
  const moveId = toDataId(resolveMoveNameEn$1(args.name));
77481
79228
  const entry = movesById.get(moveId);
@@ -77513,9 +79260,9 @@ function registerMoveInfoTool(server) {
77513
79260
  }
77514
79261
  //#endregion
77515
79262
  //#region src/tools/info/nature-info.ts
77516
- const TOOL_NAME$10 = "get_nature_info";
77517
- const TOOL_DESCRIPTION$10 = "ポケモンの性格の詳細情報(上昇ステ・下降ステ)を取得する。育成方針の検討や性格選びに使用する。plus/minus が null の性格は無補正。ポケモンチャンピオンズ対応。";
77518
- const inputSchema$8 = { name: z.string().describe("性格名(日本語 or 英語、例: 'ひかえめ'、'Modest')") };
79263
+ const TOOL_NAME$9 = "get_nature_info";
79264
+ const TOOL_DESCRIPTION$9 = "ポケモンの性格の詳細情報(上昇ステ・下降ステ)を取得する。育成方針の検討や性格選びに使用する。plus/minus が null の性格は無補正。ポケモンチャンピオンズ対応。";
79265
+ const inputSchema$7 = { name: z.string().describe("性格名(日本語 or 英語、例: 'ひかえめ'、'Modest')") };
77519
79266
  /**
77520
79267
  * 性格名を英語に解決する。日本語名・英語名どちらでも受け付ける。
77521
79268
  */
@@ -77528,7 +79275,7 @@ function resolveNatureNameEn(input) {
77528
79275
  throw new Error(`性格「${input}」が見つかりません。${suggestionMessage}`);
77529
79276
  }
77530
79277
  function registerNatureInfoTool(server) {
77531
- server.tool(TOOL_NAME$10, TOOL_DESCRIPTION$10, inputSchema$8, async (args) => {
79278
+ server.tool(TOOL_NAME$9, TOOL_DESCRIPTION$9, inputSchema$7, async (args) => {
77532
79279
  try {
77533
79280
  const englishName = resolveNatureNameEn(args.name);
77534
79281
  const entry = naturesById.get(toDataId(englishName));
@@ -77557,16 +79304,12 @@ function registerNatureInfoTool(server) {
77557
79304
  }
77558
79305
  //#endregion
77559
79306
  //#region src/tools/analysis/party-analysis.ts
77560
- const CHAMPIONS_GEN_NUM$7 = 0;
77561
- const TOOL_NAME$9 = "analyze_party_weakness";
77562
- const TOOL_DESCRIPTION$9 = "パーティのタイプ相性を分析し、弱点と攻撃範囲の穴を洗い出す。パーティ構築の改善やバランスの確認に使用する。ポケモンチャンピオンズ対応。";
79307
+ const CHAMPIONS_GEN_NUM$6 = 0;
79308
+ const TOOL_NAME$8 = "analyze_party_weakness";
79309
+ const TOOL_DESCRIPTION$8 = "パーティ各メンバーのタイプ相性データを集計する。どのタイプが何匹の弱点か(teamWeaknesses)、どのタイプに抜群を取れないか(uncoveredTypes)を返す。致命性の判断は AI が文脈で行う前提。ポケモンチャンピオンズ対応。";
77563
79310
  const partyAnalysisInputSchema = { party: z.array(pokemonSchema).describe("パーティメンバー") };
77564
- /** タイプ相性の倍率しきい値 */
77565
- const WEAKNESS_THRESHOLD$1 = 2;
77566
- const RESISTANCE_THRESHOLD = 1;
77567
- const IMMUNITY_THRESHOLD = 0;
77568
- /** 致命的弱点とみなすための最低弱点数 */
77569
- const CRITICAL_WEAKNESS_MIN_COUNT = 2;
79311
+ /** ???タイプは計算対象から除外するためのマーカー */
79312
+ const UNKNOWN_TYPE_NAME = "???";
77570
79313
  /**
77571
79314
  * ポケモン名を英語に解決する。
77572
79315
  */
@@ -77578,34 +79321,15 @@ function resolvePokemonName$2(name) {
77578
79321
  const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
77579
79322
  throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
77580
79323
  }
77581
- /** ???タイプは計算対象から除外するためのマーカー */
77582
- const UNKNOWN_TYPE_NAME = "???";
77583
79324
  /**
77584
- * ポケモンのタイプに対する各攻撃タイプの倍率を計算する。
79325
+ * 日本語・英語のどちらの名前でも英語名に解決する。
79326
+ * 未知の名前は undefined を返し、呼び出し側で silent ignore する。
77585
79327
  */
77586
- function calculateTypeMatchups(pokemonTypes, gen) {
77587
- const weaknesses = [];
77588
- const resistances = [];
77589
- const immunities = [];
77590
- const defenderTypes = pokemonTypes;
77591
- for (const attackType of gen.types) {
77592
- if (attackType.name === UNKNOWN_TYPE_NAME) continue;
77593
- const multiplier = calculateTypeEffectiveness(gen, attackType.name, defenderTypes);
77594
- if (multiplier === IMMUNITY_THRESHOLD) immunities.push(attackType.name);
77595
- else if (multiplier >= WEAKNESS_THRESHOLD$1) weaknesses.push({
77596
- type: attackType.name,
77597
- multiplier
77598
- });
77599
- else if (multiplier < RESISTANCE_THRESHOLD) resistances.push({
77600
- type: attackType.name,
77601
- multiplier
77602
- });
77603
- }
77604
- return {
77605
- weaknesses,
77606
- resistances,
77607
- immunities
77608
- };
79328
+ function resolveOptionalName(resolver, name) {
79329
+ if (name === void 0) return void 0;
79330
+ const english = resolver.toEnglish(name);
79331
+ if (english !== void 0) return english;
79332
+ if (resolver.hasEnglishName(name)) return name;
77609
79333
  }
77610
79334
  /**
77611
79335
  * パーティ全体の攻撃範囲でカバーされていないタイプを判定する。
@@ -77618,7 +79342,7 @@ function findUncoveredTypes(memberTypes, gen) {
77618
79342
  if (targetType.name === UNKNOWN_TYPE_NAME) continue;
77619
79343
  let isCovered = false;
77620
79344
  for (const types of memberTypes) {
77621
- for (const memberType of types) if (calculateTypeEffectiveness(gen, memberType, [targetType.name]) >= WEAKNESS_THRESHOLD$1) {
79345
+ for (const memberType of types) if (calculateTypeEffectiveness(gen, memberType, [targetType.name]) >= 2) {
77622
79346
  isCovered = true;
77623
79347
  break;
77624
79348
  }
@@ -77629,12 +79353,11 @@ function findUncoveredTypes(memberTypes, gen) {
77629
79353
  return uncovered;
77630
79354
  }
77631
79355
  function registerPartyAnalysisTool(server) {
77632
- server.tool(TOOL_NAME$9, TOOL_DESCRIPTION$9, partyAnalysisInputSchema, async (args) => {
79356
+ server.tool(TOOL_NAME$8, TOOL_DESCRIPTION$8, partyAnalysisInputSchema, async (args) => {
77633
79357
  try {
77634
- const gen = import_dist.Generations.get(CHAMPIONS_GEN_NUM$7);
79358
+ const gen = import_dist.Generations.get(CHAMPIONS_GEN_NUM$6);
77635
79359
  const members = [];
77636
79360
  const teamWeaknesses = {};
77637
- const teamResistances = {};
77638
79361
  const memberTypesList = [];
77639
79362
  for (const member of args.party) {
77640
79363
  const nameEn = resolvePokemonName$2(member.name);
@@ -77643,7 +79366,7 @@ function registerPartyAnalysisTool(server) {
77643
79366
  const nameJa = entry.nameJa ?? entry.name;
77644
79367
  const types = [...entry.types];
77645
79368
  memberTypesList.push(types);
77646
- const { weaknesses, resistances, immunities } = calculateTypeMatchups(types, gen);
79369
+ const { weaknesses, resistances, immunities } = classifyPokemonTypeMatchups(types, gen, { ability: resolveOptionalName(abilityNameResolver, member.ability) });
77647
79370
  members.push({
77648
79371
  name: entry.name,
77649
79372
  nameJa,
@@ -77660,24 +79383,11 @@ function registerPartyAnalysisTool(server) {
77660
79383
  teamWeaknesses[weakness.type].count += 1;
77661
79384
  teamWeaknesses[weakness.type].members.push(entry.name);
77662
79385
  }
77663
- for (const resistance of resistances) teamResistances[resistance.type] = (teamResistances[resistance.type] ?? 0) + 1;
77664
- for (const immuneType of immunities) teamResistances[immuneType] = (teamResistances[immuneType] ?? 0) + 1;
77665
79386
  }
77666
- const criticalWeaknesses = [];
77667
- for (const [type, entry] of Object.entries(teamWeaknesses)) {
77668
- const resistCount = teamResistances[type] ?? 0;
77669
- if (entry.count >= CRITICAL_WEAKNESS_MIN_COUNT) criticalWeaknesses.push({
77670
- type,
77671
- weakCount: entry.count,
77672
- resistCount
77673
- });
77674
- }
77675
- criticalWeaknesses.sort((a, b) => b.weakCount - a.weakCount);
77676
79387
  const output = {
77677
79388
  members,
77678
79389
  teamWeaknesses,
77679
- uncoveredTypes: findUncoveredTypes(memberTypesList, gen),
77680
- criticalWeaknesses
79390
+ uncoveredTypes: findUncoveredTypes(memberTypesList, gen)
77681
79391
  };
77682
79392
  return { content: [{
77683
79393
  type: "text",
@@ -77696,153 +79406,130 @@ function registerPartyAnalysisTool(server) {
77696
79406
  });
77697
79407
  }
77698
79408
  //#endregion
77699
- //#region src/tools/analysis/party-coverage.ts
77700
- const CHAMPIONS_GEN_NUM$6 = 0;
77701
- /** ステータス技(攻撃タイプから除外するため) */
77702
- const STATUS_CATEGORY$2 = "Status";
77703
- const TOOL_NAME$8 = "analyze_party_coverage";
77704
- const TOOL_DESCRIPTION$8 = "パーティの攻撃カバレッジを分析する。各防御タイプ(18種)に対して、パーティのどの技が最も効果的かを算出し、抜群を取れないタイプを洗い出す。 `uncoveredTypes` は『抜群(>1 倍)を取れる技が 1 つも無い防御タイプ』を列挙する(等倍 1 倍も含む)。抜群倍率の内訳は `coverage[].maxMultiplier` を参照。 2タイプ複合のディフェンダーは analyze_matchup で個別に確認してください。ポケモンチャンピオンズ対応。";
77705
- const inputSchema$7 = {
77706
- myParty: z.array(pokemonSchema).describe("自分のパーティ(moves 未指定時は learnset 内の全攻撃技を候補にする)"),
77707
- moves: z.record(z.string(), z.array(z.string())).optional().describe("ポケモン名(日本語 or 英語)をキーに技名配列を値とする map。省略時は learnset から全攻撃技を候補にする。")
79409
+ //#region src/tools/party/party-tools.ts
79410
+ const SAVE_TOOL_NAME = "save_party";
79411
+ const SAVE_TOOL_DESCRIPTION = "パーティを保存する (upsert)。同名のパーティが既に存在する場合は上書きされる。createdAt は新規時のみ現在時刻が記録され、同名上書きの場合は保持される。updatedAt は毎回現在時刻に更新される。";
79412
+ const LOAD_TOOL_NAME = "load_party";
79413
+ const LOAD_TOOL_DESCRIPTION = "保存済みパーティを name 指定で 1 件取得する。存在しない場合はエラーを返す。";
79414
+ const LIST_TOOL_NAME = "list_parties";
79415
+ const LIST_TOOL_DESCRIPTION = "保存済みパーティの一覧 (サマリ) を返す。各要素は { name, memo, updatedAt, memberCount } のみで、メンバー詳細は含まない。詳細は load_party を使用する。";
79416
+ const DELETE_TOOL_NAME = "delete_party";
79417
+ const DELETE_TOOL_DESCRIPTION = "保存済みパーティを name 指定で削除する。存在しない場合はエラーを返す。";
79418
+ const defaultNowProvider = () => /* @__PURE__ */ new Date();
79419
+ const defaultStoreIO = {
79420
+ load: () => loadPartiesFile(),
79421
+ save: (data) => savePartiesFile(data)
77708
79422
  };
77709
- /**
77710
- * 1 メンバー分の「覚えている攻撃技 ID」を取得する。
77711
- * moves 指定があればそれを使い、未指定時は learnset から category !== Status の技を全て拾う。
77712
- */
77713
- function resolveAttackingMoveIds(pokemonEntry, explicitMoves) {
77714
- if (explicitMoves !== void 0) {
77715
- const result = [];
77716
- for (const moveName of explicitMoves) {
77717
- const moveId = toDataId(moveName);
77718
- const move = movesById.get(moveId);
77719
- if (move !== void 0 && move.category !== STATUS_CATEGORY$2) result.push(move);
77720
- }
77721
- return result;
77722
- }
77723
- const learnset = championsLearnsets[pokemonEntry.id];
77724
- if (learnset === void 0) return [];
77725
- const moves = [];
77726
- for (const moveId of learnset) {
77727
- const move = movesById.get(moveId);
77728
- if (move !== void 0 && move.category !== STATUS_CATEGORY$2) moves.push(move);
77729
- }
77730
- return moves;
77731
- }
77732
- /**
77733
- * ポケモン名を pokemon.json のエントリに解決する。
77734
- */
77735
- function resolvePokemonEntry$2(name) {
77736
- const englishName = pokemonNameResolver.toEnglish(name) ?? (pokemonNameResolver.hasEnglishName(name) ? name : null);
77737
- if (englishName === null) {
77738
- const suggestions = pokemonNameResolver.suggestSimilar(name);
77739
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
77740
- throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
77741
- }
77742
- const entry = pokemonById.get(toDataId(englishName));
77743
- if (entry === void 0) throw new Error(`ポケモン「${name}」のデータが見つかりません。`);
77744
- return entry;
79423
+ const nameField = z.string().min(1, { message: "名前は 1 文字以上で指定してください。" }).max(100, { message: `名前は 100 文字以下で指定してください。` });
79424
+ const partyMemberInputSchema = z.object({
79425
+ name: nameField.describe("ポケモン名 (日本語 or 英語)。"),
79426
+ nature: nameField.optional().describe("性格名 (日本語 or 英語)。"),
79427
+ ability: nameField.optional().describe("特性名 (日本語 or 英語)。"),
79428
+ item: nameField.optional().describe("持ち物名 (日本語 or 英語)。"),
79429
+ evs: evsSchema.optional().describe("能力ポイント (SP) 配分。"),
79430
+ moves: z.array(nameField).max(4, { message: `技は 4 個までです。` }).optional().describe("技リスト (最大 4)。")
79431
+ }).describe("パーティメンバー 1 匹分のビルド情報。");
79432
+ const partyNameField = z.string().min(1, { message: "パーティ名は 1 文字以上で指定してください。" }).max(50, { message: `パーティ名は 50 文字以下で指定してください。` });
79433
+ const saveInputSchema = {
79434
+ name: partyNameField.describe("パーティの識別子 (同名は上書き)。"),
79435
+ memo: z.string().max(MAX_PARTY_MEMO_LENGTH, { message: `メモは ${MAX_PARTY_MEMO_LENGTH} 文字以下で指定してください。` }).optional().describe("自由記述メモ。"),
79436
+ members: z.array(partyMemberInputSchema).min(1, { message: `パーティには 1 匹以上を含めてください。` }).max(6, { message: `パーティには 6 匹までしか含められません。` }).describe("1〜6 匹のメンバー。")
79437
+ };
79438
+ const loadInputSchema = { name: partyNameField.describe("取得するパーティ名。") };
79439
+ const deleteInputSchema = { name: partyNameField.describe("削除するパーティ名。") };
79440
+ const listInputSchema = {};
79441
+ function toErrorResponse(error) {
79442
+ const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
79443
+ return {
79444
+ content: [{
79445
+ type: "text",
79446
+ text: JSON.stringify({ error: message })
79447
+ }],
79448
+ isError: true
79449
+ };
77745
79450
  }
77746
- /**
77747
- * moves マップのキー(日本語 or 英語ポケモン名)を英語 ID に正規化する。
77748
- */
77749
- function normalizeMovesMap(moves) {
77750
- const result = /* @__PURE__ */ new Map();
77751
- if (moves === void 0) return result;
77752
- for (const [pokemonName, moveList] of Object.entries(moves)) {
77753
- const entry = resolvePokemonEntry$2(pokemonName);
77754
- result.set(entry.id, moveList);
77755
- }
77756
- return result;
79451
+ function toTextResponse(value) {
79452
+ return { content: [{
79453
+ type: "text",
79454
+ text: JSON.stringify(value)
79455
+ }] };
77757
79456
  }
77758
- /**
77759
- * 攻撃タイプ → 単一防御タイプへの倍率を計算する。
77760
- */
77761
- function getEffectivenessForDefenderType(attackTypeName, defenderTypeName, gen) {
77762
- return calculateTypeEffectiveness(gen, attackTypeName, [defenderTypeName]);
79457
+ function toSummary(party) {
79458
+ const summary = {
79459
+ name: party.name,
79460
+ updatedAt: party.updatedAt,
79461
+ memberCount: party.members.length
79462
+ };
79463
+ if (party.memo !== void 0) summary.memo = party.memo;
79464
+ return summary;
77763
79465
  }
77764
79466
  /**
77765
- * パーティの攻撃カバレッジを計算する純関数。
77766
- * MCP tool handler からも直接テストからも呼び出せる。
79467
+ * パーティ永続化 4 ツールをサーバーに登録する。
79468
+ * deps は主にテスト用。本番は省略してデフォルト (ファイル I/O + 現在時刻) を使う。
77767
79469
  */
77768
- function analyzePartyCoverage(args) {
77769
- const gen = import_dist.Generations.get(CHAMPIONS_GEN_NUM$6);
77770
- const movesMap = normalizeMovesMap(args.moves);
77771
- const members = [];
77772
- const attackingTypesSet = /* @__PURE__ */ new Set();
77773
- for (const member of args.myParty) {
77774
- const entry = resolvePokemonEntry$2(member.name);
77775
- const attackingMoves = resolveAttackingMoveIds(entry, movesMap.get(entry.id));
77776
- for (const move of attackingMoves) attackingTypesSet.add(move.type);
77777
- members.push({
77778
- entry,
77779
- attackingMoves
77780
- });
77781
- }
77782
- const attackingTypes = [];
77783
- const typeJaMap = new Map(championsTypes.map((t) => [t.name, t.nameJa]));
77784
- for (const typeName of attackingTypesSet) attackingTypes.push({
77785
- type: typeName,
77786
- nameJa: typeJaMap.get(typeName) ?? typeName
79470
+ function registerPartyTools(server, deps = {}) {
79471
+ const storeIO = deps.storeIO ?? defaultStoreIO;
79472
+ const now = deps.now ?? defaultNowProvider;
79473
+ server.tool(SAVE_TOOL_NAME, SAVE_TOOL_DESCRIPTION, saveInputSchema, async (args) => {
79474
+ try {
79475
+ const file = storeIO.load();
79476
+ const nowIso = now().toISOString();
79477
+ const existingIndex = file.parties.findIndex((p) => p.name === args.name);
79478
+ const createdAt = existingIndex >= 0 ? file.parties[existingIndex].createdAt : nowIso;
79479
+ const party = {
79480
+ name: args.name,
79481
+ members: args.members,
79482
+ createdAt,
79483
+ updatedAt: nowIso
79484
+ };
79485
+ if (args.memo !== void 0) party.memo = args.memo;
79486
+ if (existingIndex >= 0) file.parties[existingIndex] = party;
79487
+ else file.parties.push(party);
79488
+ storeIO.save({
79489
+ schemaVersion: 1,
79490
+ parties: file.parties
79491
+ });
79492
+ return toTextResponse({
79493
+ saved: true,
79494
+ overwrote: existingIndex >= 0,
79495
+ party,
79496
+ filePath: resolvePartiesFilePath()
79497
+ });
79498
+ } catch (error) {
79499
+ return toErrorResponse(error);
79500
+ }
77787
79501
  });
77788
- attackingTypes.sort((a, b) => a.type.localeCompare(b.type));
77789
- const coverage = [];
77790
- const uncoveredTypes = [];
77791
- for (const defenderType of championsTypes) {
77792
- let maxMultiplier = 0;
77793
- const bestAttackers = [];
77794
- for (const member of members) for (const move of member.attackingMoves) {
77795
- const multiplier = getEffectivenessForDefenderType(move.type, defenderType.name, gen);
77796
- if (multiplier > maxMultiplier) {
77797
- maxMultiplier = multiplier;
77798
- bestAttackers.length = 0;
77799
- bestAttackers.push({
77800
- pokemon: member.entry.name,
77801
- move: move.name,
77802
- multiplier
77803
- });
77804
- } else if (multiplier === maxMultiplier && multiplier > 0) {
77805
- if (!bestAttackers.some((ba) => ba.pokemon === member.entry.name)) bestAttackers.push({
77806
- pokemon: member.entry.name,
77807
- move: move.name,
77808
- multiplier
77809
- });
77810
- }
79502
+ server.tool(LOAD_TOOL_NAME, LOAD_TOOL_DESCRIPTION, loadInputSchema, async (args) => {
79503
+ try {
79504
+ const party = storeIO.load().parties.find((p) => p.name === args.name);
79505
+ if (party === void 0) throw new Error(`パーティ「${args.name}」が見つかりません。list_parties で一覧を確認してください。`);
79506
+ return toTextResponse({ party });
79507
+ } catch (error) {
79508
+ return toErrorResponse(error);
77811
79509
  }
77812
- coverage.push({
77813
- defenderType: defenderType.name,
77814
- defenderTypeJa: defenderType.nameJa,
77815
- maxMultiplier,
77816
- bestAttackers
77817
- });
77818
- if (maxMultiplier <= 1) uncoveredTypes.push({
77819
- type: defenderType.name,
77820
- nameJa: defenderType.nameJa
77821
- });
77822
- }
77823
- return {
77824
- attackingTypes,
77825
- coverage,
77826
- uncoveredTypes
77827
- };
77828
- }
77829
- function registerPartyCoverageTool(server) {
77830
- server.tool(TOOL_NAME$8, TOOL_DESCRIPTION$8, inputSchema$7, async (args) => {
79510
+ });
79511
+ server.tool(LIST_TOOL_NAME, LIST_TOOL_DESCRIPTION, listInputSchema, async () => {
77831
79512
  try {
77832
- const output = analyzePartyCoverage(args);
77833
- return { content: [{
77834
- type: "text",
77835
- text: JSON.stringify(output)
77836
- }] };
79513
+ return toTextResponse({ parties: storeIO.load().parties.map(toSummary) });
77837
79514
  } catch (error) {
77838
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
77839
- return {
77840
- content: [{
77841
- type: "text",
77842
- text: JSON.stringify({ error: message })
77843
- }],
77844
- isError: true
77845
- };
79515
+ return toErrorResponse(error);
79516
+ }
79517
+ });
79518
+ server.tool(DELETE_TOOL_NAME, DELETE_TOOL_DESCRIPTION, deleteInputSchema, async (args) => {
79519
+ try {
79520
+ const file = storeIO.load();
79521
+ const nextParties = file.parties.filter((p) => p.name !== args.name);
79522
+ if (nextParties.length === file.parties.length) throw new Error(`パーティ「${args.name}」が見つかりません。`);
79523
+ storeIO.save({
79524
+ schemaVersion: 1,
79525
+ parties: nextParties
79526
+ });
79527
+ return toTextResponse({
79528
+ deleted: true,
79529
+ name: args.name
79530
+ });
79531
+ } catch (error) {
79532
+ return toErrorResponse(error);
77846
79533
  }
77847
79534
  });
77848
79535
  }
@@ -78463,20 +80150,8 @@ function registerSearchByTypeEffectivenessTool(server) {
78463
80150
  //#endregion
78464
80151
  //#region src/tools/analysis/selection-analysis.ts
78465
80152
  const CHAMPIONS_GEN_NUM$3 = 0;
78466
- /** 選出推奨のトップ N 件 */
78467
- const RECOMMENDATION_TOP_N = 3;
78468
- /** 各スコアの重み */
78469
- const SCORE_WEIGHT_SPEED_WIN = 2;
78470
- const SCORE_WEIGHT_TYPE_ADVANTAGE = 3;
78471
- const SCORE_WEIGHT_DAMAGE_ADVANTAGE = 5;
78472
- const SCORE_WEIGHT_TYPE_DISADVANTAGE = -1;
78473
- /** ダメージ閾値(%表記) */
78474
- const OHKO_PERCENT_THRESHOLD = 100;
78475
- const TWO_HKO_PERCENT_THRESHOLD = 50;
78476
- /** タイプ抜群判定のしきい値 */
78477
- const SUPER_EFFECTIVE_THRESHOLD = 2;
78478
80153
  const TOOL_NAME$3 = "analyze_selection";
78479
- const TOOL_DESCRIPTION$3 = "選出判断の一括分析を行う。自分と相手のパーティから全組み合わせ(最大 6x6)のマトリクスを生成し、タイプ相性・素早さ・ダメージ見積もりと先発/起点交代候補の推奨を返す。ポケモンチャンピオンズ対応。";
80154
+ const TOOL_DESCRIPTION$3 = "6v6 パーティ間の全対面(最大 36 エントリ)について、タイプ相性・素早さ比較・最大ダメージ見積もりをマトリクスで返す。選出判断は本ツールが返すデータを元に AI が総合的に行う前提で、ツール側では推奨やスコアリングは行わない。ポケモンチャンピオンズ対応。正確な計算のため各ポケモンの ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
78480
80155
  const inputSchema$2 = {
78481
80156
  myParty: z.array(pokemonSchema).describe("自分のパーティ"),
78482
80157
  opponentParty: z.array(pokemonSchema).describe("相手のパーティ"),
@@ -78512,45 +80187,13 @@ function bestDamageEstimate(results, moveJaResolver) {
78512
80187
  move: {
78513
80188
  name: best.move,
78514
80189
  nameJa
78515
- }
80190
+ },
80191
+ typeMultiplier: best.typeMultiplier,
80192
+ isStab: best.isStab,
80193
+ effectivePowerMultiplier: best.effectivePowerMultiplier
78516
80194
  };
78517
80195
  }
78518
80196
  /**
78519
- * ポケモンの対面スコア(選出推奨用)を計算する。
78520
- * 大きいほど対面に強い。
78521
- */
78522
- function calcMatchupScore(entry) {
78523
- let score = 0;
78524
- if (entry.speedCompare === "faster") score += SCORE_WEIGHT_SPEED_WIN;
78525
- else if (entry.speedCompare === "slower") score -= SCORE_WEIGHT_SPEED_WIN;
78526
- if (entry.typeAdvantage.myToOpp >= SUPER_EFFECTIVE_THRESHOLD) score += SCORE_WEIGHT_TYPE_ADVANTAGE;
78527
- if (entry.typeAdvantage.oppToMy >= SUPER_EFFECTIVE_THRESHOLD) score += SCORE_WEIGHT_TYPE_DISADVANTAGE;
78528
- if (entry.damageEstimate !== null) {
78529
- if (entry.damageEstimate.max >= OHKO_PERCENT_THRESHOLD) score += SCORE_WEIGHT_DAMAGE_ADVANTAGE;
78530
- else if (entry.damageEstimate.max >= TWO_HKO_PERCENT_THRESHOLD) score += SCORE_WEIGHT_DAMAGE_ADVANTAGE / 2;
78531
- }
78532
- return score;
78533
- }
78534
- /**
78535
- * あるポケモンの「合計スコア」を、相手パーティ全員に対するスコア和として算出する。
78536
- */
78537
- function calcTotalScoreForAttacker(attackerName, matrix) {
78538
- let total = 0;
78539
- for (const entry of matrix) if (entry.mine === attackerName) total += calcMatchupScore(entry);
78540
- return total;
78541
- }
78542
- /**
78543
- * 上位 N 件のポケモン名(日本語名)を返す。
78544
- */
78545
- function topPokemonByScore(myParty, scorer, topN) {
78546
- const scored = myParty.map((p) => ({
78547
- nameJa: p.nameJa,
78548
- score: scorer(p.name)
78549
- }));
78550
- scored.sort((a, b) => b.score - a.score);
78551
- return scored.slice(0, topN).map((s) => s.nameJa);
78552
- }
78553
- /**
78554
80197
  * ポケモンごとの候補技を英名リストに正規化する(日本語 → 英語)。
78555
80198
  */
78556
80199
  function resolveMovesMap(moves) {
@@ -78567,8 +80210,11 @@ function resolveMovesMap(moves) {
78567
80210
  /**
78568
80211
  * attacker vs defender の候補技でダメージを計算する。
78569
80212
  * movesMap に指定があればそれを、無ければ全技で計算する。
80213
+ * movesMap 未指定経路では attacker の learnset でフィルタし、覚えない技での過大評価を避ける。
80214
+ * 明示指定経路は learnset フィルタを掛けない(ユーザーの明示選択を尊重する既存仕様を維持)。
80215
+ * conditions (battleFormat 等) を calculator に伝える。
78570
80216
  */
78571
- function calculateDamageForMatchup(calculator, attacker, defender, attackerId, movesMap) {
80217
+ function calculateDamageForMatchup(calculator, attacker, defender, attackerId, attackerLearnsetIds, movesMap, conditions) {
78572
80218
  const explicitMoves = movesMap.get(attackerId);
78573
80219
  if (explicitMoves !== void 0 && explicitMoves.length > 0) {
78574
80220
  const results = [];
@@ -78576,16 +80222,18 @@ function calculateDamageForMatchup(calculator, attacker, defender, attackerId, m
78576
80222
  results.push(calculator.calculate({
78577
80223
  attacker,
78578
80224
  defender,
78579
- moveName
80225
+ moveName,
80226
+ conditions
78580
80227
  }));
78581
80228
  } catch {}
78582
80229
  results.sort((a, b) => b.max - a.max);
78583
80230
  return results;
78584
80231
  }
78585
- return calculator.calculateAllMoves({
80232
+ return filterResultsByLearnset(calculator.calculateAllMoves({
78586
80233
  attacker,
78587
- defender
78588
- });
80234
+ defender,
80235
+ conditions
80236
+ }), attackerLearnsetIds, toDataId);
78589
80237
  }
78590
80238
  function registerSelectionAnalysisTool(server) {
78591
80239
  const calculator = new DamageCalculatorAdapter({
@@ -78599,15 +80247,24 @@ function registerSelectionAnalysisTool(server) {
78599
80247
  try {
78600
80248
  const gen = import_dist.Generations.get(CHAMPIONS_GEN_NUM$3);
78601
80249
  const movesMap = resolveMovesMap(args.moves);
80250
+ const damageConditions = { battleFormat: args.battleFormat };
78602
80251
  function buildMemberContext(input) {
78603
80252
  const { pokemon, resolvedName } = calculator.createPokemonObject(input);
78604
- const entry = pokemonById.get(toDataId(resolvedName));
80253
+ const entryId = toDataId(resolvedName);
80254
+ const entry = pokemonById.get(entryId);
80255
+ const nameJa = pokemonNameResolver.toJapanese(resolvedName) ?? resolvedName;
80256
+ const types = entry !== void 0 ? [...entry.types] : [...pokemon.types];
80257
+ const priorityMoves = extractPriorityMoves({
80258
+ learnsetMoveIds: championsLearnsets[entryId] ?? [],
80259
+ resolveMove: (id) => movesById.get(id),
80260
+ toJapanese: (enName) => moveNameResolver.toJapanese(enName)
80261
+ });
78605
80262
  return {
78606
80263
  input,
78607
80264
  profile: {
78608
80265
  name: resolvedName,
78609
- nameJa: pokemonNameResolver.toJapanese(resolvedName) ?? resolvedName,
78610
- types: entry !== void 0 ? [...entry.types] : [...pokemon.types],
80266
+ nameJa,
80267
+ types,
78611
80268
  actualStats: {
78612
80269
  hp: pokemon.stats.hp,
78613
80270
  atk: pokemon.stats.atk,
@@ -78615,13 +80272,16 @@ function registerSelectionAnalysisTool(server) {
78615
80272
  spa: pokemon.stats.spa,
78616
80273
  spd: pokemon.stats.spd,
78617
80274
  spe: pokemon.stats.spe
78618
- }
80275
+ },
80276
+ priorityMoves
78619
80277
  },
78620
- entryId: toDataId(resolvedName)
80278
+ entryId
78621
80279
  };
78622
80280
  }
78623
80281
  const myMembers = args.myParty.map(buildMemberContext);
78624
80282
  const oppMembers = args.opponentParty.map(buildMemberContext);
80283
+ const myLearnsetIds = /* @__PURE__ */ new Map();
80284
+ for (const mine of myMembers) myLearnsetIds.set(mine.entryId, getLearnsetMoveIdSet(mine.entryId));
78625
80285
  const matrix = [];
78626
80286
  for (const mine of myMembers) for (const opp of oppMembers) {
78627
80287
  const myToOpp = maxTypeMultiplier(mine.profile.types, opp.profile.types, gen);
@@ -78629,7 +80289,7 @@ function registerSelectionAnalysisTool(server) {
78629
80289
  const speedCompare = compareSpeed(mine.profile.actualStats.spe, opp.profile.actualStats.spe);
78630
80290
  let damageEstimate = null;
78631
80291
  try {
78632
- damageEstimate = bestDamageEstimate(calculateDamageForMatchup(calculator, mine.input, opp.input, mine.entryId, movesMap), (enName) => moveNameResolver.toJapanese(enName));
80292
+ damageEstimate = bestDamageEstimate(calculateDamageForMatchup(calculator, mine.input, opp.input, mine.entryId, myLearnsetIds.get(mine.entryId) ?? /* @__PURE__ */ new Set(), movesMap, damageConditions), (enName) => moveNameResolver.toJapanese(enName));
78633
80293
  } catch {
78634
80294
  damageEstimate = null;
78635
80295
  }
@@ -78644,26 +80304,10 @@ function registerSelectionAnalysisTool(server) {
78644
80304
  damageEstimate
78645
80305
  });
78646
80306
  }
78647
- const leadScorer = (name) => calcTotalScoreForAttacker(name, matrix);
78648
- const lead = topPokemonByScore(myMembers.map((m) => m.profile), leadScorer, RECOMMENDATION_TOP_N);
78649
- const pivotScorer = (name) => {
78650
- let total = 0;
78651
- for (const entry of matrix) {
78652
- if (entry.mine !== name) continue;
78653
- if (entry.typeAdvantage.oppToMy < 1) total += 1;
78654
- if (entry.speedCompare === "slower") total -= .5;
78655
- }
78656
- return total;
78657
- };
78658
- const pivot = topPokemonByScore(myMembers.map((m) => m.profile), pivotScorer, RECOMMENDATION_TOP_N);
78659
80307
  const output = {
78660
80308
  myParty: myMembers.map((m) => m.profile),
78661
80309
  opponentParty: oppMembers.map((m) => m.profile),
78662
80310
  matchupMatrix: matrix,
78663
- recommendations: {
78664
- lead,
78665
- pivot
78666
- },
78667
80311
  battleFormat: args.battleFormat
78668
80312
  };
78669
80313
  return { content: [{
@@ -78953,10 +80597,12 @@ function createServer() {
78953
80597
  version: SERVER_VERSION
78954
80598
  }, { instructions: SERVER_INSTRUCTIONS });
78955
80599
  registerAbilityInfoTool(server);
80600
+ registerComparePartiesTool(server);
78956
80601
  registerConditionInfoTool(server);
78957
80602
  registerDamageCalculationTools(server);
78958
80603
  registerDamageRangeTool(server);
78959
80604
  registerFindCountersTool(server);
80605
+ registerImportPartyFromTextTool(server);
78960
80606
  registerItemInfoTool(server);
78961
80607
  registerLearnsetTool(server);
78962
80608
  registerMatchupTool(server);
@@ -78964,6 +80610,7 @@ function createServer() {
78964
80610
  registerNatureInfoTool(server);
78965
80611
  registerPartyAnalysisTool(server);
78966
80612
  registerPartyCoverageTool(server);
80613
+ registerPartyTools(server);
78967
80614
  registerPokemonInfoTools(server);
78968
80615
  registerPokemonSummaryTool(server);
78969
80616
  registerSearchByAbilityTool(server);