@nonz250/ai-rotom 1.3.7 → 2.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
@@ -1,39 +1,116 @@
1
1
  #!/usr/bin/env node
2
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { z } from "zod";
5
- import { Field, Generations, Move, Pokemon, calculate } from "@smogon/calc";
5
+ import { Field, Generations, Move, Pokemon, calculate, toID } from "@smogon/calc";
6
6
  import { randomBytes } from "node:crypto";
7
7
  import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
8
8
  import { homedir } from "node:os";
9
9
  import { dirname, join } from "node:path";
10
10
  import { parse } from "@pokesol/pokesol-text-parser-ts";
11
+ // ../../shared/src/constants/champions.ts
12
+ /** タイプ一致 (STAB) 補正倍率。てきおうりょく等の特性補正は含まない通常値 */
13
+ const STAB_MULTIPLIER = 1.5;
14
+ // ../../shared/src/schemas/stats.ts
15
+ const statPointValueSchema = z.number({ message: "能力ポイント(SP)は数値で指定してください。" }).int({ message: "能力ポイント(SP)は整数で指定してください。" }).finite().min(0, { message: "能力ポイント(SP)は 0 以上で指定してください。" }).max(32, { message: `能力ポイント(SP)は各ステータス 32 以下です (ポケモンチャンピオンズ仕様)。` });
16
+ /**
17
+ * 能力ポイント(SP) のスキーマ。
18
+ * ポケモンチャンピオンズ仕様: 各ステ 0〜MAX_STAT_POINT_PER_STAT、
19
+ * 合計 0〜MAX_STAT_POINT_TOTAL の範囲。
20
+ * 従来の EV (各 252 / 合計 510) とは別仕様なので AI クライアントが
21
+ * 旧知識で 252 等を渡してきた場合に弾く。
22
+ */
23
+ const evsSchema = z.object({
24
+ hp: statPointValueSchema.optional(),
25
+ atk: statPointValueSchema.optional(),
26
+ def: statPointValueSchema.optional(),
27
+ spa: statPointValueSchema.optional(),
28
+ spd: statPointValueSchema.optional(),
29
+ spe: statPointValueSchema.optional()
30
+ }).refine((evs) => {
31
+ return Object.values(evs).reduce((sum, v) => sum + (v ?? 0), 0) <= 66;
32
+ }, { message: `能力ポイント(SP)の合計は 66 以下でなければなりません (ポケモンチャンピオンズ仕様)。各ステ 32 上限・合計 66 上限です。従来の努力値(EV)の 252/510 上限ではありません。` });
33
+ const boostValueSchema = z.number().int().finite().min(-6).max(6);
34
+ /**
35
+ * ランク補正 (いかく・ちからをつける等) のスキーマ。
36
+ * 各ステータスは -6〜+6 の整数のみ許可する。
37
+ */
38
+ const boostsSchema = z.object({
39
+ hp: boostValueSchema.optional(),
40
+ atk: boostValueSchema.optional(),
41
+ def: boostValueSchema.optional(),
42
+ spa: boostValueSchema.optional(),
43
+ spd: boostValueSchema.optional(),
44
+ spe: boostValueSchema.optional()
45
+ });
46
+ /** メモの最大文字数。 */
47
+ const MAX_PARTY_MEMO_LENGTH = 4e3;
48
+ const nameField$1 = z.string().min(1, { message: "名前は 1 文字以上で指定してください。" }).max(100, { message: `名前は 100 文字以下で指定してください。` });
49
+ const optionalNameField = nameField$1.optional();
50
+ /**
51
+ * パーティに所属する 1 匹分の入力スキーマ。
52
+ */
53
+ const partyMemberSchema = z.object({
54
+ name: nameField$1.describe("ポケモン名 (日本語 or 英語)。"),
55
+ nature: optionalNameField.describe("性格名 (日本語 or 英語)。"),
56
+ ability: optionalNameField.describe("特性名 (日本語 or 英語)。"),
57
+ item: optionalNameField.describe("持ち物名 (日本語 or 英語)。"),
58
+ evs: evsSchema.optional().describe("能力ポイント (SP) の配分。"),
59
+ moves: z.array(nameField$1).max(4, { message: `技は 4 個までです。` }).optional().describe("技リスト (日本語 or 英語、最大 4)。")
60
+ });
61
+ const isoDateTimeField = z.string().refine((value) => !Number.isNaN(Date.parse(value)), { message: "ISO 8601 形式の日時文字列で指定してください。" });
62
+ /**
63
+ * 1 パーティ分の入力スキーマ。
64
+ */
65
+ const partySchema = z.object({
66
+ name: z.string().min(1, { message: "パーティ名は 1 文字以上で指定してください。" }).max(50, { message: `パーティ名は 50 文字以下で指定してください。` }).describe("パーティの識別子。"),
67
+ memo: z.string().max(MAX_PARTY_MEMO_LENGTH, { message: `メモは ${MAX_PARTY_MEMO_LENGTH} 文字以下で指定してください。` }).optional().describe("自由記述メモ。"),
68
+ members: z.array(partyMemberSchema).min(1, { message: `パーティには 1 匹以上を含めてください。` }).max(6, { message: `パーティには 6 匹までしか含められません。` }).describe("1〜6 匹のメンバー。"),
69
+ createdAt: isoDateTimeField.describe("作成日時 (ISO 8601)。"),
70
+ updatedAt: isoDateTimeField.describe("更新日時 (ISO 8601)。")
71
+ });
72
+ /**
73
+ * `~/.ai-rotom/parties.json` 全体のスキーマ。
74
+ */
75
+ const partiesFileSchema = z.object({
76
+ schemaVersion: z.number().int().positive().describe("パーティファイルの schemaVersion。"),
77
+ parties: z.array(partySchema).describe("登録済みパーティの一覧。")
78
+ });
11
79
  // ../../shared/src/utils/name-resolver.ts
80
+ /**
81
+ * データ上の日本語名は全角英数字 (10まんボルト) と半角英数字 (メガリザードンX) が混在しており、
82
+ * 入力側も半角で書かれることが多いため、照合は NFKC で正規化した表記で行う。
83
+ */
84
+ function normalizeJapaneseName(name) {
85
+ return name.normalize("NFKC");
86
+ }
12
87
  var NameResolver = class {
13
88
  jaToEn;
14
89
  enToJa;
15
90
  jaNames;
16
91
  constructor(entries) {
17
- this.jaToEn = new Map(entries.map((e) => [e.ja, e.en]));
92
+ this.jaToEn = new Map(entries.map((e) => [normalizeJapaneseName(e.ja), e.en]));
18
93
  this.enToJa = new Map(entries.map((e) => [e.en, e.ja]));
19
94
  this.jaNames = entries.map((e) => e.ja);
20
95
  }
21
96
  toEnglish(jaName) {
22
- return this.jaToEn.get(jaName);
97
+ return this.jaToEn.get(normalizeJapaneseName(jaName));
23
98
  }
24
99
  toJapanese(enName) {
25
100
  return this.enToJa.get(enName);
26
101
  }
27
102
  hasJapaneseName(jaName) {
28
- return this.jaToEn.has(jaName);
103
+ return this.jaToEn.has(normalizeJapaneseName(jaName));
29
104
  }
30
105
  hasEnglishName(enName) {
31
106
  return this.enToJa.has(enName);
32
107
  }
33
108
  suggestSimilar(jaName, maxResults = 3) {
109
+ const normalizedInput = normalizeJapaneseName(jaName);
110
+ if (normalizedInput.length > 100) return [];
34
111
  const candidates = [];
35
112
  for (const name of this.jaNames) {
36
- const distance = levenshteinDistance(jaName, name);
113
+ const distance = levenshteinDistance(normalizedInput, normalizeJapaneseName(name));
37
114
  candidates.push({
38
115
  name,
39
116
  distance
@@ -61,9 +138,15 @@ function levenshteinDistance(a, b) {
61
138
  }
62
139
  return matrix[a.length][b.length];
63
140
  }
64
- // ../../shared/src/constants/champions.ts
65
- /** タイプ一致 (STAB) 補正倍率。てきおうりょく等の特性補正は含まない通常値 */
66
- const STAB_MULTIPLIER = 1.5;
141
+ // ../../shared/src/errors/user-facing-error.ts
142
+ /**
143
+ * メッセージをそのままツールの呼び出し元に返してよい例外。
144
+ * 呼び出し元が引数を直して呼び直せるように、何が悪いかを日本語で伝える文面だけを載せる。
145
+ * これ以外の例外のメッセージは内部の事情を含みうるため、呼び出し元には返さない。
146
+ */
147
+ var UserFacingError = class extends Error {
148
+ name = "UserFacingError";
149
+ };
67
150
  // ../../shared/src/analysis/type-matchup.ts
68
151
  /** 等倍の相性倍率 */
69
152
  const NEUTRAL_EFFECTIVENESS = 1;
@@ -307,7 +390,7 @@ const NORMAL_TYPE = "Normal";
307
390
  * mcp-server 側の MoveCategory と同じ文字列だが、shared は mcp-server に
308
391
  * 依存できないためここで独立に定義する。
309
392
  */
310
- const STATUS_CATEGORY$4 = "Status";
393
+ const STATUS_CATEGORY$3 = "Status";
311
394
  /** 文字列を ID 相当(英数字のみ・小文字)に正規化する */
312
395
  function toId(value) {
313
396
  return value.toLowerCase().replace(/[^a-z0-9]/g, "");
@@ -341,96 +424,63 @@ const OFFENSIVE_TYPE_OVERRIDES = /* @__PURE__ */ new Map([
341
424
  function applyOffensiveTypeOverride(originalMoveType, moveCategory, ability) {
342
425
  if (ability === void 0) return originalMoveType;
343
426
  if (originalMoveType !== NORMAL_TYPE) return originalMoveType;
344
- if (moveCategory === STATUS_CATEGORY$4) return originalMoveType;
427
+ if (moveCategory === STATUS_CATEGORY$3) return originalMoveType;
345
428
  const abilityId = toId(ability);
346
429
  const overrideType = OFFENSIVE_TYPE_OVERRIDES.get(abilityId);
347
430
  if (overrideType === void 0) return originalMoveType;
348
431
  return overrideType;
349
432
  }
350
- // ../../shared/src/schemas/stats.ts
351
- const statPointValueSchema = z.number({ message: "能力ポイント(SP)は数値で指定してください。" }).int({ message: "能力ポイント(SP)は整数で指定してください。" }).finite().min(0, { message: "能力ポイント(SP)は 0 以上で指定してください。" }).max(32, { message: `能力ポイント(SP)は各ステータス 32 以下です (ポケモンチャンピオンズ仕様)。` });
433
+ // ../../shared/src/schemas/pokemon-input.ts
352
434
  /**
353
- * 能力ポイント(SP) のスキーマ。
354
- * ポケモンチャンピオンズ仕様: 各ステ 0〜MAX_STAT_POINT_PER_STAT、
355
- * 合計 0〜MAX_STAT_POINT_TOTAL の範囲。
356
- * 従来の EV (各 252 / 合計 510) とは別仕様なので AI クライアントが
357
- * 旧知識で 252 等を渡してきた場合に弾く。
435
+ * ポケモン名・技名・タイプ名などの名前の入力スキーマ。
358
436
  */
359
- const evsSchema = z.object({
360
- hp: statPointValueSchema.optional(),
361
- atk: statPointValueSchema.optional(),
362
- def: statPointValueSchema.optional(),
363
- spa: statPointValueSchema.optional(),
364
- spd: statPointValueSchema.optional(),
365
- spe: statPointValueSchema.optional()
366
- }).refine((evs) => {
367
- return Object.values(evs).reduce((sum, v) => sum + (v ?? 0), 0) <= 66;
368
- }, { message: `能力ポイント(SP)の合計は 66 以下でなければなりません (ポケモンチャンピオンズ仕様)。各ステ 32 上限・合計 66 上限です。従来の努力値(EV)の 252/510 上限ではありません。` });
369
- const boostValueSchema = z.number().int().finite().min(-6).max(6);
437
+ const nameInputSchema = z.string().max(100);
438
+ const moveNameInputSchema = z.string().min(1).max(100);
370
439
  /**
371
- * ランク補正 (いかく・ちからをつける等) のスキーマ。
372
- * 各ステータスは -6〜+6 の整数のみ許可する。
440
+ * 1 匹分の技構成の入力スキーマ。
373
441
  */
374
- const boostsSchema = z.object({
375
- hp: boostValueSchema.optional(),
376
- atk: boostValueSchema.optional(),
377
- def: boostValueSchema.optional(),
378
- spa: boostValueSchema.optional(),
379
- spd: boostValueSchema.optional(),
380
- spe: boostValueSchema.optional()
442
+ const movesInputSchema = z.array(moveNameInputSchema).max(4, { message: `技は 4 個までです。` });
443
+ /**
444
+ * ポケモン名をキーに技構成を値とする入力スキーマ。
445
+ */
446
+ const movesByPokemonSchema = z.record(nameInputSchema, z.array(moveNameInputSchema)).refine((movesByPokemon) => Object.keys(movesByPokemon).length <= 6, { message: `技を指定できるポケモンは 6 匹までです。` }).superRefine((movesByPokemon, ctx) => {
447
+ const exceeded = Object.entries(movesByPokemon).filter(([, moves]) => moves.length > 4).map(([pokemonName]) => pokemonName);
448
+ if (exceeded.length === 0) return;
449
+ ctx.addIssue({
450
+ code: "custom",
451
+ message: `技は 1 体につき 4 つまで指定できます。moves 引数の ${exceeded.join("、")} の技を 4 つ以内にして呼び直してください。`
452
+ });
381
453
  });
382
- // ../../shared/src/schemas/pokemon-input.ts
383
- const pokemonSchema = z.object({
384
- name: z.string().describe("ポケモン名(日本語 or 英語)"),
385
- nature: z.string().optional().describe("性格名(省略時: まじめ)"),
454
+ const pokemonFields = {
455
+ name: nameInputSchema.describe("ポケモン名(日本語 or 英語)"),
456
+ nature: nameInputSchema.optional().describe("性格名(省略時: まじめ)"),
386
457
  evs: evsSchema.optional().describe("能力ポイント(SP)。各ステ 0-32、合計 0-66。省略時は全 0 (無振り)。"),
387
- ability: z.string().optional().describe("特性名"),
388
- item: z.string().optional().describe("持ち物名"),
458
+ ability: nameInputSchema.optional().describe("特性名"),
459
+ item: nameInputSchema.optional().describe("持ち物名"),
389
460
  boosts: boostsSchema.optional().describe("ランク補正 (-6〜+6 の整数)。省略時は全 0。いかく・ちからをつける等の変動を表現する。"),
390
- status: z.string().optional().describe("状態異常")
461
+ status: nameInputSchema.optional().describe("状態異常")
462
+ };
463
+ /**
464
+ * 技構成を使わないツール向けのポケモン入力スキーマ。
465
+ * moves を受け付けると AI が指定を反映されたものと誤解するため、項目自体を持たない。
466
+ */
467
+ const pokemonSchema = z.object(pokemonFields);
468
+ /**
469
+ * 攻撃側として全技ダメ計を行うツール向けのポケモン入力スキーマ。
470
+ */
471
+ const pokemonWithMovesSchema = z.object({
472
+ ...pokemonFields,
473
+ moves: movesInputSchema.optional().describe("技構成(日本語 or 英語、最大 4)。攻撃側として全技計算するときは指定した技だけを計算する。省略時は習得技すべてで計算する。")
391
474
  });
392
475
  const conditionsSchema = z.object({
393
- weather: z.string().optional().describe("天候(Sun, Rain, Sand, Hail, Snow)"),
394
- terrain: z.string().optional().describe("フィールド(Electric, Grassy, Misty, Psychic)"),
476
+ weather: nameInputSchema.optional().describe("天候(Sun, Rain, Sand, Hail, Snow)"),
477
+ terrain: nameInputSchema.optional().describe("フィールド(Electric, Grassy, Misty, Psychic)"),
395
478
  battleFormat: z.enum(["singles", "doubles"]).optional().describe("対戦形式(シングル: singles / ダブル: doubles)。省略時は singles。doubles 指定時は全体攻撃技 (じしん/ねっぷう等) の威力が ×0.75 され、壁系の軽減率が約 0.667 倍に変わる。"),
396
479
  isReflect: z.boolean().optional().describe("リフレクター"),
397
480
  isLightScreen: z.boolean().optional().describe("ひかりのかべ"),
398
481
  isAuroraVeil: z.boolean().optional().describe("オーロラベール"),
399
482
  isCriticalHit: z.boolean().optional().describe("急所")
400
483
  });
401
- /** メモの最大文字数。 */
402
- const MAX_PARTY_MEMO_LENGTH = 4e3;
403
- const nameField$1 = z.string().min(1, { message: "名前は 1 文字以上で指定してください。" }).max(100, { message: `名前は 100 文字以下で指定してください。` });
404
- const optionalNameField = nameField$1.optional();
405
- /**
406
- * パーティに所属する 1 匹分の入力スキーマ。
407
- */
408
- const partyMemberSchema = z.object({
409
- name: nameField$1.describe("ポケモン名 (日本語 or 英語)。"),
410
- nature: optionalNameField.describe("性格名 (日本語 or 英語)。"),
411
- ability: optionalNameField.describe("特性名 (日本語 or 英語)。"),
412
- item: optionalNameField.describe("持ち物名 (日本語 or 英語)。"),
413
- evs: evsSchema.optional().describe("能力ポイント (SP) の配分。"),
414
- moves: z.array(nameField$1).max(4, { message: `技は 4 個までです。` }).optional().describe("技リスト (日本語 or 英語、最大 4)。")
415
- });
416
- const isoDateTimeField = z.string().refine((value) => !Number.isNaN(Date.parse(value)), { message: "ISO 8601 形式の日時文字列で指定してください。" });
417
- /**
418
- * 1 パーティ分の入力スキーマ。
419
- */
420
- const partySchema = z.object({
421
- name: z.string().min(1, { message: "パーティ名は 1 文字以上で指定してください。" }).max(50, { message: `パーティ名は 50 文字以下で指定してください。` }).describe("パーティの識別子。"),
422
- memo: z.string().max(MAX_PARTY_MEMO_LENGTH, { message: `メモは ${MAX_PARTY_MEMO_LENGTH} 文字以下で指定してください。` }).optional().describe("自由記述メモ。"),
423
- members: z.array(partyMemberSchema).min(1, { message: `パーティには 1 匹以上を含めてください。` }).max(6, { message: `パーティには 6 匹までしか含められません。` }).describe("1〜6 匹のメンバー。"),
424
- createdAt: isoDateTimeField.describe("作成日時 (ISO 8601)。"),
425
- updatedAt: isoDateTimeField.describe("更新日時 (ISO 8601)。")
426
- });
427
- /**
428
- * `~/.ai-rotom/parties.json` 全体のスキーマ。
429
- */
430
- const partiesFileSchema = z.object({
431
- schemaVersion: z.number().int().positive().describe("パーティファイルの schemaVersion。"),
432
- parties: z.array(partySchema).describe("登録済みパーティの一覧。")
433
- });
434
484
  // ../../shared/src/calc/resolvers/resolve-name.ts
435
485
  /**
436
486
  * 日本語名または英語名を受け取り、対応する英語名に変換する。
@@ -441,8 +491,7 @@ function resolveNameWithFallback(resolver, name, label) {
441
491
  if (englishName !== void 0) return englishName;
442
492
  if (resolver.hasEnglishName(name)) return name;
443
493
  const suggestions = resolver.suggestSimilar(name);
444
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
445
- throw new Error(`${label}「${name}」が見つかりません。${suggestionMessage}`);
494
+ throw new UserFacingError(`${label}「${name}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
446
495
  }
447
496
  /**
448
497
  * `resolveNameWithFallback` の undefined 許容版。
@@ -551,7 +600,7 @@ function toPercent(value, maxHP) {
551
600
  return Math.round(value / maxHP * 100 * 10) / 10;
552
601
  }
553
602
  // ../../shared/src/calc/damage-calculator.ts
554
- const CHAMPIONS_GEN_NUM$10 = 0;
603
+ const CHAMPIONS_GEN_NUM$9 = 0;
555
604
  const DEFAULT_NATURE_EN$2 = "Serious";
556
605
  function buildTypeMetrics(gen, move, attacker, defender) {
557
606
  const moveType = move.type;
@@ -580,9 +629,11 @@ function buildTypeMetrics(gen, move, attacker, defender) {
580
629
  var DamageCalculatorAdapter = class {
581
630
  resolvers;
582
631
  entryProvider;
583
- constructor(resolvers, entryProvider) {
632
+ learnsetProvider;
633
+ constructor(resolvers, entryProvider, learnsetProvider) {
584
634
  this.resolvers = resolvers;
585
635
  this.entryProvider = entryProvider;
636
+ this.learnsetProvider = learnsetProvider;
586
637
  }
587
638
  calculate(input) {
588
639
  const gen = this.getGen();
@@ -635,34 +686,32 @@ var DamageCalculatorAdapter = class {
635
686
  const defender = new Pokemon(gen, defenderName, buildPokemonOptions(input.defender, defenderNature, defenderAbility, defenderItem, this.entryProvider.getByName(defenderName)));
636
687
  const field = buildField(input.conditions);
637
688
  const defenderMaxHP = defender.maxHP();
689
+ const candidateMoveNames = this.resolveCandidateMoveNames(gen, attackerName, input.attacker.moves);
638
690
  const results = [];
639
- for (const moveData of gen.moves) {
640
- if (!moveData.basePower || moveData.basePower <= 0) continue;
641
- try {
642
- const move = new Move(gen, moveData.name, { isCrit: input.conditions?.isCriticalHit });
643
- const result = calculate(gen, attacker, defender, move, field);
644
- const [min, max] = result.range();
645
- if (max <= 0) continue;
646
- const minPercent = toPercent(min, defenderMaxHP);
647
- const maxPercent = toPercent(max, defenderMaxHP);
648
- const koResult = result.kochance();
649
- const damageArray = flattenDamage(result.damage);
650
- const typeMetrics = buildTypeMetrics(gen, result.move, result.attacker, result.defender);
651
- results.push({
652
- attacker: attackerName,
653
- defender: defenderName,
654
- move: moveData.name,
655
- damage: damageArray,
656
- min,
657
- max,
658
- minPercent,
659
- maxPercent,
660
- koChance: koResult.text,
661
- description: result.fullDesc(),
662
- ...typeMetrics
663
- });
664
- } catch {}
665
- }
691
+ for (const moveName of candidateMoveNames) try {
692
+ const move = new Move(gen, moveName, { isCrit: input.conditions?.isCriticalHit });
693
+ const result = calculate(gen, attacker, defender, move, field);
694
+ const [min, max] = result.range();
695
+ if (max <= 0) continue;
696
+ const minPercent = toPercent(min, defenderMaxHP);
697
+ const maxPercent = toPercent(max, defenderMaxHP);
698
+ const koResult = result.kochance();
699
+ const damageArray = flattenDamage(result.damage);
700
+ const typeMetrics = buildTypeMetrics(gen, result.move, result.attacker, result.defender);
701
+ results.push({
702
+ attacker: attackerName,
703
+ defender: defenderName,
704
+ move: moveName,
705
+ damage: damageArray,
706
+ min,
707
+ max,
708
+ minPercent,
709
+ maxPercent,
710
+ koChance: koResult.text,
711
+ description: result.fullDesc(),
712
+ ...typeMetrics
713
+ });
714
+ } catch {}
666
715
  results.sort((a, b) => b.max - a.max);
667
716
  return results;
668
717
  }
@@ -677,8 +726,23 @@ var DamageCalculatorAdapter = class {
677
726
  resolvedName
678
727
  };
679
728
  }
729
+ /**
730
+ * 技名 (日本語 or 英語) を英語名に解決し、重複を取り除く。
731
+ * 解決できない技名があれば類似候補を添えて例外を投げる。
732
+ * マスターデータにはあっても計算エンジンが持たない技は、計算すると結果から
733
+ * 黙って消えてしまうため、ここで例外にする。
734
+ */
735
+ resolveMoveNames(moves) {
736
+ const gen = this.getGen();
737
+ const resolved = moves.map((name) => {
738
+ const englishName = resolveNameWithFallback(this.resolvers.move, name, "技");
739
+ if (gen.moves.get(toID(englishName)) === void 0) throw new UserFacingError(`技「${name}」は計算エンジンが未対応のため計算できません。技構成から外して呼び出してください。`);
740
+ return englishName;
741
+ });
742
+ return [...new Set(resolved)];
743
+ }
680
744
  getGen() {
681
- return Generations.get(CHAMPIONS_GEN_NUM$10);
745
+ return Generations.get(CHAMPIONS_GEN_NUM$9);
682
746
  }
683
747
  get pokemonResolver() {
684
748
  return this.resolvers.pokemon;
@@ -689,192 +753,57 @@ var DamageCalculatorAdapter = class {
689
753
  get natureResolver() {
690
754
  return this.resolvers.nature;
691
755
  }
756
+ resolveCandidateMoveNames(gen, attackerName, moves) {
757
+ if (moves !== void 0 && moves.length > 0) return this.resolveMoveNames(moves);
758
+ const learnableMoveIds = this.learnsetProvider.getMoveIds(attackerName);
759
+ const names = [];
760
+ for (const moveData of gen.moves) {
761
+ if (!moveData.basePower || moveData.basePower <= 0) continue;
762
+ if (learnableMoveIds.size > 0 && !learnableMoveIds.has(moveData.id)) continue;
763
+ names.push(moveData.name);
764
+ }
765
+ return names;
766
+ }
692
767
  resolveNature(nature) {
693
768
  if (nature === void 0) return DEFAULT_NATURE_EN$2;
694
769
  return resolveNameWithFallback(this.resolvers.nature, nature, "性格");
695
770
  }
696
771
  };
697
- // ../../shared/src/calc/filters/learnset-filter.ts
772
+ // ../../shared/src/calc/formatters/move-damage-summary.ts
698
773
  /**
699
- * calculateAllMoves の結果を learnset で絞り込む。
700
- *
701
- * @smogon/calc は全技を走査するため、実際に覚えない技で過大評価しないように
702
- * 呼び出し側で learnset フィルタを適用するための純関数。
703
- *
704
- * learnsetMoveIds が空集合の場合は、learnset データが無い(不明)とみなして
705
- * フィルタせず元の配列をそのまま返す(現行挙動踏襲)。
706
- *
707
- * 呼び出し側は `results[i].move` と `learnsetMoveIds` を同じ正規化形式で
708
- * 揃える責務を持つ。正規化ロジックは `normalize` 引数で注入する。
774
+ * ダメージ降順に並んだ計算結果を要約する。
775
+ * 特性や持ち物の補正はどの技にも同じように掛かるため、反映されたかの確認には
776
+ * 最大打点の技の説明文があれば足りる。全技に付けると出力が膨らむので先頭にだけ残す。
709
777
  */
710
- function filterResultsByLearnset(results, learnsetMoveIds, normalize) {
711
- if (learnsetMoveIds.size === 0) return [...results];
712
- return results.filter((r) => learnsetMoveIds.has(normalize(r.move)));
778
+ function summarizeMoveDamages(results, toJapanese) {
779
+ return results.map((result, index) => {
780
+ const summary = {
781
+ move: result.move,
782
+ moveJa: toJapanese(result.move) ?? result.move,
783
+ moveType: result.moveType,
784
+ isStab: result.isStab,
785
+ typeMultiplier: result.typeMultiplier,
786
+ effectivePowerMultiplier: result.effectivePowerMultiplier,
787
+ minPercent: result.minPercent,
788
+ maxPercent: result.maxPercent,
789
+ koChance: result.koChance
790
+ };
791
+ if (index === 0) summary.description = result.description;
792
+ return summary;
793
+ });
794
+ }
795
+ // src/moves-requirement.ts
796
+ const MOVES_OPTIONAL = { requireMoves: false };
797
+ /**
798
+ * 技構成が必須の環境で、moves を指定していない攻撃側があればエラーにする。
799
+ * 習得技すべてを計算すると、実行環境の処理時間の上限を超えるため。
800
+ */
801
+ function assertMovesSpecified(requirement, targets) {
802
+ if (!requirement.requireMoves) return;
803
+ const missing = targets.filter((target) => (target.moves?.length ?? 0) === 0);
804
+ if (missing.length === 0) return;
805
+ throw new UserFacingError(`このサーバーは 1 回の処理時間に上限があるため、技構成の指定が必要です。${missing.map((target) => `${target.field} (${target.name})`).join("、")} の moves に技構成を指定して呼び直してください。技は 4 つまで指定できます。技構成が分からない場合は get_learnset で覚える技を確認して選んでください。`);
713
806
  }
714
- // src/instructions.ts
715
- const SERVER_INSTRUCTIONS = `
716
- ai-rotom はポケモンチャンピオンズ (Pokemon Champions) の対戦アドバイザー MCP サーバーです。
717
-
718
- ## セッションスコープ(重要)
719
-
720
- - このセッション内でポケモン関連の話題が出た場合は、すべてポケモンチャンピオンズ (Pokemon Champions) の仕様として扱ってください。
721
- - 従来作 (SV / 剣盾 / USUM / BDSP / LA 等) の仕様・技威力・特性効果・種族値・タイプ相性などを前提にしないでください。
722
- - ポケモン名・技名・特性・持ち物・タイプ・素早さ等の固有名詞や数値がユーザー発話に出た時点で、まず本サーバーのツールを呼んで事実を取得してから回答すること。記憶や推測で即答しない (下の「ツール利用方針(必須)」を参照)。
723
- - ポケチャン固有仕様で不明な点は推測で埋めず、ユーザーに確認してください。
724
-
725
- 以降は、従来作と差異が出やすい代表的な固有仕様です。
726
-
727
- ## 能力ポイント (SP) について
728
-
729
- - 従来の「努力値 (EV)」は廃止され、「能力ポイント (SP)」という仕様に変更されました。
730
- - 各ステータス (hp/atk/def/spa/spd/spe) あたりの上限: 32 SP
731
- - 全ステータス合計の上限: 66 SP
732
- - 1 SP = 実数値 +1 で直接加算されます (従来 EV の「4 EV = 実数値 +1」ではありません)。
733
- - 各ステ 0〜32、合計 0〜66 の範囲内なら振り方は自由です。
734
- - 従来の 252 EV / 510 EV 合計上限をそのまま渡すとエラーになります。
735
-
736
- ## SP 振りの実践(重要)
737
-
738
- ポケチャンの SP は **1 単位で振れる**(各ステ 0〜32、合計 0〜66)ため、
739
- 従来作流の「とりあえず最速」「とりあえず HP252」のような **ブッパ一辺倒は最適でないことが多い**。
740
- AI クライアントは目的駆動で刻む振り方を提案すること。各ステに 32 振り切るより、
741
- 要求を満たす最小限を割り当てて余り SP を別の役割に回す方が、合計 66 SP の制約下では強い。
742
-
743
- ### 火力調整(atk / spa)
744
- - 「主要対面相手を確定 1 発(or 確定 2 発)で落とす最低限の振り」を calculate_damage_single / calculate_damage_all_moves で逆算する。
745
- - 余った SP は HP / 素早さ / 別ステに回す。
746
-
747
- ### 耐久調整(hp / def / spd)
748
- - 「主要対面相手の技を確定耐えする最低限の振り」を analyze_damage_range で逆算する。
749
- - 物理耐久は hp + def、特殊耐久は hp + spd の組み合わせで効率化。HP のみブッパだと無駄が出やすい。
750
-
751
- ### 素早さ調整(spe)— S 調整振り
752
- - 「特定ラインを抜く / 同速回避するピンポイント振り」を list_speed_tiers + calculate_stats で逆算する。
753
- - 例: 準速 100 族(実数値 152)を抜きたいだけなら spe を 32 振り切る必要はなく、必要最小限の SP で抜ける。
754
- - 同速回避は相手と同じ振りに対し +1 SP 多く振る。
755
-
756
- ### 提案フローのテンプレート
757
- 1. ユーザーに役割(耐久型 / 火力型 / 削り役 / サポート 等)と主要対面相手 2-3 体を確認する。
758
- 2. 火力 / 耐久 / 素早さの要求 SP を、対面相手ごとに計算ツールで逆算する。
759
- 3. 合計 66 SP の制約内で配分案を提示する(複数案あれば併記)。
760
- 4. 余り SP の使い道(HP / 素早さ微調整 / 火力上乗せ)も併記する。
761
-
762
- 「ブッパで雑に最速・HP 全振り」の提案はポケチャンでは型として弱いため、明示的に要求された場合を除き避けること。
763
-
764
- ## その他の固有仕様
765
-
766
- - 個体値 (IV): 廃止。全ポケモン一律 31 固定として扱われます。
767
- - 対戦レベル: 50 固定。
768
- - メガシンカ: 1試合につき1回のみ使用可能。
769
- - テラスタル: 未対応 (ゲーム側で未実装のため)。
770
- - 特性の一部は計算エンジンが未対応で、ダメージ計算結果に効果が反映されません。get_ability_info で効果を確認し、必要に応じて結果の解釈時に補正してください。
771
- - 持ち物の一部も同様に計算エンジンが未対応で、ダメージ計算結果に効果が反映されません (フィールド・接地判定に関わるものは反映されます)。get_item_info で効果を確認してください。
772
- - メガシンカ後のフォルムと、一部のフォルムは覚える技 (learnset) のデータが未整備です。この場合 get_learnset はエラーになり、get_pokemon_summary の learnableMoves.count は 0、技の逆引き検索 (search_pokemon_by_move 等) では結果に出てきませんが、いずれも「技を覚えない」という意味ではありません。未整備かどうかは get_pokemon_info の learnableMoveCount が null かどうかで判別できるため、技プールを断定せずデータ未整備である旨をユーザーに伝えてください。これらの技プールはベースフォームの learnset を参照してください。
773
-
774
- ## 判断と計算の役割分担
775
-
776
- - 本サーバーのツールは「判断の根拠となる正確なデータを返す」ことに責務を限定しています。
777
- 「この選出が最適」「この構築が正解」といった最終判断は返しません。
778
- - 選出・構築・対策の結論は、ツールが返したデータ (タイプ相性・ダメ計・素早さ比較・対面マトリクス等) を元に AI が総合的に導いてください。
779
- - 一部ツール (find_counters 等) はスコア付きの候補リストを返しますが、これは候補抽出のための目安であり、
780
- 最終的な採用判断はダメ計・素早さ・対面状況を踏まえて AI が行うものです。
781
-
782
- ## ツール利用方針(必須)
783
-
784
- 以下のトピックがユーザー発話に出てきたら、必ず該当ツールを呼んで根拠データを取得してから回答すること。
785
- ポケチャンは従来作と種族値・技威力・特性効果等で差異が出るため、知識ベースの即答は禁止。
786
-
787
- ### ポケモン検索・情報取得 (「○○ってどんなポケモン?」「○○タイプで素早いポケモンは?」等)
788
- - 単体の基本情報 (種族値 / タイプ / 特性 / 体重) → get_pokemon_info
789
- - 単体の総合プロファイル (耐性 / 覚える技 / 実数値) → get_pokemon_summary
790
- - タイプ・種族値での絞り込み → search_pokemon
791
- - 技の逆引き (この技を覚えるポケモン) → search_pokemon_by_move
792
- - 特性の逆引き (この特性を持つポケモン) → search_pokemon_by_ability
793
- - タイプ相性での逆引き (○○タイプを半減/無効化する等) → search_pokemon_by_type_effectiveness
794
- - 覚える技一覧 → get_learnset
795
-
796
- ### 技・攻撃まわり (「○○の威力は?」「電気タイプで威力高い技は?」「攻撃範囲は?」等)
797
- - 技の威力 / タイプ / 効果 / PP → get_move_info
798
- - ある技を覚えるポケモン一覧 → search_pokemon_by_move
799
- - 個体 / パーティの攻撃範囲 → get_pokemon_summary / analyze_party_coverage
800
- - ダメージ計算 → calculate_damage_single (1 対 1 単発) / calculate_damage_all_moves (1 対 1 全技) / calculate_damage_party_matchup (6v6)
801
- - 確定数 / 乱数 / 耐久要求の逆算 → analyze_damage_range
802
-
803
- ### 素早さ (S ライン) (「○○の素早さは?」「○○より早いポケモンは?」「S○○族は?」等)
804
- - 実数値計算 → calculate_stats
805
- - 素早さライン一覧・スカーフ込み比較 → list_speed_tiers
806
- - 対面での先後判定 (素早さ比較込み) → analyze_matchup
807
-
808
- ### その他の事実確認 (「○○の特性効果は?」「○○の効果は?」「ねっぷう撃たれたら?」等)
809
- - 特性効果 → get_ability_info
810
- - 持ち物効果 → get_item_info
811
- - 性格補正 → get_nature_info
812
- - タイプ相性 → get_type_info
813
- - 天候 / 状態異常 / フィールド / 壁 → get_condition_info
814
-
815
- ## 計算・分析系ツールでの ability / item 指定
816
-
817
- - 計算・対面分析系ツール (calculate_damage_single / calculate_damage_all_moves / calculate_damage_party_matchup / analyze_damage_range / analyze_matchup / analyze_selection / find_counters) を呼ぶ前に、攻撃側・防御側の ability / item を確認してから指定すること。
818
- - 省略時の挙動: ability は通常特性 (pokemon.json の abilities[0]) が自動設定され、item は持ち物なし扱いとなる。そのためメガシンカ・こだわり系・半減きのみ・ちからのハチマキ 等が反映されず、実戦想定の build と乖離した結果になる。
819
- - 正確な計算のためには ability / item を明示的に指定することを強く推奨する。
820
- - 一方で、育成データ (evs・nature) が不明な場合は省略してよい (デフォルト値で計算)。
821
-
822
- ## パーティデータの扱い
823
-
824
- - セッション開始時 (初回ユーザー発話への応答前) に必ず list_parties を呼び、保存済みパーティの名前一覧を把握すること。
825
- - ユーザーが「メインパ」「ドラゴン軸」等の保存名に言及したら load_party で詳細を取得し、分析ツールに渡すこと。
826
- - ユーザーが新規構築を説明した際は「保存しますか」と確認し、同意があれば save_party を呼ぶこと。
827
- - パーティの削除依頼は delete_party を使うこと。
828
- - 起動時にパーティ詳細まで自動読み込みしないこと (トークン消費を抑えるため、詳細は都度 load_party で取得する)。
829
-
830
- ## パーティ登録の対話スタイル
831
-
832
- ユーザーが「パーティを保存したい」「構築を覚えて」等と依頼した場合:
833
-
834
- ### テキスト一括投入の場合 (ケース A)
835
-
836
- - ユーザーが Showdown 風 or ポケソルテキストを貼り付けた → import_party_from_text を呼ぶ (原文をそのまま渡す)。
837
- - ユーザーがゲーム内画面のスクショを添付した → 画像から build を読み取り、下記の対話ケース (B) と同じ手順でポケソルテキストに整理してから import_party_from_text を呼ぶ。
838
-
839
- ### 対話で埋める場合 (ケース B)
840
-
841
- - ユーザーがテキストもスクショも提供しない → AI が段階的に質問する。
842
- - 1 匹ずつ以下の順で聞く (ユーザーが知っている情報から埋める):
843
- 1. ポケモン名 (日本語 or 英語)
844
- 2. 性格 (候補を 4-5 個提示: いじっぱり / ようき / ひかえめ / おくびょう / ずぶとい など)
845
- 3. 特性 (該当ポケモンの候補を提示)
846
- 4. もちもの (省略可能、候補があれば提示)
847
- 5. 技 4 つ
848
- 6. SP 配分 (省略時は無振り 0、指定あれば各 0〜32 / 合計 0〜66 で受け付け)
849
-
850
- ### 整理ステップ (重要)
851
-
852
- - 対話で情報が揃ったら、必ずポケソルテキスト形式にまとめて表示し、ユーザーに確認を取ること:
853
-
854
- 例:
855
- ガブリアス @ こだわりスカーフ
856
- 特性: さめはだ
857
- 能力補正: いじっぱり
858
- 170(2)-200(32)-115(0)-90(0)-100(0)-167(32)
859
- じしん / ドラゴンクロー / つのドリル / いわなだれ
860
-
861
- - 実数値が不明な場合は calculate_stats を呼んで補完する (パーサー仕様上、実数値行は省略可能だが、ユーザー確認用に含めることを推奨)。
862
- - 複数匹の場合は空行区切りで並べる。
863
- - ユーザー確認後 import_party_from_text(text, name, memo) を呼ぶ。
864
- - パーサーがエラーを返した場合は、原因を提示してユーザーに修正を確認する。
865
-
866
- ### 質問の書き方ルール
867
-
868
- - 質問は短く、候補があれば列挙する (「性格はどうしますか? いじっぱり / ようき / ひかえめ」のような形式)。
869
- - 一度に 1 項目だけ聞く (複数同時の質問は避ける)。
870
- - ユーザーが「後で決める」と言った項目はデフォルト値で埋める (性格=まじめ、特性=基本特性、SP=無振り 等)。
871
- - 不明な項目は tool 呼び出しで確認する (例: 覚える技 → get_learnset)。
872
-
873
- ### 絶対に守ること
874
-
875
- - 対話で得た情報を JSON 化して save_party を直接呼ばない (ハルシネーションリスク軽減のため必ずポケソルテキスト経由)。
876
- - ユーザー確認なしに save / import を実行しない。
877
- `.trim();
878
807
  // ../../data/champions/abilities.json
879
808
  var abilities_default = [
880
809
  {
@@ -38043,9 +37972,25 @@ function toDataId(name) {
38043
37972
  * 英語名から pokemonById Map を引いて PokemonEntry を返す。
38044
37973
  */
38045
37974
  const pokemonEntryProvider = { getByName: (name) => pokemonById.get(toDataId(name)) };
37975
+ /** メガシンカ後のフォルム名の末尾 (例: "-Mega", "-Mega-X")。 */
37976
+ const MEGA_FORME_SUFFIX = /-Mega(-[XYZ])?$/;
37977
+ /**
37978
+ * shared/calc モジュールに渡すための LearnsetProvider 実装。
37979
+ * 英語名を ID に変換して learnset を引く。
37980
+ */
37981
+ const learnsetProvider = { getMoveIds: (pokemonName) => {
37982
+ const id = toDataId(pokemonName);
37983
+ const own = getLearnsetMoveIdSet(id);
37984
+ if (own.size > 0) return own;
37985
+ const preMega = getLearnsetMoveIdSet(toDataId(pokemonName.replace(MEGA_FORME_SUFFIX, "")));
37986
+ if (preMega.size > 0) return preMega;
37987
+ const baseSpecies = pokemonById.get(id)?.baseSpecies;
37988
+ if (baseSpecies === null || baseSpecies === void 0) return own;
37989
+ return getLearnsetMoveIdSet(toDataId(baseSpecies));
37990
+ } };
38046
37991
  /**
38047
37992
  * 指定ポケモンの learnset に含まれる技 ID セットを取得する。
38048
- * 未登録のポケモンは空 Set を返す(shared の filterResultsByLearnset では
37993
+ * 未登録のポケモンは空 Set を返す(DamageCalculatorAdapter.calculateAllMoves では
38049
37994
  * 空 Set を「learnset データが無い」フォールバックとして扱う)。
38050
37995
  * learnset JSON の ID は既に Showdown toID 形式だが、呼び出し側の
38051
37996
  * 正規化関数({@link toDataId})との対称性を保つため念のため通している。
@@ -38102,12 +38047,16 @@ function toTextResponse(value) {
38102
38047
  text: JSON.stringify(value)
38103
38048
  });
38104
38049
  }
38050
+ /** UserFacingError 以外の例外のときに、元の文面の代わりに返す文面。 */
38051
+ const UNEXPECTED_ERROR_MESSAGE = "ツールの実行中に予期しないエラーが発生しました。";
38105
38052
  /**
38106
38053
  * エラー応答 (isError: true) を組み立てるヘルパー。
38107
38054
  * エラー時はノイズになるため hint は付けない (仕様)。
38055
+ * 元の文面を返すのは UserFacingError だけにする。それ以外の例外の文面には
38056
+ * ライブラリ内部の事情が含まれうるため、固定の文面に置き換える。
38108
38057
  */
38109
38058
  function toErrorResponse(error) {
38110
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
38059
+ const message = error instanceof UserFacingError ? error.message : UNEXPECTED_ERROR_MESSAGE;
38111
38060
  return {
38112
38061
  content: [{
38113
38062
  type: "text",
@@ -38117,9 +38066,9 @@ function toErrorResponse(error) {
38117
38066
  };
38118
38067
  }
38119
38068
  // src/tools/info/ability-info.ts
38120
- const TOOL_NAME$20 = "get_ability_info";
38121
- const TOOL_DESCRIPTION$20 = "ポケモンの特性の詳細情報(効果説明)を取得する。ポケモンチャンピオンズで使える特性のみ返す。対戦でポケモンの特性を理解したいときに使用する。";
38122
- const inputSchema$17 = { name: z.string().describe("特性名(日本語 or 英語)") };
38069
+ const TOOL_NAME$19 = "get_ability_info";
38070
+ const TOOL_DESCRIPTION$19 = "ポケモンの特性の詳細情報(効果説明)を取得する。ポケモンチャンピオンズで使える特性のみ返す。対戦でポケモンの特性を理解したいときに使用する。";
38071
+ const inputSchema$16 = { name: nameInputSchema.describe("特性名(日本語 or 英語)") };
38123
38072
  /**
38124
38073
  * 特性名を英語に解決する。日本語名・英語名どちらでも受け付ける。
38125
38074
  */
@@ -38128,15 +38077,14 @@ function resolveAbilityNameEn$1(input) {
38128
38077
  if (fromJa !== void 0) return fromJa;
38129
38078
  if (abilityNameResolver.hasEnglishName(input)) return input;
38130
38079
  const suggestions = abilityNameResolver.suggestSimilar(input);
38131
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
38132
- throw new Error(`特性「${input}」が見つかりません。${suggestionMessage}`);
38080
+ throw new UserFacingError(`特性「${input}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
38133
38081
  }
38134
38082
  function registerAbilityInfoTool(server) {
38135
- server.tool(TOOL_NAME$20, TOOL_DESCRIPTION$20, inputSchema$17, async (args) => {
38083
+ server.tool(TOOL_NAME$19, TOOL_DESCRIPTION$19, inputSchema$16, async (args) => {
38136
38084
  try {
38137
38085
  const abilityId = toDataId(resolveAbilityNameEn$1(args.name));
38138
38086
  const entry = abilitiesById.get(abilityId);
38139
- if (entry === void 0) throw new Error(`特性「${args.name}」はチャンピオンズでは使用できません。`);
38087
+ if (entry === void 0) throw new UserFacingError(`特性「${args.name}」はチャンピオンズでは使用できません。`);
38140
38088
  const output = {
38141
38089
  name: entry.name,
38142
38090
  nameJa: entry.nameJa,
@@ -38148,19 +38096,12 @@ function registerAbilityInfoTool(server) {
38148
38096
  text: JSON.stringify(output)
38149
38097
  });
38150
38098
  } catch (error) {
38151
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
38152
- return {
38153
- content: [{
38154
- type: "text",
38155
- text: JSON.stringify({ error: message })
38156
- }],
38157
- isError: true
38158
- };
38099
+ return toErrorResponse(error);
38159
38100
  }
38160
38101
  });
38161
38102
  }
38162
38103
  // src/tools/analysis/party-coverage.ts
38163
- const CHAMPIONS_GEN_NUM$9 = 0;
38104
+ const CHAMPIONS_GEN_NUM$8 = 0;
38164
38105
  /** 複合タイプを構成するタイプ数 */
38165
38106
  const DUAL_TYPE_COUNT = 2;
38166
38107
  /** 複合タイプ集合キーのセパレータ(タイプ名に現れない文字) */
@@ -38168,12 +38109,12 @@ const DUAL_TYPE_KEY_SEPARATOR = "/";
38168
38109
  /** `dualTypeCoverage` の `examplePokemon` に収める最大件数 */
38169
38110
  const MAX_EXAMPLE_POKEMON = 3;
38170
38111
  /** ステータス技(攻撃タイプから除外するため) */
38171
- const STATUS_CATEGORY$3 = "Status";
38172
- const TOOL_NAME$19 = "analyze_party_coverage";
38173
- const TOOL_DESCRIPTION$19 = "パーティの攻撃カバレッジを分析する。各防御タイプ(18種)に対して、パーティのどの技が最も効果的かを算出し、抜群を取れないタイプを洗い出す。 `uncoveredTypes` は『抜群(>1 倍)を取れる技が 1 つも無い防御タイプ』を列挙する(等倍 1 倍も含む)。抜群倍率の内訳は `coverage[].maxMultiplier` を参照。 実在する複合タイプ(データ内に 1 匹以上存在する 2 タイプ組合せ)に対するカバレッジは `dualTypeCoverage` を参照。抜群を取れない複合タイプ数は `dualTypeUncoveredCount`。 攻撃側のタイプ変換系特性(Pixilate 等)は単一/複合カバレッジ双方に反映される。 ポケモンチャンピオンズ対応。";
38174
- const inputSchema$16 = {
38175
- myParty: z.array(pokemonSchema).describe("自分のパーティ(moves 未指定時は learnset 内の全攻撃技を候補にする)"),
38176
- moves: z.record(z.string(), z.array(z.string())).optional().describe("ポケモン名(日本語 or 英語)をキーに技名配列を値とする map。省略時は learnset から全攻撃技を候補にする。")
38112
+ const STATUS_CATEGORY$2 = "Status";
38113
+ const TOOL_NAME$18 = "analyze_party_coverage";
38114
+ const TOOL_DESCRIPTION$18 = "パーティの攻撃カバレッジを分析する。各防御タイプ(18種)に対して、パーティのどの技が最も効果的かを算出し、抜群を取れないタイプを洗い出す。 `uncoveredTypes` は『抜群(>1 倍)を取れる技が 1 つも無い防御タイプ』を列挙する(等倍 1 倍も含む)。抜群倍率の内訳は `coverage[].maxMultiplier` を参照。 実在する複合タイプ(データ内に 1 匹以上存在する 2 タイプ組合せ)に対するカバレッジは `dualTypeCoverage` を参照。抜群を取れない複合タイプ数は `dualTypeUncoveredCount`。 攻撃側のタイプ変換系特性(Pixilate 等)は単一/複合カバレッジ双方に反映される。 ポケモンチャンピオンズ対応。";
38115
+ const inputSchema$15 = {
38116
+ myParty: z.array(pokemonSchema).min(1).max(6).describe("自分のパーティ(moves 未指定時は learnset 内の全攻撃技を候補にする)"),
38117
+ moves: movesByPokemonSchema.optional().describe("ポケモン名(日本語 or 英語)をキーに技名配列を値とする map。省略時は learnset から全攻撃技を候補にする。")
38177
38118
  };
38178
38119
  /**
38179
38120
  * 技名を英語名に解決する。日本語名・英語名どちらでも受け付ける。
@@ -38188,8 +38129,7 @@ function resolveMoveEnglishName(name) {
38188
38129
  if (fromJa !== void 0) return fromJa;
38189
38130
  if (moveNameResolver.hasEnglishName(name)) return name;
38190
38131
  const suggestions = moveNameResolver.suggestSimilar(name);
38191
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
38192
- throw new Error(`技「${name}」が見つかりません。${suggestionMessage}`);
38132
+ throw new UserFacingError(`技「${name}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
38193
38133
  }
38194
38134
  /**
38195
38135
  * 1 メンバー分の「覚えている攻撃技 ID」を取得する。
@@ -38201,7 +38141,7 @@ function resolveAttackingMoveIds(pokemonEntry, explicitMoves) {
38201
38141
  for (const moveName of explicitMoves) {
38202
38142
  const moveId = toDataId(resolveMoveEnglishName(moveName));
38203
38143
  const move = movesById.get(moveId);
38204
- if (move !== void 0 && move.category !== STATUS_CATEGORY$3) result.push(move);
38144
+ if (move !== void 0 && move.category !== STATUS_CATEGORY$2) result.push(move);
38205
38145
  }
38206
38146
  return result;
38207
38147
  }
@@ -38210,7 +38150,7 @@ function resolveAttackingMoveIds(pokemonEntry, explicitMoves) {
38210
38150
  const moves = [];
38211
38151
  for (const moveId of learnset) {
38212
38152
  const move = movesById.get(moveId);
38213
- if (move !== void 0 && move.category !== STATUS_CATEGORY$3) moves.push(move);
38153
+ if (move !== void 0 && move.category !== STATUS_CATEGORY$2) moves.push(move);
38214
38154
  }
38215
38155
  return moves;
38216
38156
  }
@@ -38231,15 +38171,14 @@ function resolveOptionalName$1(resolver, name) {
38231
38171
  /**
38232
38172
  * ポケモン名を pokemon.json のエントリに解決する。
38233
38173
  */
38234
- function resolvePokemonEntry$4(name) {
38174
+ function resolvePokemonEntry$3(name) {
38235
38175
  const englishName = pokemonNameResolver.toEnglish(name) ?? (pokemonNameResolver.hasEnglishName(name) ? name : null);
38236
38176
  if (englishName === null) {
38237
38177
  const suggestions = pokemonNameResolver.suggestSimilar(name);
38238
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
38239
- throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
38178
+ throw new UserFacingError(`ポケモン「${name}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
38240
38179
  }
38241
38180
  const entry = pokemonById.get(toDataId(englishName));
38242
- if (entry === void 0) throw new Error(`ポケモン「${name}」のデータが見つかりません。`);
38181
+ if (entry === void 0) throw new UserFacingError(`ポケモン「${name}」のデータが見つかりません。`);
38243
38182
  return entry;
38244
38183
  }
38245
38184
  /**
@@ -38249,7 +38188,7 @@ function normalizeMovesMap(moves) {
38249
38188
  const result = /* @__PURE__ */ new Map();
38250
38189
  if (moves === void 0) return result;
38251
38190
  for (const [pokemonName, moveList] of Object.entries(moves)) {
38252
- const entry = resolvePokemonEntry$4(pokemonName);
38191
+ const entry = resolvePokemonEntry$3(pokemonName);
38253
38192
  result.set(entry.id, moveList);
38254
38193
  }
38255
38194
  return result;
@@ -38329,12 +38268,12 @@ function updateBestAttackers(currentMax, bestAttackers, candidate) {
38329
38268
  * MCP tool handler からも直接テストからも呼び出せる。
38330
38269
  */
38331
38270
  function analyzePartyCoverage(args) {
38332
- const gen = Generations.get(CHAMPIONS_GEN_NUM$9);
38271
+ const gen = Generations.get(CHAMPIONS_GEN_NUM$8);
38333
38272
  const movesMap = normalizeMovesMap(args.moves);
38334
38273
  const members = [];
38335
38274
  const attackingTypesSet = /* @__PURE__ */ new Set();
38336
38275
  for (const member of args.myParty) {
38337
- const entry = resolvePokemonEntry$4(member.name);
38276
+ const entry = resolvePokemonEntry$3(member.name);
38338
38277
  const rawAttackingMoves = resolveAttackingMoveIds(entry, movesMap.get(entry.id));
38339
38278
  const ability = resolveOptionalName$1(abilityNameResolver, member.ability);
38340
38279
  const attackingMoves = [];
@@ -38423,7 +38362,7 @@ function analyzePartyCoverage(args) {
38423
38362
  };
38424
38363
  }
38425
38364
  function registerPartyCoverageTool(server) {
38426
- server.tool(TOOL_NAME$19, TOOL_DESCRIPTION$19, inputSchema$16, async (args) => {
38365
+ server.tool(TOOL_NAME$18, TOOL_DESCRIPTION$18, inputSchema$15, async (args) => {
38427
38366
  try {
38428
38367
  const output = analyzePartyCoverage(args);
38429
38368
  return withHint({
@@ -38431,47 +38370,37 @@ function registerPartyCoverageTool(server) {
38431
38370
  text: JSON.stringify(output)
38432
38371
  });
38433
38372
  } catch (error) {
38434
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
38435
- return {
38436
- content: [{
38437
- type: "text",
38438
- text: JSON.stringify({ error: message })
38439
- }],
38440
- isError: true
38441
- };
38373
+ return toErrorResponse(error);
38442
38374
  }
38443
38375
  });
38444
38376
  }
38445
38377
  // src/tools/analysis/compare-parties.ts
38446
- const CHAMPIONS_GEN_NUM$8 = 0;
38447
- /** 対戦に組めるパーティメンバーの上限 (ポケモンチャンピオンズ仕様) */
38448
- const MAX_PARTY_SIZE = 6;
38378
+ const CHAMPIONS_GEN_NUM$7 = 0;
38449
38379
  /** 性格未指定時の既定 (無補正性格) */
38450
38380
  const DEFAULT_NATURE_EN$1 = "Serious";
38451
- const TOOL_NAME$18 = "compare_parties";
38452
- const TOOL_DESCRIPTION$18 = "2 つのパーティ (A / B) の統計差分を比較する。メンバー差分・タイプ分布・弱点/耐性/カバレッジ集合・素早さ分布・種族値合計の構造化データを 1 コールで返す。 パーティ改修案の比較や入れ替え検討に使用する。優劣判定は行わず、差分データのみを返す (解釈は AI 側の責務)。 moves は指定できないため、カバレッジ差分は learnset 全攻撃技ベースで評価される。ポケモンチャンピオンズ対応。";
38381
+ const TOOL_NAME$17 = "compare_parties";
38382
+ const TOOL_DESCRIPTION$17 = "2 つのパーティ (A / B) の統計差分を比較する。メンバー差分・タイプ分布・弱点/耐性/カバレッジ集合・素早さ分布・種族値合計の構造化データを 1 コールで返す。 パーティ改修案の比較や入れ替え検討に使用する。優劣判定は行わず、差分データのみを返す (解釈は AI 側の責務)。 moves は指定できないため、カバレッジ差分は learnset 全攻撃技ベースで評価される。ポケモンチャンピオンズ対応。";
38453
38383
  const labelsSchema = z.object({
38454
- partyA: z.string().optional(),
38455
- partyB: z.string().optional()
38384
+ partyA: z.string().max(50).optional(),
38385
+ partyB: z.string().max(50).optional()
38456
38386
  }).optional().describe("表示用ラベル (例: { partyA: '現行', partyB: '改修案' })");
38457
- const inputSchema$15 = {
38458
- partyA: z.array(pokemonSchema).min(1).max(MAX_PARTY_SIZE).describe("比較対象のパーティ A"),
38459
- partyB: z.array(pokemonSchema).min(1).max(MAX_PARTY_SIZE).describe("比較対象のパーティ B"),
38387
+ const inputSchema$14 = {
38388
+ partyA: z.array(pokemonSchema).min(1).max(6).describe("比較対象のパーティ A"),
38389
+ partyB: z.array(pokemonSchema).min(1).max(6).describe("比較対象のパーティ B"),
38460
38390
  labels: labelsSchema
38461
38391
  };
38462
38392
  /**
38463
38393
  * ポケモン名を pokemon.json のエントリに解決する。
38464
38394
  * 未登録名は類似候補付きエラーを投げる。
38465
38395
  */
38466
- function resolvePokemonEntry$3(name) {
38396
+ function resolvePokemonEntry$2(name) {
38467
38397
  const englishName = pokemonNameResolver.toEnglish(name) ?? (pokemonNameResolver.hasEnglishName(name) ? name : null);
38468
38398
  if (englishName === null) {
38469
38399
  const suggestions = pokemonNameResolver.suggestSimilar(name);
38470
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
38471
- throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
38400
+ throw new UserFacingError(`ポケモン「${name}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
38472
38401
  }
38473
38402
  const entry = pokemonById.get(toDataId(englishName));
38474
- if (entry === void 0) throw new Error(`ポケモン「${name}」のデータが見つかりません。`);
38403
+ if (entry === void 0) throw new UserFacingError(`ポケモン「${name}」のデータが見つかりません。`);
38475
38404
  return entry;
38476
38405
  }
38477
38406
  /**
@@ -38483,8 +38412,7 @@ function resolveNatureName$1(nature) {
38483
38412
  if (englishName !== void 0) return englishName;
38484
38413
  if (natureNameResolver.hasEnglishName(nature)) return nature;
38485
38414
  const suggestions = natureNameResolver.suggestSimilar(nature);
38486
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
38487
- throw new Error(`性格「${nature}」が見つかりません。${suggestionMessage}`);
38415
+ throw new UserFacingError(`性格「${nature}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
38488
38416
  }
38489
38417
  /**
38490
38418
  * pokemon.json のエントリから @smogon/calc 用 overrides を組み立てる。
@@ -38517,7 +38445,7 @@ function toMemberRef(entry) {
38517
38445
  }
38518
38446
  function resolveMembers(party) {
38519
38447
  return party.map((input) => {
38520
- const entry = resolvePokemonEntry$3(input.name);
38448
+ const entry = resolvePokemonEntry$2(input.name);
38521
38449
  return {
38522
38450
  input,
38523
38451
  entry,
@@ -38619,7 +38547,7 @@ function computeCoverageDiff(partyA, partyB) {
38619
38547
  * パーティ比較の純関数。MCP ツールハンドラとテストから共通で利用する。
38620
38548
  */
38621
38549
  function comparePartiesAnalysis(args) {
38622
- const gen = Generations.get(CHAMPIONS_GEN_NUM$8);
38550
+ const gen = Generations.get(CHAMPIONS_GEN_NUM$7);
38623
38551
  const membersA = resolveMembers(args.partyA);
38624
38552
  const membersB = resolveMembers(args.partyB);
38625
38553
  const partyASummary = buildPartySummary(membersA, args.labels?.partyA, gen);
@@ -38652,7 +38580,7 @@ function comparePartiesAnalysis(args) {
38652
38580
  };
38653
38581
  }
38654
38582
  function registerComparePartiesTool(server) {
38655
- server.tool(TOOL_NAME$18, TOOL_DESCRIPTION$18, inputSchema$15, async (args) => {
38583
+ server.tool(TOOL_NAME$17, TOOL_DESCRIPTION$17, inputSchema$14, async (args) => {
38656
38584
  try {
38657
38585
  const output = comparePartiesAnalysis(args);
38658
38586
  return withHint({
@@ -38660,29 +38588,22 @@ function registerComparePartiesTool(server) {
38660
38588
  text: JSON.stringify(output)
38661
38589
  });
38662
38590
  } catch (error) {
38663
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
38664
- return {
38665
- content: [{
38666
- type: "text",
38667
- text: JSON.stringify({ error: message })
38668
- }],
38669
- isError: true
38670
- };
38591
+ return toErrorResponse(error);
38671
38592
  }
38672
38593
  });
38673
38594
  }
38674
38595
  // src/tools/info/condition-info.ts
38675
- const TOOL_NAME$17 = "get_condition_info";
38676
- const TOOL_DESCRIPTION$17 = "バトル条件(天候・フィールド・状態異常・サイド効果)の情報を取得する。category と name で絞り込める。省略時は全カテゴリ・全件を返す。ポケモンチャンピオンズ対応。";
38596
+ const TOOL_NAME$16 = "get_condition_info";
38597
+ const TOOL_DESCRIPTION$16 = "バトル条件(天候・フィールド・状態異常・サイド効果)の情報を取得する。category と name で絞り込める。省略時は全カテゴリ・全件を返す。ポケモンチャンピオンズ対応。";
38677
38598
  const CATEGORY_VALUES = [
38678
38599
  "weather",
38679
38600
  "terrain",
38680
38601
  "status",
38681
38602
  "sideCondition"
38682
38603
  ];
38683
- const inputSchema$14 = {
38604
+ const inputSchema$13 = {
38684
38605
  category: z.enum(CATEGORY_VALUES).optional().describe("絞り込むカテゴリ(weather: 天候 / terrain: フィールド / status: 状態異常 / sideCondition: サイド効果)。省略時は全カテゴリ。"),
38685
- name: z.string().optional().describe("絞り込む条件名(日本語 or 英語)。省略時は全件。")
38606
+ name: nameInputSchema.optional().describe("絞り込む条件名(日本語 or 英語)。省略時は全件。")
38686
38607
  };
38687
38608
  /**
38688
38609
  * 指定された name に合致するエントリだけを返す。
@@ -38701,7 +38622,7 @@ function resolveCategoryEntries(category, name) {
38701
38622
  return filterByName(entries, name);
38702
38623
  }
38703
38624
  function registerConditionInfoTool(server) {
38704
- server.tool(TOOL_NAME$17, TOOL_DESCRIPTION$17, inputSchema$14, async (args) => {
38625
+ server.tool(TOOL_NAME$16, TOOL_DESCRIPTION$16, inputSchema$13, async (args) => {
38705
38626
  try {
38706
38627
  const output = {};
38707
38628
  const targetCategories = args.category !== void 0 ? [args.category] : CATEGORY_VALUES;
@@ -38711,14 +38632,7 @@ function registerConditionInfoTool(server) {
38711
38632
  text: JSON.stringify(output)
38712
38633
  });
38713
38634
  } catch (error) {
38714
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
38715
- return {
38716
- content: [{
38717
- type: "text",
38718
- text: JSON.stringify({ error: message })
38719
- }],
38720
- isError: true
38721
- };
38635
+ return toErrorResponse(error);
38722
38636
  }
38723
38637
  });
38724
38638
  }
@@ -38729,33 +38643,43 @@ const damageCalculator = new DamageCalculatorAdapter({
38729
38643
  ability: abilityNameResolver,
38730
38644
  item: itemNameResolver,
38731
38645
  nature: natureNameResolver
38732
- }, pokemonEntryProvider);
38646
+ }, pokemonEntryProvider, learnsetProvider);
38733
38647
  // src/tools/calc/damage-calculation.ts
38734
38648
  const damageCalcInputSchema = {
38735
38649
  attacker: pokemonSchema.describe("攻撃側ポケモン"),
38736
38650
  defender: pokemonSchema.describe("防御側ポケモン"),
38737
- moveName: z.string().describe("技名(日本語 or 英語)"),
38651
+ moveName: nameInputSchema.describe("技名(日本語 or 英語)"),
38738
38652
  conditions: conditionsSchema.optional().describe("バトル条件")
38739
38653
  };
38740
38654
  const SINGLE_TOOL_NAME = "calculate_damage_single";
38741
38655
  const SINGLE_TOOL_DESCRIPTION = "ポケモンのダメージ計算を行うツール。攻撃側ポケモンの指定した1技が防御側ポケモンに与えるダメージを計算する。ポケモンチャンピオンズ (Pokemon Champions) の対戦仕様に対応。重要: 能力ポイント(evs) は各ステ 0-32・合計 0-66 で指定すること (従来の努力値 252/510 上限ではない)。レベル 50・個体値 31 固定。育成データは省略可能で、省略時はデフォルト値で計算される。正確な計算のため攻撃側・防御側の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
38742
38656
  const ALL_MOVES_TOOL_NAME = "calculate_damage_all_moves";
38743
- const ALL_MOVES_TOOL_DESCRIPTION = "ポケモン対戦で攻撃側ポケモンの全攻撃技のダメージを一括計算する。どの技が最も有効かを比較するときに使用する。ポケモンチャンピオンズ対応。正確な計算のため攻撃側・防御側の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
38657
+ const ALL_MOVES_TOOL_DESCRIPTION = "ポケモン対戦で攻撃側ポケモンの全攻撃技のダメージを一括計算する。どの技が最も有効かを比較するときに使用する。技ごとの結果はタイプ・相性・ダメージ割合・確定数の要約で、乱数の内訳は含まない。計算条件の説明文は最大打点の技にだけ付く。1 技の詳しい結果は calculate_damage_single で確認する。ポケモンチャンピオンズ対応。正確な計算のため攻撃側・防御側の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
38744
38658
  const allMovesInputSchema = {
38745
- attacker: pokemonSchema.describe("攻撃側ポケモン"),
38659
+ attacker: pokemonWithMovesSchema.describe("攻撃側ポケモン"),
38746
38660
  defender: pokemonSchema.describe("防御側ポケモン"),
38747
38661
  conditions: conditionsSchema.optional().describe("バトル条件")
38748
38662
  };
38749
38663
  const PARTY_MATCHUP_TOOL_NAME = "calculate_damage_party_matchup";
38750
38664
  const PARTY_MATCHUP_TOOL_DESCRIPTION = "パーティ対パーティの全組み合わせダメージ計算を行う。6vs6の全対面での火力関係を一覧する。ポケモン対戦の選出判断やパーティ構築の検討に使用する。正確な計算のため各ポケモンの ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
38751
38665
  const partyMatchupInputSchema = {
38752
- myParty: z.array(pokemonSchema).describe("自分のパーティ"),
38753
- opponentParty: z.array(pokemonSchema).describe("相手のパーティ"),
38666
+ myParty: z.array(pokemonWithMovesSchema).min(1).max(6).describe("自分のパーティ"),
38667
+ opponentParty: z.array(pokemonSchema).min(1).max(6).describe("相手のパーティ"),
38754
38668
  conditions: conditionsSchema.optional().describe("バトル条件")
38755
38669
  };
38670
+ /** ダメージを与えられる技がない対面の最大ダメージ割合。 */
38671
+ const NO_DAMAGE_PERCENT = 0;
38756
38672
  function extractBestMove(results, defenderNameEn, moveResolver) {
38757
- const best = results[0];
38758
38673
  const defenderNameJa = pokemonNameResolver.toJapanese(defenderNameEn) ?? defenderNameEn;
38674
+ if (results.length === 0) return {
38675
+ defender: defenderNameEn,
38676
+ defenderNameJa,
38677
+ bestMove: null,
38678
+ bestMoveJa: null,
38679
+ maxDamagePercent: NO_DAMAGE_PERCENT,
38680
+ koChance: null
38681
+ };
38682
+ const best = results[0];
38759
38683
  const bestMoveJa = moveResolver.toJapanese(best.move) ?? best.move;
38760
38684
  return {
38761
38685
  defender: defenderNameEn,
@@ -38766,7 +38690,7 @@ function extractBestMove(results, defenderNameEn, moveResolver) {
38766
38690
  koChance: best.koChance
38767
38691
  };
38768
38692
  }
38769
- function registerDamageCalculationTools(server) {
38693
+ function registerDamageCalculationTools(server, movesRequirement = MOVES_OPTIONAL) {
38770
38694
  server.tool(SINGLE_TOOL_NAME, SINGLE_TOOL_DESCRIPTION, damageCalcInputSchema, async (args) => {
38771
38695
  try {
38772
38696
  const result = damageCalculator.calculate({
@@ -38785,6 +38709,11 @@ function registerDamageCalculationTools(server) {
38785
38709
  });
38786
38710
  server.tool(ALL_MOVES_TOOL_NAME, ALL_MOVES_TOOL_DESCRIPTION, allMovesInputSchema, async (args) => {
38787
38711
  try {
38712
+ assertMovesSpecified(movesRequirement, [{
38713
+ field: "attacker",
38714
+ name: args.attacker.name,
38715
+ moves: args.attacker.moves
38716
+ }]);
38788
38717
  const results = damageCalculator.calculateAllMoves({
38789
38718
  attacker: args.attacker,
38790
38719
  defender: args.defender,
@@ -38795,7 +38724,7 @@ function registerDamageCalculationTools(server) {
38795
38724
  const output = {
38796
38725
  attacker: results.length > 0 ? results[0].attacker : attackerNameEn,
38797
38726
  defender: results.length > 0 ? results[0].defender : defenderNameEn,
38798
- results
38727
+ results: summarizeMoveDamages(results, (en) => moveNameResolver.toJapanese(en))
38799
38728
  };
38800
38729
  return withHint({
38801
38730
  type: "text",
@@ -38807,6 +38736,11 @@ function registerDamageCalculationTools(server) {
38807
38736
  });
38808
38737
  server.tool(PARTY_MATCHUP_TOOL_NAME, PARTY_MATCHUP_TOOL_DESCRIPTION, partyMatchupInputSchema, async (args) => {
38809
38738
  try {
38739
+ assertMovesSpecified(movesRequirement, args.myParty.map((member, index) => ({
38740
+ field: `myParty[${index}]`,
38741
+ name: member.name,
38742
+ moves: member.moves
38743
+ })));
38810
38744
  const output = {
38811
38745
  myParty: [],
38812
38746
  opponentParty: [],
@@ -38832,10 +38766,8 @@ function registerDamageCalculationTools(server) {
38832
38766
  defender,
38833
38767
  conditions: args.conditions
38834
38768
  });
38835
- if (results.length > 0) {
38836
- const defenderNameEn = results[0].defender;
38837
- attackerEntry.results.push(extractBestMove(results, defenderNameEn, moveNameResolver));
38838
- }
38769
+ const { resolvedName: defenderNameEn } = damageCalculator.createPokemonObject(defender);
38770
+ attackerEntry.results.push(extractBestMove(results, defenderNameEn, moveNameResolver));
38839
38771
  }
38840
38772
  output.matchups.push(attackerEntry);
38841
38773
  }
@@ -38852,12 +38784,12 @@ function registerDamageCalculationTools(server) {
38852
38784
  /** 探索に使う SP 候補ステップ(細かさ)。4 きざみで枝刈り → hit したら 1 きざみで微調整 */
38853
38785
  const SP_COARSE_STEP = 4;
38854
38786
  const SP_FINE_STEP = 1;
38855
- const TOOL_NAME$16 = "analyze_damage_range";
38856
- const TOOL_DESCRIPTION$16 = "ダメージ計算を逆引きして、防御側を耐えさせるために必要な最小 SP 配分を探索する。`damage` には min/max ダメージと % を、`nHitKo` には確定 X 発の数を、`survivalSpConfig` には確定耐えに必要な最小 SP 配分を返す。ポケモンチャンピオンズ仕様(SP 各 0-32 / 合計 0-66)で計算。正確な計算のため攻撃側・防御側の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
38857
- const inputSchema$13 = {
38787
+ const TOOL_NAME$15 = "analyze_damage_range";
38788
+ const TOOL_DESCRIPTION$15 = "ダメージ計算を逆引きして、防御側を耐えさせるために必要な最小 SP 配分を探索する。`damage` には min/max ダメージと % を、`nHitKo` には確定 X 発の数を、`survivalSpConfig` には確定耐えに必要な最小 SP 配分を返す。ポケモンチャンピオンズ仕様(SP 各 0-32 / 合計 0-66)で計算。正確な計算のため攻撃側・防御側の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
38789
+ const inputSchema$12 = {
38858
38790
  attacker: pokemonSchema.describe("攻撃側ポケモン"),
38859
38791
  defender: pokemonSchema.describe("防御側ポケモン"),
38860
- moveName: z.string().describe("技名(日本語 or 英語)"),
38792
+ moveName: nameInputSchema.describe("技名(日本語 or 英語)"),
38861
38793
  conditions: conditionsSchema.optional().describe("バトル条件")
38862
38794
  };
38863
38795
  /**
@@ -38986,16 +38918,16 @@ function findMinimalSurvivalSp(damageCalculator, attacker, defender, moveName, c
38986
38918
  };
38987
38919
  }
38988
38920
  function registerDamageRangeTool(server) {
38989
- server.tool(TOOL_NAME$16, TOOL_DESCRIPTION$16, inputSchema$13, async (args) => {
38921
+ server.tool(TOOL_NAME$15, TOOL_DESCRIPTION$15, inputSchema$12, async (args) => {
38990
38922
  try {
38991
38923
  const moveEn = moveNameResolver.toEnglish(args.moveName) ?? (moveNameResolver.hasEnglishName(args.moveName) ? args.moveName : null);
38992
38924
  if (moveEn === null) {
38993
38925
  const suggestions = moveNameResolver.suggestSimilar(args.moveName);
38994
38926
  const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
38995
- throw new Error(`技「${args.moveName}」が見つかりません。${suggestionMessage}`);
38927
+ throw new UserFacingError(`技「${args.moveName}」が見つかりません。${suggestionMessage}`);
38996
38928
  }
38997
38929
  const moveEntry = movesById.get(toDataId(moveEn));
38998
- if (moveEntry === void 0) throw new Error(`技「${args.moveName}」はチャンピオンズでは使用できません。`);
38930
+ if (moveEntry === void 0) throw new UserFacingError(`技「${args.moveName}」はチャンピオンズでは使用できません。`);
38999
38931
  const { pokemon: defObj } = damageCalculator.createPokemonObject(args.defender);
39000
38932
  const defenderMaxHp = defObj.maxHP();
39001
38933
  let baseResult = null;
@@ -39043,549 +38975,15 @@ function registerDamageRangeTool(server) {
39043
38975
  type: "text",
39044
38976
  text: JSON.stringify(output)
39045
38977
  });
39046
- } catch (error) {
39047
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
39048
- return {
39049
- content: [{
39050
- type: "text",
39051
- text: JSON.stringify({ error: message })
39052
- }],
39053
- isError: true
39054
- };
39055
- }
39056
- });
39057
- }
39058
- // src/tools/analysis/find-counters.ts
39059
- const CHAMPIONS_GEN_NUM$7 = 0;
39060
- /** 弱点タイプ判定のしきい値(候補プール抽出で使用) */
39061
- const SUPER_EFFECTIVE_MIN = 2;
39062
- /** Status 技 */
39063
- const STATUS_CATEGORY$2 = "Status";
39064
- const TOOL_NAME$15 = "find_counters";
39065
- const TOOL_DESCRIPTION$15 = "target の弱点タイプ攻撃技を持つポケモンを候補プールとして抽出し、各候補の双方向ダメ計・素早さ・タイプ相性を返す。`candidatePool` は文字列(名前のみ)と PokemonInput オブジェクト(ability / item / nature / evs 指定)を混在可能で、同一ポケモンの build 違い比較にも対応する。正確な計算のため target 側の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。判断(受け型か速度勝ち型か等)は AI が行う前提。ポケモンチャンピオンズ対応。";
39066
- const battleFormatValues = ["singles", "doubles"];
39067
- const candidatePoolItemSchema = z.union([z.string(), pokemonSchema]);
39068
- const inputSchema$12 = {
39069
- target: pokemonSchema.describe("対策したい相手ポケモン"),
39070
- candidatePool: z.array(candidatePoolItemSchema).optional().describe("候補プール。各要素は「ポケモン名の文字列(簡易指定、デフォルト build で評価)」または「PokemonInput オブジェクト(name に加え ability / item / nature / evs / boosts / status を指定可能)」。同じポケモン名でも build 違いを並列で比較できる。未指定時は target の弱点タイプ攻撃技を覚える Champions 全ポケモンから自動選定(デフォルト build 評価)。"),
39071
- battleFormat: z.enum(battleFormatValues).optional().describe("対戦形式(省略時: singles)")
39072
- };
39073
- /**
39074
- * extractPriorityMoves 用の move 解決。learnset ID から MoveEntry を引く。
39075
- */
39076
- function resolveMoveForPriority$1(id) {
39077
- return movesById.get(id);
39078
- }
39079
- /**
39080
- * extractPriorityMoves 用の日本語名解決。
39081
- */
39082
- function moveToJapanese$1(en) {
39083
- return moveNameResolver.toJapanese(en);
39084
- }
39085
- /**
39086
- * 指定ポケモン ID の learnset から先制技のみを抽出する。
39087
- * learnset データが無い場合は空配列を返す。
39088
- */
39089
- function buildPriorityMoves(pokemonId) {
39090
- return extractPriorityMoves({
39091
- learnsetMoveIds: championsLearnsets[pokemonId] ?? [],
39092
- resolveMove: resolveMoveForPriority$1,
39093
- toJapanese: moveToJapanese$1
39094
- });
39095
- }
39096
- /**
39097
- * ポケモン名を pokemon.json のエントリに解決する。
39098
- */
39099
- function resolvePokemonEntry$2(name) {
39100
- const englishName = pokemonNameResolver.toEnglish(name) ?? (pokemonNameResolver.hasEnglishName(name) ? name : null);
39101
- if (englishName === null) {
39102
- const suggestions = pokemonNameResolver.suggestSimilar(name);
39103
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
39104
- throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
39105
- }
39106
- const entry = pokemonById.get(toDataId(englishName));
39107
- if (entry === void 0) throw new Error(`ポケモン「${name}」のデータが見つかりません。`);
39108
- return entry;
39109
- }
39110
- /**
39111
- * 攻撃タイプから防御タイプ配列への複合倍率を算出する。
39112
- */
39113
- function calcMultiplier(attackTypeName, defenderTypes, gen) {
39114
- return calculateTypeEffectiveness(gen, attackTypeName, defenderTypes);
39115
- }
39116
- /**
39117
- * target のタイプに対して 2 倍以上の弱点タイプを洗い出す。
39118
- */
39119
- function findTypeWeaknesses(defenderTypes, gen) {
39120
- const typeJaMap = new Map(championsTypes.map((t) => [t.name, t.nameJa]));
39121
- const weaknesses = [];
39122
- for (const attackerType of championsTypes) {
39123
- const m = calcMultiplier(attackerType.name, defenderTypes, gen);
39124
- if (m >= SUPER_EFFECTIVE_MIN) weaknesses.push({
39125
- type: attackerType.name,
39126
- nameJa: typeJaMap.get(attackerType.name) ?? attackerType.name,
39127
- multiplier: m
39128
- });
39129
- }
39130
- weaknesses.sort((a, b) => {
39131
- if (a.multiplier !== b.multiplier) return b.multiplier - a.multiplier;
39132
- return a.type.localeCompare(b.type);
39133
- });
39134
- return weaknesses;
39135
- }
39136
- /**
39137
- * ポケモンが指定タイプ集合のいずれかに属する攻撃技を覚えるかを判定する。
39138
- * 前フィルタとして使用。
39139
- */
39140
- function hasAttackingMoveOfAnyType(pokemonId, weaknessTypes) {
39141
- const learnset = championsLearnsets[pokemonId];
39142
- if (learnset === void 0) return false;
39143
- for (const moveId of learnset) {
39144
- const move = movesById.get(moveId);
39145
- if (move === void 0) continue;
39146
- if (move.category === STATUS_CATEGORY$2) continue;
39147
- if (weaknessTypes.has(move.type)) return true;
39148
- }
39149
- return false;
39150
- }
39151
- /**
39152
- * ターゲットのタイプに対して弱点となるタイプ集合を算出する。
39153
- */
39154
- function buildWeaknessTypeSet(targetTypes, gen) {
39155
- const set = /* @__PURE__ */ new Set();
39156
- for (const attackerType of championsTypes) if (calcMultiplier(attackerType.name, targetTypes, gen) >= SUPER_EFFECTIVE_MIN) set.add(attackerType.name);
39157
- return set;
39158
- }
39159
- /**
39160
- * PokemonInput から build 部分(name 以外)を抽出する。
39161
- * 省略されたフィールドは含めない。
39162
- */
39163
- function extractBuildInfo(input) {
39164
- const build = {};
39165
- if (input.ability !== void 0) build.ability = input.ability;
39166
- if (input.item !== void 0) build.item = input.item;
39167
- if (input.nature !== void 0) build.nature = input.nature;
39168
- if (input.evs !== void 0) build.evs = input.evs;
39169
- if (input.boosts !== void 0) build.boosts = input.boosts;
39170
- if (input.status !== void 0) build.status = input.status;
39171
- return build;
39172
- }
39173
- /**
39174
- * 候補のソート用 tiebreaker として使う安定的な署名を生成する。
39175
- * 同名ポケモンの build 違いを区別する。build 未指定(string or 自動選定)は "default" 扱い。
39176
- */
39177
- function buildSignature(candidate) {
39178
- if (!candidate.hasExplicitBuild) return "default";
39179
- return JSON.stringify(extractBuildInfo(candidate.input));
39180
- }
39181
- /**
39182
- * 候補プールを決定する。
39183
- * - candidatePool 指定時: 各要素(string or PokemonInput)を正規化して CandidateBuild 配列で返す。
39184
- * - 未指定時: target のタイプ弱点を攻撃技として持つ全 Champions ポケモンに絞る(デフォルト build)。
39185
- */
39186
- function buildCandidateEntries(candidatePool, target, gen) {
39187
- if (candidatePool !== void 0) {
39188
- const candidates = [];
39189
- for (const item of candidatePool) if (typeof item === "string") {
39190
- const entry = resolvePokemonEntry$2(item);
39191
- candidates.push({
39192
- entry,
39193
- input: { name: entry.name },
39194
- hasExplicitBuild: false
39195
- });
39196
- } else {
39197
- const entry = resolvePokemonEntry$2(item.name);
39198
- candidates.push({
39199
- entry,
39200
- input: {
39201
- ...item,
39202
- name: entry.name
39203
- },
39204
- hasExplicitBuild: true
39205
- });
39206
- }
39207
- return candidates;
39208
- }
39209
- const weaknessTypes = buildWeaknessTypeSet(target.types, gen);
39210
- return (weaknessTypes.size === 0 ? [...championsPokemon].filter((p) => p.id !== target.id) : championsPokemon.filter((p) => p.id !== target.id && hasAttackingMoveOfAnyType(p.id, weaknessTypes))).map((entry) => ({
39211
- entry,
39212
- input: { name: entry.name },
39213
- hasExplicitBuild: false
39214
- }));
39215
- }
39216
- function registerFindCountersTool(server) {
39217
- server.tool(TOOL_NAME$15, TOOL_DESCRIPTION$15, inputSchema$12, async (args) => {
39218
- try {
39219
- const gen = Generations.get(CHAMPIONS_GEN_NUM$7);
39220
- const damageConditions = { battleFormat: args.battleFormat };
39221
- const targetEntry = resolvePokemonEntry$2(args.target.name);
39222
- const { pokemon: targetObj, resolvedName: targetName } = damageCalculator.createPokemonObject(args.target);
39223
- const targetNameJa = pokemonNameResolver.toJapanese(targetName) ?? targetName;
39224
- const typeWeaknesses = findTypeWeaknesses(targetEntry.types, gen);
39225
- const targetStats = {
39226
- hp: targetObj.stats.hp,
39227
- atk: targetObj.stats.atk,
39228
- def: targetObj.stats.def,
39229
- spa: targetObj.stats.spa,
39230
- spd: targetObj.stats.spd,
39231
- spe: targetObj.stats.spe
39232
- };
39233
- const candidateBuilds = buildCandidateEntries(args.candidatePool, targetEntry, gen);
39234
- const counterEntries = [];
39235
- for (const candidate of candidateBuilds) {
39236
- const candidateEntry = candidate.entry;
39237
- const candidateInput = candidate.input;
39238
- let candidateObj;
39239
- try {
39240
- candidateObj = damageCalculator.createPokemonObject(candidateInput).pokemon;
39241
- } catch {
39242
- continue;
39243
- }
39244
- let outgoing = [];
39245
- let incoming = [];
39246
- try {
39247
- outgoing = filterResultsByLearnset(damageCalculator.calculateAllMoves({
39248
- attacker: candidateInput,
39249
- defender: args.target,
39250
- conditions: damageConditions
39251
- }), getLearnsetMoveIdSet(candidateEntry.id), toDataId);
39252
- } catch {
39253
- outgoing = [];
39254
- }
39255
- try {
39256
- incoming = filterResultsByLearnset(damageCalculator.calculateAllMoves({
39257
- attacker: args.target,
39258
- defender: candidateInput,
39259
- conditions: damageConditions
39260
- }), getLearnsetMoveIdSet(targetEntry.id), toDataId);
39261
- } catch {
39262
- incoming = [];
39263
- }
39264
- const speedCompare = compareSpeed(candidateObj.stats.spe, targetObj.stats.spe);
39265
- const nameJa = candidateEntry.nameJa ?? candidateEntry.name;
39266
- const pokemonProfile = {
39267
- id: candidateEntry.id,
39268
- name: candidateEntry.name,
39269
- nameJa,
39270
- types: [...candidateEntry.types],
39271
- baseStats: { ...candidateEntry.baseStats },
39272
- abilities: [...candidateEntry.abilities]
39273
- };
39274
- if (candidate.hasExplicitBuild) pokemonProfile.build = extractBuildInfo(candidateInput);
39275
- counterEntries.push({
39276
- pokemon: pokemonProfile,
39277
- speedCompare,
39278
- outgoing,
39279
- incoming,
39280
- priorityMoves: buildPriorityMoves(candidateEntry.id),
39281
- sortKey: buildSignature(candidate)
39282
- });
39283
- }
39284
- counterEntries.sort((a, b) => {
39285
- const nameOrder = a.pokemon.name.localeCompare(b.pokemon.name);
39286
- if (nameOrder !== 0) return nameOrder;
39287
- return a.sortKey.localeCompare(b.sortKey);
39288
- });
39289
- const output = {
39290
- target: {
39291
- name: targetName,
39292
- nameJa: targetNameJa,
39293
- stats: targetStats,
39294
- typeWeaknesses,
39295
- priorityMoves: buildPriorityMoves(targetEntry.id)
39296
- },
39297
- counters: counterEntries.map(({ sortKey: _sortKey, ...rest }) => rest)
39298
- };
39299
- return withHint({
39300
- type: "text",
39301
- text: JSON.stringify(output)
39302
- });
39303
- } catch (error) {
39304
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
39305
- return {
39306
- content: [{
39307
- type: "text",
39308
- text: JSON.stringify({ error: message })
39309
- }],
39310
- isError: true
39311
- };
39312
- }
39313
- });
39314
- }
39315
- // src/party-store.ts
39316
- /** ai-rotom の永続化用ディレクトリ名 (ホーム直下)。 */
39317
- const AI_ROTOM_DIR_NAME = ".ai-rotom";
39318
- /** パーティ永続化ファイル名。 */
39319
- const PARTIES_FILE_NAME = "parties.json";
39320
- /** atomic write 用の一時ファイル拡張子。 */
39321
- const TEMP_FILE_EXT = ".tmp";
39322
- /** JSON.stringify の indent。 */
39323
- const JSON_INDENT = 2;
39324
- /** 一時ファイル名用のランダムサフィックスバイト数。 */
39325
- const TEMP_SUFFIX_BYTES = 8;
39326
- /**
39327
- * 永続化ファイル (`~/.ai-rotom/parties.json`) の絶対パスを返す。
39328
- * ホームディレクトリが解決できない場合はエラーを投げる。
39329
- */
39330
- function resolvePartiesFilePath() {
39331
- const home = homedir();
39332
- if (home === "" || home === void 0 || home === null) throw new Error("ホームディレクトリが解決できませんでした。$HOME 環境変数を確認してください。");
39333
- return join(home, AI_ROTOM_DIR_NAME, PARTIES_FILE_NAME);
39334
- }
39335
- /**
39336
- * 永続化ファイルの読み込み結果。
39337
- * 存在しない場合は空の PartiesFile を返す。
39338
- * 破損・権限・schemaVersion 不整合の場合はエラーを投げる。
39339
- */
39340
- function loadPartiesFile(filePath = resolvePartiesFilePath()) {
39341
- let raw;
39342
- try {
39343
- raw = readFileSync(filePath, { encoding: "utf-8" });
39344
- } catch (error) {
39345
- if (isNodeErrnoException(error) && error.code === "ENOENT") return {
39346
- schemaVersion: 1,
39347
- parties: []
39348
- };
39349
- throw wrapIoError("パーティファイルの読み込みに失敗しました", error);
39350
- }
39351
- let parsed;
39352
- try {
39353
- parsed = JSON.parse(raw);
39354
- } catch (error) {
39355
- const cause = error instanceof Error ? error.message : String(error);
39356
- throw new Error(`パーティファイル (${filePath}) の JSON パースに失敗しました: ${cause}`);
39357
- }
39358
- const result = partiesFileSchema.safeParse(parsed);
39359
- if (!result.success) {
39360
- const issues = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
39361
- throw new Error(`パーティファイル (${filePath}) のスキーマ検証に失敗しました: ${issues}`);
39362
- }
39363
- if (result.data.schemaVersion !== 1) throw new Error(`未対応の schemaVersion (${result.data.schemaVersion}) です。現行は 1 です。`);
39364
- return result.data;
39365
- }
39366
- /**
39367
- * 永続化ファイルを atomic に書き込む。
39368
- * 親ディレクトリが存在しない場合は作成する。
39369
- * 一時ファイル → rename で置き換えるため、途中失敗でも元ファイルは壊れない。
39370
- */
39371
- function savePartiesFile(data, filePath = resolvePartiesFilePath()) {
39372
- const validated = partiesFileSchema.parse(data);
39373
- const dir = dirname(filePath);
39374
- try {
39375
- mkdirSync(dir, { recursive: true });
39376
- } catch (error) {
39377
- throw wrapIoError(`パーティ保存ディレクトリ (${dir}) の作成に失敗しました`, error);
39378
- }
39379
- const tempPath = `${filePath}.${randomBytes(TEMP_SUFFIX_BYTES).toString("hex")}${TEMP_FILE_EXT}`;
39380
- const serialized = JSON.stringify(validated, null, JSON_INDENT);
39381
- try {
39382
- writeFileSync(tempPath, serialized, {
39383
- encoding: "utf-8",
39384
- mode: 384
39385
- });
39386
- renameSync(tempPath, filePath);
39387
- } catch (error) {
39388
- try {
39389
- rmSync(tempPath, { force: true });
39390
- } catch {}
39391
- throw wrapIoError(`パーティファイル (${filePath}) の保存に失敗しました`, error);
39392
- }
39393
- }
39394
- function isNodeErrnoException(value) {
39395
- return value instanceof Error && typeof value.code === "string";
39396
- }
39397
- function wrapIoError(prefix, error) {
39398
- const message = error instanceof Error ? error.message : String(error);
39399
- const code = isNodeErrnoException(error) && error.code !== void 0 ? ` [${error.code}]` : "";
39400
- return /* @__PURE__ */ new Error(`${prefix}${code}: ${message}`);
39401
- }
39402
- // src/party-text.ts
39403
- /** ポケソルテキストで性格を省略した場合のデフォルト。 */
39404
- const DEFAULT_NATURE_NAME = "まじめ";
39405
- /**
39406
- * ポケソルテキストを空行区切りで個別ブロックに分割する。
39407
- * 改行 (LF / CRLF) のどちらにも対応する。
39408
- * 空白のみのブロックは除外する。
39409
- */
39410
- function splitPokesolTextBlocks(text) {
39411
- return text.replace(/\r\n/g, "\n").split(/\n\s*\n/).map((block) => block.trim()).filter((block) => block.length > 0);
39412
- }
39413
- /**
39414
- * パーサー出力 (`PokesolTextParseReult`) を `PartyMember` に変換する。
39415
- * - `abilityNames[1..]` (括弧内のメガ前特性) が存在すれば最も元の状態 (末尾) を
39416
- * `ability` として保存 (通常状態の特性が基本。メガ進化時の特性変化は計算側の責務)
39417
- * - `natureName` が null の場合は `DEFAULT_NATURE_NAME` で補完
39418
- * - `terastalName` が存在する場合はポケチャン未対応のため無視
39419
- * - `moveNames` が空配列の場合は `moves` フィールド自体を省く
39420
- *
39421
- * 補完・無視を行った場合はブロック番号付きの warnings を返す。
39422
- */
39423
- function mapPokesolResultToPartyMember(result, blockNumber) {
39424
- const warnings = [];
39425
- if (result.pokemonName === null || result.pokemonName === "") throw new Error(`ブロック ${blockNumber}: ポケモン名が読み取れませんでした。`);
39426
- const member = { name: result.pokemonName };
39427
- if (result.itemName !== null) member.item = result.itemName;
39428
- const { ability, ignoredAbilities } = selectAbility(result.abilityNames);
39429
- if (ability !== void 0) {
39430
- member.ability = ability;
39431
- if (ignoredAbilities.length > 0) {
39432
- const ignored = ignoredAbilities.map((name) => `「${name}」`).join("");
39433
- warnings.push(`ブロック ${blockNumber}: メガ進化特性${ignored}は無視し、メガ前特性「${ability}」を ability として保存しました。`);
39434
- }
39435
- }
39436
- if (result.natureName !== null) member.nature = result.natureName;
39437
- else {
39438
- member.nature = DEFAULT_NATURE_NAME;
39439
- warnings.push(`ブロック ${blockNumber}: 性格が省略されていたためデフォルト「${DEFAULT_NATURE_NAME}」を補完しました。`);
39440
- }
39441
- if (result.terastalName !== null && result.terastalName !== "") warnings.push(`ブロック ${blockNumber}: テラスタイプ「${result.terastalName}」はポケモンチャンピオンズ未対応のため無視しました。`);
39442
- const evs = buildEvsFromResult(result.evs);
39443
- if (evs !== void 0) member.evs = evs;
39444
- if (result.moveNames.length > 0) member.moves = [...result.moveNames];
39445
- else warnings.push(`ブロック ${blockNumber}: 技行が省略されていたため moves を空で登録しました。`);
39446
- return {
39447
- member,
39448
- warnings
39449
- };
39450
- }
39451
- /**
39452
- * パーサー出力の `abilityNames` から `PartyMember.ability` に保存する特性を選ぶ。
39453
- * `abilityNames` は `[現在の特性, ...括弧内の以前の特性]` の順で、
39454
- * 特性名が省略された位置 (`特性: (さめはだ)` の先頭など) は null になる。
39455
- *
39456
- * - 括弧内に特性があれば、最も元の状態である末尾の特性を採用する
39457
- * - 括弧内が全て空なら現在の特性を採用する
39458
- * - 採用しなかった特性 (重複を除く) は ignoredAbilities として返す
39459
- */
39460
- function selectAbility(abilityNames) {
39461
- const names = abilityNames.filter((name) => name !== null);
39462
- const [currentAbility, ...previousAbilities] = abilityNames;
39463
- const ability = previousAbilities.filter((name) => name !== null).at(-1) ?? currentAbility ?? void 0;
39464
- return {
39465
- ability,
39466
- ignoredAbilities: [...new Set(names)].filter((name) => name !== ability)
39467
- };
39468
- }
39469
- /**
39470
- * パーサー出力の SP (努力値フィールド) を `EvsInput` に変換する。
39471
- * 全て 0 の場合は undefined を返し、`PartyMember.evs` を省く。
39472
- */
39473
- function buildEvsFromResult(parserEvs) {
39474
- const mapped = {
39475
- hp: parserEvs.hp,
39476
- atk: parserEvs.attack,
39477
- def: parserEvs.defense,
39478
- spa: parserEvs.specialAttack,
39479
- spd: parserEvs.specialDefense,
39480
- spe: parserEvs.speed
39481
- };
39482
- return Object.values(mapped).some((value) => value !== void 0 && value !== 0) ? mapped : void 0;
39483
- }
39484
- // src/tools/party/import-party-from-text.ts
39485
- const TOOL_NAME$14 = "import_party_from_text";
39486
- const TOOL_DESCRIPTION$14 = "ポケソルテキスト (Showdown 風に 1 匹あたり 3〜6 行・複数匹は空行区切り) からパーティを一括取り込みして保存する (upsert)。各メンバーはポケモン名 / 特性 / 性格 / 技 / 持ち物をポケチャン内の既知データと照合する。エラーがある場合は部分保存せず全体を失敗させる。";
39487
- /** ポケソルテキスト入力の最大文字数 (6 匹 × 数百文字 + メモ想定)。 */
39488
- const MAX_POKESOL_TEXT_LENGTH = 8e3;
39489
- const defaultNowProvider$1 = () => /* @__PURE__ */ new Date();
39490
- const defaultStoreIO$1 = {
39491
- load: () => loadPartiesFile(),
39492
- save: (data) => savePartiesFile(data)
39493
- };
39494
- const inputSchema$11 = {
39495
- text: z.string().min(1, { message: "ポケソルテキストは 1 文字以上で指定してください。" }).max(MAX_POKESOL_TEXT_LENGTH, { message: `ポケソルテキストは ${MAX_POKESOL_TEXT_LENGTH} 文字以下で指定してください。` }).describe("ポケソルテキスト。1 匹あたり 3〜6 行 (ポケモン名[@持ち物] / テラスタイプ行 省略可 / 特性 / 能力補正 / 実数値(SP) 省略可 / 技 省略可)。複数匹は空行で区切る。"),
39496
- name: z.string().min(1, { message: "パーティ名は 1 文字以上で指定してください。" }).max(50, { message: `パーティ名は 50 文字以下で指定してください。` }).describe("保存名 (識別子。同名は上書き)。"),
39497
- memo: z.string().max(MAX_PARTY_MEMO_LENGTH, { message: `メモは ${MAX_PARTY_MEMO_LENGTH} 文字以下で指定してください。` }).optional().describe("構築メモ (自由記述)。")
39498
- };
39499
- /**
39500
- * NameResolver の既知名 (日英どちらでも) として存在するかを判定する。
39501
- * 未知の場合は類似候補付きのメッセージを投げる。
39502
- */
39503
- function assertKnownName(resolver, name, label, blockNumber) {
39504
- if (resolver.hasJapaneseName(name) || resolver.hasEnglishName(name)) return;
39505
- const suggestions = resolver.suggestSimilar(name, 3);
39506
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
39507
- throw new Error(`ブロック ${blockNumber}: ${label}「${name}」が見つかりません。${suggestionMessage}`);
39508
- }
39509
- /**
39510
- * PartyMember の各名前フィールドを NameResolver で検証する。
39511
- * 未知名があれば該当ブロックのエラーとして throw。
39512
- */
39513
- function validateMemberNames(member, blockNumber) {
39514
- assertKnownName(pokemonNameResolver, member.name, "ポケモン名", blockNumber);
39515
- if (member.nature !== void 0) assertKnownName(natureNameResolver, member.nature, "性格", blockNumber);
39516
- if (member.ability !== void 0) assertKnownName(abilityNameResolver, member.ability, "特性", blockNumber);
39517
- if (member.item !== void 0) assertKnownName(itemNameResolver, member.item, "持ち物", blockNumber);
39518
- if (member.moves !== void 0) for (const move of member.moves) assertKnownName(moveNameResolver, move, "技", blockNumber);
39519
- }
39520
- /**
39521
- * 本ツールの全処理 (split → parse → map → validate → persist) を実行する。
39522
- * テストから直接呼び出せるようエクスポートする。
39523
- */
39524
- function runImportPartyFromText(input, deps = {}) {
39525
- const storeIO = deps.storeIO ?? defaultStoreIO$1;
39526
- const now = deps.now ?? defaultNowProvider$1;
39527
- const blocks = splitPokesolTextBlocks(input.text);
39528
- if (blocks.length < 1) throw new Error(`パーティには 1 匹以上を含めてください (検出: ${blocks.length} 匹)。`);
39529
- if (blocks.length > 6) throw new Error(`パーティには 6 匹までしか含められません (検出: ${blocks.length} 匹)。`);
39530
- const warnings = [];
39531
- const members = [];
39532
- blocks.forEach((block, index) => {
39533
- const blockNumber = index + 1;
39534
- let parsed;
39535
- try {
39536
- parsed = parse(block);
39537
- } catch (error) {
39538
- const reason = error instanceof Error ? error.message : String(error);
39539
- throw new Error(`ブロック ${blockNumber} のパースに失敗しました: ${reason}`);
39540
- }
39541
- const mapped = mapPokesolResultToPartyMember(parsed, blockNumber);
39542
- validateMemberNames(mapped.member, blockNumber);
39543
- members.push(mapped.member);
39544
- warnings.push(...mapped.warnings);
39545
- });
39546
- const file = storeIO.load();
39547
- const existingIndex = file.parties.findIndex((p) => p.name === input.name);
39548
- const nowIso = now().toISOString();
39549
- const createdAt = existingIndex >= 0 ? file.parties[existingIndex].createdAt : nowIso;
39550
- const party = {
39551
- name: input.name,
39552
- members,
39553
- createdAt,
39554
- updatedAt: nowIso
39555
- };
39556
- if (input.memo !== void 0) party.memo = input.memo;
39557
- partySchema.parse(party);
39558
- const nextParties = [...file.parties];
39559
- if (existingIndex >= 0) nextParties[existingIndex] = party;
39560
- else nextParties.push(party);
39561
- storeIO.save({
39562
- schemaVersion: 1,
39563
- parties: nextParties
39564
- });
39565
- return {
39566
- saved: true,
39567
- party,
39568
- warnings,
39569
- filePath: resolvePartiesFilePath(),
39570
- overwrote: existingIndex >= 0
39571
- };
39572
- }
39573
- /**
39574
- * import_party_from_text ツールをサーバーに登録する。
39575
- */
39576
- function registerImportPartyFromTextTool(server, deps = {}) {
39577
- server.tool(TOOL_NAME$14, TOOL_DESCRIPTION$14, inputSchema$11, async (args) => {
39578
- try {
39579
- return toTextResponse(runImportPartyFromText(args, deps));
39580
38978
  } catch (error) {
39581
38979
  return toErrorResponse(error);
39582
38980
  }
39583
38981
  });
39584
38982
  }
39585
38983
  // src/tools/info/item-info.ts
39586
- const TOOL_NAME$13 = "get_item_info";
39587
- const TOOL_DESCRIPTION$13 = "ポケモンの持ち物(アイテム)の詳細情報(効果説明、メガストーン情報)を取得する。ポケモンチャンピオンズで使える持ち物のみ返す。パーティ構築で持ち物を選ぶ際に使用する。";
39588
- const inputSchema$10 = { name: z.string().describe("持ち物名(日本語 or 英語)") };
38984
+ const TOOL_NAME$14 = "get_item_info";
38985
+ const TOOL_DESCRIPTION$14 = "ポケモンの持ち物(アイテム)の詳細情報(効果説明、メガストーン情報)を取得する。ポケモンチャンピオンズで使える持ち物のみ返す。パーティ構築で持ち物を選ぶ際に使用する。";
38986
+ const inputSchema$11 = { name: nameInputSchema.describe("持ち物名(日本語 or 英語)") };
39589
38987
  /**
39590
38988
  * 持ち物名を英語に解決する。日本語名・英語名どちらでも受け付ける。
39591
38989
  */
@@ -39594,15 +38992,14 @@ function resolveItemNameEn(input) {
39594
38992
  if (fromJa !== void 0) return fromJa;
39595
38993
  if (itemNameResolver.hasEnglishName(input)) return input;
39596
38994
  const suggestions = itemNameResolver.suggestSimilar(input);
39597
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
39598
- throw new Error(`持ち物「${input}」が見つかりません。${suggestionMessage}`);
38995
+ throw new UserFacingError(`持ち物「${input}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
39599
38996
  }
39600
38997
  function registerItemInfoTool(server) {
39601
- server.tool(TOOL_NAME$13, TOOL_DESCRIPTION$13, inputSchema$10, async (args) => {
38998
+ server.tool(TOOL_NAME$14, TOOL_DESCRIPTION$14, inputSchema$11, async (args) => {
39602
38999
  try {
39603
39000
  const itemId = toDataId(resolveItemNameEn(args.name));
39604
39001
  const entry = itemsById.get(itemId);
39605
- if (entry === void 0) throw new Error(`持ち物「${args.name}」はチャンピオンズでは使用できません。`);
39002
+ if (entry === void 0) throw new UserFacingError(`持ち物「${args.name}」はチャンピオンズでは使用できません。`);
39606
39003
  const isMegaStone = entry.megaStone !== null;
39607
39004
  const output = {
39608
39005
  name: entry.name,
@@ -39618,21 +39015,14 @@ function registerItemInfoTool(server) {
39618
39015
  text: JSON.stringify(output)
39619
39016
  });
39620
39017
  } catch (error) {
39621
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
39622
- return {
39623
- content: [{
39624
- type: "text",
39625
- text: JSON.stringify({ error: message })
39626
- }],
39627
- isError: true
39628
- };
39018
+ return toErrorResponse(error);
39629
39019
  }
39630
39020
  });
39631
39021
  }
39632
39022
  // src/tools/info/learnset.ts
39633
- const TOOL_NAME$12 = "get_learnset";
39634
- const TOOL_DESCRIPTION$12 = "ポケモンチャンピオンズで特定のポケモンが覚える技の一覧を取得する。「○○は何を覚える?」のようにポケモン名と覚える技が話題に出たら、知識ベースで即答せず、まずこのツールを呼んでデータを引くこと(チャンピオンズ固有の技プール変更=没収技等が反映される)。パーティ構築や技構成の検討に使用する。";
39635
- const inputSchema$9 = { name: z.string().describe("ポケモン名(日本語 or 英語)") };
39023
+ const TOOL_NAME$13 = "get_learnset";
39024
+ const TOOL_DESCRIPTION$13 = "ポケモンチャンピオンズで特定のポケモンが覚える技の一覧を取得する。「○○は何を覚える?」のようにポケモン名と覚える技が話題に出たら、知識ベースで即答せず、まずこのツールを呼んでデータを引くこと(チャンピオンズ固有の技プール変更=没収技等が反映される)。パーティ構築や技構成の検討に使用する。";
39025
+ const inputSchema$10 = { name: nameInputSchema.describe("ポケモン名(日本語 or 英語)") };
39636
39026
  /**
39637
39027
  * ポケモン名を英語に解決する。日本語名・英語名どちらでも受け付ける。
39638
39028
  */
@@ -39641,8 +39031,7 @@ function resolvePokemonNameEn(input) {
39641
39031
  if (fromJa !== void 0) return fromJa;
39642
39032
  if (pokemonNameResolver.hasEnglishName(input)) return input;
39643
39033
  const suggestions = pokemonNameResolver.suggestSimilar(input);
39644
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
39645
- throw new Error(`ポケモン「${input}」が見つかりません。${suggestionMessage}`);
39034
+ throw new UserFacingError(`ポケモン「${input}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
39646
39035
  }
39647
39036
  /**
39648
39037
  * 技 ID から出力用の英語名・日本語名ペアを組み立てる。
@@ -39660,12 +39049,12 @@ function buildLearnsetMoveEntry(moveId) {
39660
39049
  };
39661
39050
  }
39662
39051
  function registerLearnsetTool(server) {
39663
- server.tool(TOOL_NAME$12, TOOL_DESCRIPTION$12, inputSchema$9, async (args) => {
39052
+ server.tool(TOOL_NAME$13, TOOL_DESCRIPTION$13, inputSchema$10, async (args) => {
39664
39053
  try {
39665
39054
  const englishName = resolvePokemonNameEn(args.name);
39666
39055
  const pokemonId = toDataId(englishName);
39667
39056
  const moveIds = championsLearnsets[pokemonId];
39668
- if (moveIds === void 0) throw new Error(`ポケモン「${args.name}」のチャンピオンズ向け learnset データが見つかりません。`);
39057
+ if (moveIds === void 0) throw new UserFacingError(`ポケモン「${args.name}」のチャンピオンズ向け learnset データが見つかりません。`);
39669
39058
  const output = {
39670
39059
  pokemon: englishName,
39671
39060
  pokemonJa: pokemonNameResolver.toJapanese(englishName) ?? null,
@@ -39676,23 +39065,25 @@ function registerLearnsetTool(server) {
39676
39065
  text: JSON.stringify(output)
39677
39066
  });
39678
39067
  } catch (error) {
39679
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
39680
- return {
39681
- content: [{
39682
- type: "text",
39683
- text: JSON.stringify({ error: message })
39684
- }],
39685
- isError: true
39686
- };
39068
+ return toErrorResponse(error);
39687
39069
  }
39688
39070
  });
39689
39071
  }
39072
+ // src/calc/candidate-moves.ts
39073
+ /**
39074
+ * ポケモンが使う候補技の ID 一覧を返す。
39075
+ * 技構成の指定があればその技、なければ習得技すべて。
39076
+ */
39077
+ function candidateMoveIds(resolvedName, moves) {
39078
+ if (moves !== void 0 && moves.length > 0) return damageCalculator.resolveMoveNames(moves).map(toDataId);
39079
+ return [...learnsetProvider.getMoveIds(resolvedName)];
39080
+ }
39690
39081
  // src/tools/analysis/matchup.ts
39691
- const TOOL_NAME$11 = "analyze_matchup";
39692
- const TOOL_DESCRIPTION$11 = "ポケモン2体の対面を分析する。双方向のダメージ計算と素早さ比較を行い、どちらが有利かを判断するためのデータを提供する。ポケモン対戦の対面判断に使用する。pokemon1Faster は静的な素早さ実数値のみの比較のため、素早さ負けでも先制技で逆転できる判断は pokemon{1,2}PriorityMoves を併用すること。正確な計算のため双方の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
39082
+ const TOOL_NAME$12 = "analyze_matchup";
39083
+ const TOOL_DESCRIPTION$12 = "ポケモン2体の対面を分析する。双方向のダメージ計算と素早さ比較を行い、どちらが有利かを判断するためのデータを提供する。ポケモン対戦の対面判断に使用する。技ごとの結果はタイプ・相性・ダメージ割合・確定数の要約で、乱数の内訳は含まない。計算条件の説明文は最大打点の技にだけ付く。1 技の詳しい結果は calculate_damage_single で確認する。pokemon1Faster は静的な素早さ実数値のみの比較のため、素早さ負けでも先制技で逆転できる判断は pokemon{1,2}PriorityMoves を併用すること。正確な計算のため双方の ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
39693
39084
  const matchupInputSchema = {
39694
- pokemon1: pokemonSchema.describe("ポケモン1"),
39695
- pokemon2: pokemonSchema.describe("ポケモン2"),
39085
+ pokemon1: pokemonWithMovesSchema.describe("ポケモン1"),
39086
+ pokemon2: pokemonWithMovesSchema.describe("ポケモン2"),
39696
39087
  conditions: conditionsSchema.optional().describe("バトル条件")
39697
39088
  };
39698
39089
  function resolveMoveForPriority(id) {
@@ -39701,9 +39092,9 @@ function resolveMoveForPriority(id) {
39701
39092
  function moveToJapanese(en) {
39702
39093
  return moveNameResolver.toJapanese(en);
39703
39094
  }
39704
- function priorityMovesFor(resolvedName) {
39095
+ function priorityMovesFor(resolvedName, moves) {
39705
39096
  return extractPriorityMoves({
39706
- learnsetMoveIds: championsLearnsets[toDataId(resolvedName)] ?? [],
39097
+ learnsetMoveIds: candidateMoveIds(resolvedName, moves),
39707
39098
  resolveMove: resolveMoveForPriority,
39708
39099
  toJapanese: moveToJapanese
39709
39100
  });
@@ -39722,23 +39113,28 @@ function maxTypeMultiplier$1(attackerTypes, defenderTypes, gen) {
39722
39113
  }
39723
39114
  return max;
39724
39115
  }
39725
- function registerMatchupTool(server) {
39726
- server.tool(TOOL_NAME$11, TOOL_DESCRIPTION$11, matchupInputSchema, async (args) => {
39116
+ function registerMatchupTool(server, movesRequirement = MOVES_OPTIONAL) {
39117
+ server.tool(TOOL_NAME$12, TOOL_DESCRIPTION$12, matchupInputSchema, async (args) => {
39727
39118
  try {
39119
+ assertMovesSpecified(movesRequirement, [{
39120
+ field: "pokemon1",
39121
+ name: args.pokemon1.name,
39122
+ moves: args.pokemon1.moves
39123
+ }]);
39728
39124
  const { pokemon: p1, resolvedName: name1 } = damageCalculator.createPokemonObject(args.pokemon1);
39729
39125
  const { pokemon: p2, resolvedName: name2 } = damageCalculator.createPokemonObject(args.pokemon2);
39730
39126
  const nameJa1 = pokemonNameResolver.toJapanese(name1) ?? name1;
39731
39127
  const nameJa2 = pokemonNameResolver.toJapanese(name2) ?? name2;
39732
- const pokemon1Attacks = filterResultsByLearnset(damageCalculator.calculateAllMoves({
39128
+ const pokemon1Attacks = damageCalculator.calculateAllMoves({
39733
39129
  attacker: args.pokemon1,
39734
39130
  defender: args.pokemon2,
39735
39131
  conditions: args.conditions
39736
- }), getLearnsetMoveIdSet(toDataId(name1)), toDataId);
39737
- const pokemon2Attacks = filterResultsByLearnset(damageCalculator.calculateAllMoves({
39132
+ });
39133
+ const pokemon2Attacks = damageCalculator.calculateAllMoves({
39738
39134
  attacker: args.pokemon2,
39739
39135
  defender: args.pokemon1,
39740
39136
  conditions: args.conditions
39741
- }), getLearnsetMoveIdSet(toDataId(name2)), toDataId);
39137
+ });
39742
39138
  const gen = damageCalculator.getGen();
39743
39139
  const typeSummary = {
39744
39140
  p1ToP2MaxByPokemonType: maxTypeMultiplier$1(p1.types, p2.types, gen),
@@ -39756,10 +39152,10 @@ function registerMatchupTool(server) {
39756
39152
  speed: p2.stats.spe
39757
39153
  },
39758
39154
  pokemon1Faster: compareSpeed(p1.stats.spe, p2.stats.spe) === "faster",
39759
- pokemon1Attacks,
39760
- pokemon2Attacks,
39761
- pokemon1PriorityMoves: priorityMovesFor(name1),
39762
- pokemon2PriorityMoves: priorityMovesFor(name2),
39155
+ pokemon1Attacks: summarizeMoveDamages(pokemon1Attacks, moveToJapanese),
39156
+ pokemon2Attacks: summarizeMoveDamages(pokemon2Attacks, moveToJapanese),
39157
+ pokemon1PriorityMoves: priorityMovesFor(name1, args.pokemon1.moves),
39158
+ pokemon2PriorityMoves: priorityMovesFor(name2, args.pokemon2.moves),
39763
39159
  typeSummary
39764
39160
  };
39765
39161
  return withHint({
@@ -39767,21 +39163,14 @@ function registerMatchupTool(server) {
39767
39163
  text: JSON.stringify(output)
39768
39164
  });
39769
39165
  } catch (error) {
39770
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
39771
- return {
39772
- content: [{
39773
- type: "text",
39774
- text: JSON.stringify({ error: message })
39775
- }],
39776
- isError: true
39777
- };
39166
+ return toErrorResponse(error);
39778
39167
  }
39779
39168
  });
39780
39169
  }
39781
39170
  // src/tools/info/move-info.ts
39782
- const TOOL_NAME$10 = "get_move_info";
39783
- const TOOL_DESCRIPTION$10 = "ポケモンの技の詳細情報(タイプ・威力・命中率・分類・優先度・効果説明)を取得する。対戦で使う技の仕様を確認したいときに使用する。ポケモンチャンピオンズ対応。";
39784
- const inputSchema$8 = { name: z.string().describe("技名(日本語 or 英語)") };
39171
+ const TOOL_NAME$11 = "get_move_info";
39172
+ const TOOL_DESCRIPTION$11 = "ポケモンの技の詳細情報(タイプ・威力・命中率・分類・優先度・効果説明)を取得する。対戦で使う技の仕様を確認したいときに使用する。ポケモンチャンピオンズ対応。";
39173
+ const inputSchema$9 = { name: nameInputSchema.describe("技名(日本語 or 英語)") };
39785
39174
  /**
39786
39175
  * 技名を英語に解決する。日本語名・英語名どちらでも受け付ける。
39787
39176
  * 名前変換辞書には登録されているがチャンピオンズで使えない技の場合はエラー。
@@ -39791,8 +39180,7 @@ function resolveMoveNameEn$1(input) {
39791
39180
  if (fromJa !== void 0) return fromJa;
39792
39181
  if (moveNameResolver.hasEnglishName(input)) return input;
39793
39182
  const suggestions = moveNameResolver.suggestSimilar(input);
39794
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
39795
- throw new Error(`技「${input}」が見つかりません。${suggestionMessage}`);
39183
+ throw new UserFacingError(`技「${input}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
39796
39184
  }
39797
39185
  /**
39798
39186
  * 変化技(Status)の威力は 0 だが、ユーザー側では null の方が意図が明確なので変換する。
@@ -39802,11 +39190,11 @@ function normalizeBasePower(category, basePower) {
39802
39190
  return basePower;
39803
39191
  }
39804
39192
  function registerMoveInfoTool(server) {
39805
- server.tool(TOOL_NAME$10, TOOL_DESCRIPTION$10, inputSchema$8, async (args) => {
39193
+ server.tool(TOOL_NAME$11, TOOL_DESCRIPTION$11, inputSchema$9, async (args) => {
39806
39194
  try {
39807
39195
  const moveId = toDataId(resolveMoveNameEn$1(args.name));
39808
39196
  const entry = movesById.get(moveId);
39809
- if (entry === void 0) throw new Error(`技「${args.name}」はチャンピオンズでは使用できません。`);
39197
+ if (entry === void 0) throw new UserFacingError(`技「${args.name}」はチャンピオンズでは使用できません。`);
39810
39198
  const output = {
39811
39199
  name: entry.name,
39812
39200
  nameJa: entry.nameJa,
@@ -39827,21 +39215,14 @@ function registerMoveInfoTool(server) {
39827
39215
  text: JSON.stringify(output)
39828
39216
  });
39829
39217
  } catch (error) {
39830
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
39831
- return {
39832
- content: [{
39833
- type: "text",
39834
- text: JSON.stringify({ error: message })
39835
- }],
39836
- isError: true
39837
- };
39218
+ return toErrorResponse(error);
39838
39219
  }
39839
39220
  });
39840
39221
  }
39841
39222
  // src/tools/info/nature-info.ts
39842
- const TOOL_NAME$9 = "get_nature_info";
39843
- const TOOL_DESCRIPTION$9 = "ポケモンの性格の詳細情報(上昇ステ・下降ステ)を取得する。育成方針の検討や性格選びに使用する。plus/minus が null の性格は無補正。ポケモンチャンピオンズ対応。";
39844
- const inputSchema$7 = { name: z.string().describe("性格名(日本語 or 英語、例: 'ひかえめ'、'Modest')") };
39223
+ const TOOL_NAME$10 = "get_nature_info";
39224
+ const TOOL_DESCRIPTION$10 = "ポケモンの性格の詳細情報(上昇ステ・下降ステ)を取得する。育成方針の検討や性格選びに使用する。plus/minus が null の性格は無補正。ポケモンチャンピオンズ対応。";
39225
+ const inputSchema$8 = { name: nameInputSchema.describe("性格名(日本語 or 英語、例: 'ひかえめ'、'Modest')") };
39845
39226
  /**
39846
39227
  * 性格名を英語に解決する。日本語名・英語名どちらでも受け付ける。
39847
39228
  */
@@ -39850,15 +39231,14 @@ function resolveNatureNameEn(input) {
39850
39231
  if (fromJa !== void 0) return fromJa;
39851
39232
  if (natureNameResolver.hasEnglishName(input)) return input;
39852
39233
  const suggestions = natureNameResolver.suggestSimilar(input);
39853
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
39854
- throw new Error(`性格「${input}」が見つかりません。${suggestionMessage}`);
39234
+ throw new UserFacingError(`性格「${input}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
39855
39235
  }
39856
39236
  function registerNatureInfoTool(server) {
39857
- server.tool(TOOL_NAME$9, TOOL_DESCRIPTION$9, inputSchema$7, async (args) => {
39237
+ server.tool(TOOL_NAME$10, TOOL_DESCRIPTION$10, inputSchema$8, async (args) => {
39858
39238
  try {
39859
39239
  const englishName = resolveNatureNameEn(args.name);
39860
39240
  const entry = naturesById.get(toDataId(englishName));
39861
- if (entry === void 0) throw new Error(`性格「${args.name}」はチャンピオンズでは使用できません。`);
39241
+ if (entry === void 0) throw new UserFacingError(`性格「${args.name}」はチャンピオンズでは使用できません。`);
39862
39242
  const output = {
39863
39243
  name: entry.name,
39864
39244
  nameJa: entry.nameJa,
@@ -39870,22 +39250,15 @@ function registerNatureInfoTool(server) {
39870
39250
  text: JSON.stringify(output)
39871
39251
  });
39872
39252
  } catch (error) {
39873
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
39874
- return {
39875
- content: [{
39876
- type: "text",
39877
- text: JSON.stringify({ error: message })
39878
- }],
39879
- isError: true
39880
- };
39253
+ return toErrorResponse(error);
39881
39254
  }
39882
39255
  });
39883
39256
  }
39884
39257
  // src/tools/analysis/party-analysis.ts
39885
39258
  const CHAMPIONS_GEN_NUM$6 = 0;
39886
- const TOOL_NAME$8 = "analyze_party_weakness";
39887
- const TOOL_DESCRIPTION$8 = "パーティ各メンバーのタイプ相性データを集計する。どのタイプが何匹の弱点か(teamWeaknesses)、どのタイプに抜群を取れないか(uncoveredTypes)を返す。致命性の判断は AI が文脈で行う前提。ポケモンチャンピオンズ対応。";
39888
- const partyAnalysisInputSchema = { party: z.array(pokemonSchema).describe("パーティメンバー") };
39259
+ const TOOL_NAME$9 = "analyze_party_weakness";
39260
+ const TOOL_DESCRIPTION$9 = "パーティ各メンバーのタイプ相性データを集計する。どのタイプが何匹の弱点か(teamWeaknesses)、どのタイプに抜群を取れないか(uncoveredTypes)を返す。致命性の判断は AI が文脈で行う前提。ポケモンチャンピオンズ対応。";
39261
+ const partyAnalysisInputSchema = { party: z.array(pokemonSchema).min(1).max(6).describe("パーティメンバー") };
39889
39262
  /** ???タイプは計算対象から除外するためのマーカー */
39890
39263
  const UNKNOWN_TYPE_NAME = "???";
39891
39264
  /**
@@ -39896,8 +39269,7 @@ function resolvePokemonName$2(name) {
39896
39269
  if (englishName !== void 0) return englishName;
39897
39270
  if (pokemonNameResolver.hasEnglishName(name)) return name;
39898
39271
  const suggestions = pokemonNameResolver.suggestSimilar(name);
39899
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
39900
- throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
39272
+ throw new UserFacingError(`ポケモン「${name}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
39901
39273
  }
39902
39274
  /**
39903
39275
  * 日本語・英語のどちらの名前でも英語名に解決する。
@@ -39931,7 +39303,7 @@ function findUncoveredTypes(memberTypes, gen) {
39931
39303
  return uncovered;
39932
39304
  }
39933
39305
  function registerPartyAnalysisTool(server) {
39934
- server.tool(TOOL_NAME$8, TOOL_DESCRIPTION$8, partyAnalysisInputSchema, async (args) => {
39306
+ server.tool(TOOL_NAME$9, TOOL_DESCRIPTION$9, partyAnalysisInputSchema, async (args) => {
39935
39307
  try {
39936
39308
  const gen = Generations.get(CHAMPIONS_GEN_NUM$6);
39937
39309
  const members = [];
@@ -39940,7 +39312,7 @@ function registerPartyAnalysisTool(server) {
39940
39312
  for (const member of args.party) {
39941
39313
  const nameEn = resolvePokemonName$2(member.name);
39942
39314
  const entry = pokemonById.get(toDataId(nameEn));
39943
- if (entry === void 0) throw new Error(`ポケモン「${member.name}」のデータが見つかりません。`);
39315
+ if (entry === void 0) throw new UserFacingError(`ポケモン「${member.name}」のデータが見つかりません。`);
39944
39316
  const nameJa = entry.nameJa ?? entry.name;
39945
39317
  const types = [...entry.types];
39946
39318
  memberTypesList.push(types);
@@ -39971,124 +39343,6 @@ function registerPartyAnalysisTool(server) {
39971
39343
  type: "text",
39972
39344
  text: JSON.stringify(output)
39973
39345
  });
39974
- } catch (error) {
39975
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
39976
- return {
39977
- content: [{
39978
- type: "text",
39979
- text: JSON.stringify({ error: message })
39980
- }],
39981
- isError: true
39982
- };
39983
- }
39984
- });
39985
- }
39986
- // src/tools/party/party-tools.ts
39987
- const SAVE_TOOL_NAME = "save_party";
39988
- const SAVE_TOOL_DESCRIPTION = "パーティを保存する (upsert)。同名のパーティが既に存在する場合は上書きされる。createdAt は新規時のみ現在時刻が記録され、同名上書きの場合は保持される。updatedAt は毎回現在時刻に更新される。";
39989
- const LOAD_TOOL_NAME = "load_party";
39990
- const LOAD_TOOL_DESCRIPTION = "保存済みパーティを name 指定で 1 件取得する。存在しない場合はエラーを返す。";
39991
- const LIST_TOOL_NAME = "list_parties";
39992
- const LIST_TOOL_DESCRIPTION = "保存済みパーティの一覧 (サマリ) を返す。各要素は { name, memo, updatedAt, memberCount } のみで、メンバー詳細は含まない。詳細は load_party を使用する。";
39993
- const DELETE_TOOL_NAME = "delete_party";
39994
- const DELETE_TOOL_DESCRIPTION = "保存済みパーティを name 指定で削除する。存在しない場合はエラーを返す。";
39995
- const defaultNowProvider = () => /* @__PURE__ */ new Date();
39996
- const defaultStoreIO = {
39997
- load: () => loadPartiesFile(),
39998
- save: (data) => savePartiesFile(data)
39999
- };
40000
- const nameField = z.string().min(1, { message: "名前は 1 文字以上で指定してください。" }).max(100, { message: `名前は 100 文字以下で指定してください。` });
40001
- const partyMemberInputSchema = z.object({
40002
- name: nameField.describe("ポケモン名 (日本語 or 英語)。"),
40003
- nature: nameField.optional().describe("性格名 (日本語 or 英語)。"),
40004
- ability: nameField.optional().describe("特性名 (日本語 or 英語)。"),
40005
- item: nameField.optional().describe("持ち物名 (日本語 or 英語)。"),
40006
- evs: evsSchema.optional().describe("能力ポイント (SP) 配分。"),
40007
- moves: z.array(nameField).max(4, { message: `技は 4 個までです。` }).optional().describe("技リスト (最大 4)。")
40008
- }).describe("パーティメンバー 1 匹分のビルド情報。");
40009
- const partyNameField = z.string().min(1, { message: "パーティ名は 1 文字以上で指定してください。" }).max(50, { message: `パーティ名は 50 文字以下で指定してください。` });
40010
- const saveInputSchema = {
40011
- name: partyNameField.describe("パーティの識別子 (同名は上書き)。"),
40012
- memo: z.string().max(MAX_PARTY_MEMO_LENGTH, { message: `メモは ${MAX_PARTY_MEMO_LENGTH} 文字以下で指定してください。` }).optional().describe("自由記述メモ。"),
40013
- members: z.array(partyMemberInputSchema).min(1, { message: `パーティには 1 匹以上を含めてください。` }).max(6, { message: `パーティには 6 匹までしか含められません。` }).describe("1〜6 匹のメンバー。")
40014
- };
40015
- const loadInputSchema = { name: partyNameField.describe("取得するパーティ名。") };
40016
- const deleteInputSchema = { name: partyNameField.describe("削除するパーティ名。") };
40017
- const listInputSchema = {};
40018
- function toSummary(party) {
40019
- const summary = {
40020
- name: party.name,
40021
- updatedAt: party.updatedAt,
40022
- memberCount: party.members.length
40023
- };
40024
- if (party.memo !== void 0) summary.memo = party.memo;
40025
- return summary;
40026
- }
40027
- /**
40028
- * パーティ永続化 4 ツールをサーバーに登録する。
40029
- * deps は主にテスト用。本番は省略してデフォルト (ファイル I/O + 現在時刻) を使う。
40030
- */
40031
- function registerPartyTools(server, deps = {}) {
40032
- const storeIO = deps.storeIO ?? defaultStoreIO;
40033
- const now = deps.now ?? defaultNowProvider;
40034
- server.tool(SAVE_TOOL_NAME, SAVE_TOOL_DESCRIPTION, saveInputSchema, async (args) => {
40035
- try {
40036
- const file = storeIO.load();
40037
- const nowIso = now().toISOString();
40038
- const existingIndex = file.parties.findIndex((p) => p.name === args.name);
40039
- const createdAt = existingIndex >= 0 ? file.parties[existingIndex].createdAt : nowIso;
40040
- const party = {
40041
- name: args.name,
40042
- members: args.members,
40043
- createdAt,
40044
- updatedAt: nowIso
40045
- };
40046
- if (args.memo !== void 0) party.memo = args.memo;
40047
- if (existingIndex >= 0) file.parties[existingIndex] = party;
40048
- else file.parties.push(party);
40049
- storeIO.save({
40050
- schemaVersion: 1,
40051
- parties: file.parties
40052
- });
40053
- return toTextResponse({
40054
- saved: true,
40055
- overwrote: existingIndex >= 0,
40056
- party,
40057
- filePath: resolvePartiesFilePath()
40058
- });
40059
- } catch (error) {
40060
- return toErrorResponse(error);
40061
- }
40062
- });
40063
- server.tool(LOAD_TOOL_NAME, LOAD_TOOL_DESCRIPTION, loadInputSchema, async (args) => {
40064
- try {
40065
- const party = storeIO.load().parties.find((p) => p.name === args.name);
40066
- if (party === void 0) throw new Error(`パーティ「${args.name}」が見つかりません。list_parties で一覧を確認してください。`);
40067
- return toTextResponse({ party });
40068
- } catch (error) {
40069
- return toErrorResponse(error);
40070
- }
40071
- });
40072
- server.tool(LIST_TOOL_NAME, LIST_TOOL_DESCRIPTION, listInputSchema, async () => {
40073
- try {
40074
- return toTextResponse({ parties: storeIO.load().parties.map(toSummary) });
40075
- } catch (error) {
40076
- return toErrorResponse(error);
40077
- }
40078
- });
40079
- server.tool(DELETE_TOOL_NAME, DELETE_TOOL_DESCRIPTION, deleteInputSchema, async (args) => {
40080
- try {
40081
- const file = storeIO.load();
40082
- const nextParties = file.parties.filter((p) => p.name !== args.name);
40083
- if (nextParties.length === file.parties.length) throw new Error(`パーティ「${args.name}」が見つかりません。`);
40084
- storeIO.save({
40085
- schemaVersion: 1,
40086
- parties: nextParties
40087
- });
40088
- return toTextResponse({
40089
- deleted: true,
40090
- name: args.name
40091
- });
40092
39346
  } catch (error) {
40093
39347
  return toErrorResponse(error);
40094
39348
  }
@@ -40145,8 +39399,7 @@ function resolvePokemonName$1(name) {
40145
39399
  if (englishName !== void 0) return englishName;
40146
39400
  if (pokemonNameResolver.hasEnglishName(name)) return name;
40147
39401
  const suggestions = pokemonNameResolver.suggestSimilar(name);
40148
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
40149
- throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
39402
+ throw new UserFacingError(`ポケモン「${name}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
40150
39403
  }
40151
39404
  /**
40152
39405
  * 種族値の合計を計算する。
@@ -40183,35 +39436,22 @@ function buildPokemonInfoResult(entry) {
40183
39436
  return result;
40184
39437
  }
40185
39438
  function registerPokemonInfoTools(server) {
40186
- server.tool(GET_POKEMON_INFO_TOOL_NAME, GET_POKEMON_INFO_DESCRIPTION, { name: z.string().describe("ポケモン名(日本語 or 英語)") }, async (args) => {
39439
+ server.tool(GET_POKEMON_INFO_TOOL_NAME, GET_POKEMON_INFO_DESCRIPTION, { name: nameInputSchema.describe("ポケモン名(日本語 or 英語)") }, async (args) => {
40187
39440
  try {
40188
39441
  const englishName = resolvePokemonName$1(args.name);
40189
39442
  const entry = pokemonById.get(toDataId(englishName));
40190
- if (entry === void 0) return {
40191
- content: [{
40192
- type: "text",
40193
- text: JSON.stringify({ error: `ポケモン「${args.name}」のデータが見つかりません。` })
40194
- }],
40195
- isError: true
40196
- };
39443
+ if (entry === void 0) throw new UserFacingError(`ポケモン「${args.name}」のデータが見つかりません。`);
40197
39444
  const result = buildPokemonInfoResult(entry);
40198
39445
  return withHint({
40199
39446
  type: "text",
40200
39447
  text: JSON.stringify(result)
40201
39448
  });
40202
39449
  } catch (error) {
40203
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
40204
- return {
40205
- content: [{
40206
- type: "text",
40207
- text: JSON.stringify({ error: message })
40208
- }],
40209
- isError: true
40210
- };
39450
+ return toErrorResponse(error);
40211
39451
  }
40212
39452
  });
40213
39453
  server.tool(SEARCH_POKEMON_TOOL_NAME, SEARCH_POKEMON_DESCRIPTION, {
40214
- type: z.string().optional().describe("タイプで絞り込み(例: 'ほのお'、'Fire')"),
39454
+ type: nameInputSchema.optional().describe("タイプで絞り込み(例: 'ほのお'、'Fire')"),
40215
39455
  minStat: z.object({
40216
39456
  hp: z.number().optional(),
40217
39457
  atk: z.number().optional(),
@@ -40227,13 +39467,7 @@ function registerPokemonInfoTools(server) {
40227
39467
  let typeFilterEn;
40228
39468
  if (args.type !== void 0) {
40229
39469
  typeFilterEn = resolveTypeName(args.type);
40230
- if (typeFilterEn === void 0) return {
40231
- content: [{
40232
- type: "text",
40233
- text: JSON.stringify({ error: `タイプ「${args.type}」が見つかりません。` })
40234
- }],
40235
- isError: true
40236
- };
39470
+ if (typeFilterEn === void 0) throw new UserFacingError(`タイプ「${args.type}」が見つかりません。`);
40237
39471
  }
40238
39472
  const results = [];
40239
39473
  for (const entry of championsPokemon) {
@@ -40256,14 +39490,7 @@ function registerPokemonInfoTools(server) {
40256
39490
  text: JSON.stringify(results)
40257
39491
  });
40258
39492
  } catch (error) {
40259
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
40260
- return {
40261
- content: [{
40262
- type: "text",
40263
- text: JSON.stringify({ error: message })
40264
- }],
40265
- isError: true
40266
- };
39493
+ return toErrorResponse(error);
40267
39494
  }
40268
39495
  });
40269
39496
  }
@@ -40277,9 +39504,9 @@ const WEAKNESS_MIN = 1;
40277
39504
  const IMMUNITY_MULTIPLIER$1 = 0;
40278
39505
  /** Status 技の category 値 */
40279
39506
  const STATUS_CATEGORY$1 = "Status";
40280
- const TOOL_NAME$7 = "get_pokemon_summary";
40281
- const TOOL_DESCRIPTION$7 = "ポケモンの総合プロファイル(基本情報・防御相性・覚える技の集計・実数値)を一度に取得する。ユーザー発話にポケモン名が出てきて詳細な分析や役割評価が必要な場合は、知識ベースで即答せず、まずこのツールを呼んでデータを引くこと。対戦での役割把握や初期分析に使用する。ポケモンチャンピオンズ対応。";
40282
- const inputSchema$6 = { name: z.string().describe("ポケモン名(日本語 or 英語)") };
39507
+ const TOOL_NAME$8 = "get_pokemon_summary";
39508
+ const TOOL_DESCRIPTION$8 = "ポケモンの総合プロファイル(基本情報・防御相性・覚える技の集計・実数値)を一度に取得する。ユーザー発話にポケモン名が出てきて詳細な分析や役割評価が必要な場合は、知識ベースで即答せず、まずこのツールを呼んでデータを引くこと。対戦での役割把握や初期分析に使用する。ポケモンチャンピオンズ対応。";
39509
+ const inputSchema$7 = { name: nameInputSchema.describe("ポケモン名(日本語 or 英語)") };
40283
39510
  /**
40284
39511
  * ポケモン名を pokemon.json のエントリに解決する。
40285
39512
  */
@@ -40287,11 +39514,10 @@ function resolvePokemonEntry$1(name) {
40287
39514
  const englishName = pokemonNameResolver.toEnglish(name) ?? (pokemonNameResolver.hasEnglishName(name) ? name : null);
40288
39515
  if (englishName === null) {
40289
39516
  const suggestions = pokemonNameResolver.suggestSimilar(name);
40290
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
40291
- throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
39517
+ throw new UserFacingError(`ポケモン「${name}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
40292
39518
  }
40293
39519
  const entry = pokemonById.get(toDataId(englishName));
40294
- if (entry === void 0) throw new Error(`ポケモン「${name}」のデータが見つかりません。`);
39520
+ if (entry === void 0) throw new UserFacingError(`ポケモン「${name}」のデータが見つかりません。`);
40295
39521
  return entry;
40296
39522
  }
40297
39523
  /**
@@ -40441,7 +39667,7 @@ function buildBasicProfile(entry, typeJaMap) {
40441
39667
  };
40442
39668
  }
40443
39669
  function registerPokemonSummaryTool(server) {
40444
- server.tool(TOOL_NAME$7, TOOL_DESCRIPTION$7, inputSchema$6, async (args) => {
39670
+ server.tool(TOOL_NAME$8, TOOL_DESCRIPTION$8, inputSchema$7, async (args) => {
40445
39671
  try {
40446
39672
  const entry = resolvePokemonEntry$1(args.name);
40447
39673
  const gen = Generations.get(CHAMPIONS_GEN_NUM$5);
@@ -40457,21 +39683,14 @@ function registerPokemonSummaryTool(server) {
40457
39683
  text: JSON.stringify(output)
40458
39684
  });
40459
39685
  } catch (error) {
40460
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
40461
- return {
40462
- content: [{
40463
- type: "text",
40464
- text: JSON.stringify({ error: message })
40465
- }],
40466
- isError: true
40467
- };
39686
+ return toErrorResponse(error);
40468
39687
  }
40469
39688
  });
40470
39689
  }
40471
39690
  // src/tools/search/search-by-ability.ts
40472
- const TOOL_NAME$6 = "search_pokemon_by_ability";
40473
- const TOOL_DESCRIPTION$6 = "特定の特性を持つポケモンを逆引き検索する。いかく・もうか等の特性を持つポケモンを絞り込みたい場合に使用する。ポケモンチャンピオンズ対応。";
40474
- const inputSchema$5 = { abilityName: z.string().describe("特性名(日本語 or 英語)") };
39691
+ const TOOL_NAME$7 = "search_pokemon_by_ability";
39692
+ const TOOL_DESCRIPTION$7 = "特定の特性を持つポケモンを逆引き検索する。いかく・もうか等の特性を持つポケモンを絞り込みたい場合に使用する。ポケモンチャンピオンズ対応。";
39693
+ const inputSchema$6 = { abilityName: nameInputSchema.describe("特性名(日本語 or 英語)") };
40475
39694
  /**
40476
39695
  * 特性名を英語に解決する。日本語名・英語名どちらも受け付ける。
40477
39696
  */
@@ -40480,15 +39699,14 @@ function resolveAbilityNameEn(input) {
40480
39699
  if (fromJa !== void 0) return fromJa;
40481
39700
  if (abilityNameResolver.hasEnglishName(input)) return input;
40482
39701
  const suggestions = abilityNameResolver.suggestSimilar(input);
40483
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
40484
- throw new Error(`特性「${input}」が見つかりません。${suggestionMessage}`);
39702
+ throw new UserFacingError(`特性「${input}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
40485
39703
  }
40486
39704
  function registerSearchByAbilityTool(server) {
40487
- server.tool(TOOL_NAME$6, TOOL_DESCRIPTION$6, inputSchema$5, async (args) => {
39705
+ server.tool(TOOL_NAME$7, TOOL_DESCRIPTION$7, inputSchema$6, async (args) => {
40488
39706
  try {
40489
39707
  const abilityId = toDataId(resolveAbilityNameEn(args.abilityName));
40490
39708
  const abilityEntry = abilitiesById.get(abilityId);
40491
- if (abilityEntry === void 0) throw new Error(`特性「${args.abilityName}」はチャンピオンズでは使用できません。`);
39709
+ if (abilityEntry === void 0) throw new UserFacingError(`特性「${args.abilityName}」はチャンピオンズでは使用できません。`);
40492
39710
  const matchedPokemon = [];
40493
39711
  for (const entry of championsPokemon) {
40494
39712
  if (!entry.abilities.includes(abilityEntry.name)) continue;
@@ -40515,21 +39733,14 @@ function registerSearchByAbilityTool(server) {
40515
39733
  text: JSON.stringify(output)
40516
39734
  });
40517
39735
  } catch (error) {
40518
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
40519
- return {
40520
- content: [{
40521
- type: "text",
40522
- text: JSON.stringify({ error: message })
40523
- }],
40524
- isError: true
40525
- };
39736
+ return toErrorResponse(error);
40526
39737
  }
40527
39738
  });
40528
39739
  }
40529
39740
  // src/tools/search/search-by-move.ts
40530
- const TOOL_NAME$5 = "search_pokemon_by_move";
40531
- const TOOL_DESCRIPTION$5 = "特定の技を覚えるポケモンを逆引き検索する。ステルスロックなど特定の技を覚えさせたい場合の候補ポケモン探しに使用する。ポケモンチャンピオンズ対応。";
40532
- const inputSchema$4 = { moveName: z.string().describe("技名(日本語 or 英語)") };
39741
+ const TOOL_NAME$6 = "search_pokemon_by_move";
39742
+ const TOOL_DESCRIPTION$6 = "特定の技を覚えるポケモンを逆引き検索する。ステルスロックなど特定の技を覚えさせたい場合の候補ポケモン探しに使用する。ポケモンチャンピオンズ対応。";
39743
+ const inputSchema$5 = { moveName: nameInputSchema.describe("技名(日本語 or 英語)") };
40533
39744
  /**
40534
39745
  * 技名を英語に解決する。日本語名・英語名どちらも受け付ける。
40535
39746
  * 名前辞書に存在してもチャンピオンズで使用できない技は movesById が undefined を返すのでエラー。
@@ -40539,15 +39750,14 @@ function resolveMoveNameEn(input) {
40539
39750
  if (fromJa !== void 0) return fromJa;
40540
39751
  if (moveNameResolver.hasEnglishName(input)) return input;
40541
39752
  const suggestions = moveNameResolver.suggestSimilar(input);
40542
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
40543
- throw new Error(`技「${input}」が見つかりません。${suggestionMessage}`);
39753
+ throw new UserFacingError(`技「${input}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
40544
39754
  }
40545
39755
  function registerSearchByMoveTool(server) {
40546
- server.tool(TOOL_NAME$5, TOOL_DESCRIPTION$5, inputSchema$4, async (args) => {
39756
+ server.tool(TOOL_NAME$6, TOOL_DESCRIPTION$6, inputSchema$5, async (args) => {
40547
39757
  try {
40548
39758
  const moveId = toDataId(resolveMoveNameEn(args.moveName));
40549
39759
  const moveEntry = movesById.get(moveId);
40550
- if (moveEntry === void 0) throw new Error(`技「${args.moveName}」はチャンピオンズでは使用できません。`);
39760
+ if (moveEntry === void 0) throw new UserFacingError(`技「${args.moveName}」はチャンピオンズでは使用できません。`);
40551
39761
  const matchedPokemon = [];
40552
39762
  for (const [pokemonId, moveIds] of Object.entries(championsLearnsets)) {
40553
39763
  if (!moveIds.includes(moveId)) continue;
@@ -40577,14 +39787,7 @@ function registerSearchByMoveTool(server) {
40577
39787
  text: JSON.stringify(output)
40578
39788
  });
40579
39789
  } catch (error) {
40580
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
40581
- return {
40582
- content: [{
40583
- type: "text",
40584
- text: JSON.stringify({ error: message })
40585
- }],
40586
- isError: true
40587
- };
39790
+ return toErrorResponse(error);
40588
39791
  }
40589
39792
  });
40590
39793
  }
@@ -40598,13 +39801,13 @@ const WEAKNESS_THRESHOLD = 2;
40598
39801
  const IMMUNITY_MULTIPLIER = 0;
40599
39802
  /** ステータス技を示す category 値 */
40600
39803
  const STATUS_CATEGORY = "Status";
40601
- const TOOL_NAME$4 = "search_pokemon_by_type_effectiveness";
40602
- const TOOL_DESCRIPTION$4 = "タイプ相性条件でポケモンを逆引き検索する。指定タイプを半減/無効/弱点で受けるポケモンや、指定タイプの攻撃技を覚えるポケモンを絞り込める。複数条件の AND 指定が可能。対策ポケモン探しやパーティ構築に使用する。ポケモンチャンピオンズ対応。";
40603
- const inputSchema$3 = {
40604
- resistsType: z.string().optional().describe("指定タイプの攻撃を 0.5 倍以下で受けるポケモン(半減・無効含む)"),
40605
- immuneToType: z.string().optional().describe("指定タイプの攻撃を無効化するポケモン(0 倍)"),
40606
- weakToType: z.string().optional().describe("指定タイプの攻撃で 2 倍以上のダメージを受けるポケモン(4 倍含む)"),
40607
- hasAttackingType: z.string().optional().describe("指定タイプの攻撃技を 1 つ以上覚えるポケモン")
39804
+ const TOOL_NAME$5 = "search_pokemon_by_type_effectiveness";
39805
+ const TOOL_DESCRIPTION$5 = "タイプ相性条件でポケモンを逆引き検索する。指定タイプを半減/無効/弱点で受けるポケモンや、指定タイプの攻撃技を覚えるポケモンを絞り込める。複数条件の AND 指定が可能。対策ポケモン探しやパーティ構築に使用する。ポケモンチャンピオンズ対応。";
39806
+ const inputSchema$4 = {
39807
+ resistsType: nameInputSchema.optional().describe("指定タイプの攻撃を 0.5 倍以下で受けるポケモン(半減・無効含む)"),
39808
+ immuneToType: nameInputSchema.optional().describe("指定タイプの攻撃を無効化するポケモン(0 倍)"),
39809
+ weakToType: nameInputSchema.optional().describe("指定タイプの攻撃で 2 倍以上のダメージを受けるポケモン(4 倍含む)"),
39810
+ hasAttackingType: nameInputSchema.optional().describe("指定タイプの攻撃技を 1 つ以上覚えるポケモン")
40608
39811
  };
40609
39812
  /**
40610
39813
  * タイプ名(日本語 or 英語)を英語名に解決する。
@@ -40614,7 +39817,7 @@ function resolveTypeNameEn$1(input) {
40614
39817
  for (const entry of championsTypes) if (entry.nameJa === input) return entry.name;
40615
39818
  const normalized = input.toLowerCase();
40616
39819
  for (const entry of championsTypes) if (entry.id === normalized) return entry.name;
40617
- throw new Error(`タイプ「${input}」が見つかりません。`);
39820
+ throw new UserFacingError(`タイプ「${input}」が見つかりません。`);
40618
39821
  }
40619
39822
  /**
40620
39823
  * 攻撃タイプ名 → 防御側タイプ配列への複合倍率を算出する。
@@ -40639,9 +39842,9 @@ function hasAttackingMoveOfType(pokemonId, attackTypeEn) {
40639
39842
  return false;
40640
39843
  }
40641
39844
  function registerSearchByTypeEffectivenessTool(server) {
40642
- server.tool(TOOL_NAME$4, TOOL_DESCRIPTION$4, inputSchema$3, async (args) => {
39845
+ server.tool(TOOL_NAME$5, TOOL_DESCRIPTION$5, inputSchema$4, async (args) => {
40643
39846
  try {
40644
- if (!(args.resistsType !== void 0 || args.immuneToType !== void 0 || args.weakToType !== void 0 || args.hasAttackingType !== void 0)) throw new Error("少なくとも 1 つの条件 (resistsType / immuneToType / weakToType / hasAttackingType) を指定してください。");
39847
+ if (!(args.resistsType !== void 0 || args.immuneToType !== void 0 || args.weakToType !== void 0 || args.hasAttackingType !== void 0)) throw new UserFacingError("少なくとも 1 つの条件 (resistsType / immuneToType / weakToType / hasAttackingType) を指定してください。");
40645
39848
  const gen = Generations.get(CHAMPIONS_GEN_NUM$4);
40646
39849
  const resistsTypeEn = args.resistsType !== void 0 ? resolveTypeNameEn$1(args.resistsType) : null;
40647
39850
  const immuneToTypeEn = args.immuneToType !== void 0 ? resolveTypeNameEn$1(args.immuneToType) : null;
@@ -40692,26 +39895,19 @@ function registerSearchByTypeEffectivenessTool(server) {
40692
39895
  })
40693
39896
  });
40694
39897
  } catch (error) {
40695
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
40696
- return {
40697
- content: [{
40698
- type: "text",
40699
- text: JSON.stringify({ error: message })
40700
- }],
40701
- isError: true
40702
- };
39898
+ return toErrorResponse(error);
40703
39899
  }
40704
39900
  });
40705
39901
  }
40706
39902
  // src/tools/analysis/selection-analysis.ts
40707
39903
  const CHAMPIONS_GEN_NUM$3 = 0;
40708
- const TOOL_NAME$3 = "analyze_selection";
40709
- const TOOL_DESCRIPTION$3 = "6v6 パーティ間の全対面(最大 36 エントリ)について、タイプ相性・素早さ比較・最大ダメージ見積もりをマトリクスで返す。選出判断は本ツールが返すデータを元に AI が総合的に行う前提で、ツール側では推奨やスコアリングは行わない。ポケモンチャンピオンズ対応。正確な計算のため各ポケモンの ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
40710
- const inputSchema$2 = {
40711
- myParty: z.array(pokemonSchema).describe("自分のパーティ"),
40712
- opponentParty: z.array(pokemonSchema).describe("相手のパーティ"),
39904
+ const TOOL_NAME$4 = "analyze_selection";
39905
+ const TOOL_DESCRIPTION$4 = "6v6 パーティ間の全対面(最大 36 エントリ)について、タイプ相性・素早さ比較・最大ダメージ見積もりをマトリクスで返す。選出判断は本ツールが返すデータを元に AI が総合的に行う前提で、ツール側では推奨やスコアリングは行わない。ポケモンチャンピオンズ対応。正確な計算のため各ポケモンの ability / item の指定を推奨(省略時は通常特性・持ち物なし扱い)。";
39906
+ const inputSchema$3 = {
39907
+ myParty: z.array(pokemonWithMovesSchema).min(1).max(6).describe("自分のパーティ"),
39908
+ opponentParty: z.array(pokemonSchema).min(1).max(6).describe("相手のパーティ"),
40713
39909
  battleFormat: z.enum(["singles", "doubles"]).describe("対戦形式(シングル: singles / ダブル: doubles)"),
40714
- moves: z.record(z.string(), z.array(z.string())).optional().describe("ポケモン名(日本語 or 英語)ごとに候補技を指定する。省略時は全攻撃技で計算。")
39910
+ moves: movesByPokemonSchema.optional().describe("ポケモン名(日本語 or 英語)ごとに候補技を指定する。指定がなければ myParty 各メンバーの moves、それもなければ習得技すべてで計算する。")
40715
39911
  };
40716
39912
  /**
40717
39913
  * 2つのポケモンタイプ配列から、攻撃側→防御側の最大抜群倍率を算出する。
@@ -40756,22 +39952,25 @@ function resolveMovesMap(moves) {
40756
39952
  if (moves === void 0) return result;
40757
39953
  for (const [pokemonName, moveList] of Object.entries(moves)) {
40758
39954
  const englishName = pokemonNameResolver.toEnglish(pokemonName) ?? (pokemonNameResolver.hasEnglishName(pokemonName) ? pokemonName : null);
40759
- if (englishName === null) continue;
39955
+ if (englishName === null) throw new UserFacingError(`moves に指定したポケモン「${pokemonName}」が見つかりません。`);
40760
39956
  const id = toDataId(englishName);
40761
- result.set(id, moveList);
39957
+ result.set(id, damageCalculator.resolveMoveNames(moveList));
40762
39958
  }
40763
39959
  return result;
40764
39960
  }
39961
+ function explicitMovesFor(pokemonId, movesMap) {
39962
+ const moves = movesMap.get(pokemonId);
39963
+ return moves !== void 0 && moves.length > 0 ? moves : void 0;
39964
+ }
40765
39965
  /**
40766
39966
  * attacker vs defender の候補技でダメージを計算する。
40767
- * movesMap に指定があればそれを、無ければ全技で計算する。
40768
- * movesMap 未指定経路では attacker の learnset でフィルタし、覚えない技での過大評価を避ける。
39967
+ * movesMap に指定があればそれを、無ければ attacker.moves、それも無ければ習得技すべてで計算する。
40769
39968
  * 明示指定経路は learnset フィルタを掛けない(ユーザーの明示選択を尊重する既存仕様を維持)。
40770
39969
  * conditions (battleFormat 等) を damageCalculator に伝える。
40771
39970
  */
40772
- function calculateDamageForMatchup(damageCalculator, attacker, defender, attackerId, attackerLearnsetIds, movesMap, conditions) {
40773
- const explicitMoves = movesMap.get(attackerId);
40774
- if (explicitMoves !== void 0 && explicitMoves.length > 0) {
39971
+ function calculateDamageForMatchup(damageCalculator, attacker, defender, attackerId, movesMap, conditions) {
39972
+ const explicitMoves = explicitMovesFor(attackerId, movesMap);
39973
+ if (explicitMoves !== void 0) {
40775
39974
  const results = [];
40776
39975
  for (const moveName of explicitMoves) try {
40777
39976
  results.push(damageCalculator.calculate({
@@ -40784,26 +39983,27 @@ function calculateDamageForMatchup(damageCalculator, attacker, defender, attacke
40784
39983
  results.sort((a, b) => b.max - a.max);
40785
39984
  return results;
40786
39985
  }
40787
- return filterResultsByLearnset(damageCalculator.calculateAllMoves({
39986
+ return damageCalculator.calculateAllMoves({
40788
39987
  attacker,
40789
39988
  defender,
40790
39989
  conditions
40791
- }), attackerLearnsetIds, toDataId);
39990
+ });
40792
39991
  }
40793
- function registerSelectionAnalysisTool(server) {
40794
- server.tool(TOOL_NAME$3, TOOL_DESCRIPTION$3, inputSchema$2, async (args) => {
39992
+ function registerSelectionAnalysisTool(server, movesRequirement = MOVES_OPTIONAL) {
39993
+ server.tool(TOOL_NAME$4, TOOL_DESCRIPTION$4, inputSchema$3, async (args) => {
40795
39994
  try {
40796
39995
  const gen = Generations.get(CHAMPIONS_GEN_NUM$3);
40797
39996
  const movesMap = resolveMovesMap(args.moves);
40798
39997
  const damageConditions = { battleFormat: args.battleFormat };
40799
- function buildMemberContext(input) {
39998
+ function buildMemberContext(input, partyMoves) {
39999
+ damageCalculator.resolveMoveNames(input.moves ?? []);
40800
40000
  const { pokemon, resolvedName } = damageCalculator.createPokemonObject(input);
40801
40001
  const entryId = toDataId(resolvedName);
40802
40002
  const entry = pokemonById.get(entryId);
40803
40003
  const nameJa = pokemonNameResolver.toJapanese(resolvedName) ?? resolvedName;
40804
40004
  const types = entry !== void 0 ? [...entry.types] : [...pokemon.types];
40805
40005
  const priorityMoves = extractPriorityMoves({
40806
- learnsetMoveIds: championsLearnsets[entryId] ?? [],
40006
+ learnsetMoveIds: candidateMoveIds(resolvedName, explicitMovesFor(entryId, partyMoves) ?? input.moves),
40807
40007
  resolveMove: (id) => movesById.get(id),
40808
40008
  toJapanese: (enName) => moveNameResolver.toJapanese(enName)
40809
40009
  });
@@ -40826,10 +40026,13 @@ function registerSelectionAnalysisTool(server) {
40826
40026
  entryId
40827
40027
  };
40828
40028
  }
40829
- const myMembers = args.myParty.map(buildMemberContext);
40830
- const oppMembers = args.opponentParty.map(buildMemberContext);
40831
- const myLearnsetIds = /* @__PURE__ */ new Map();
40832
- for (const mine of myMembers) myLearnsetIds.set(mine.entryId, getLearnsetMoveIdSet(mine.entryId));
40029
+ const myMembers = args.myParty.map((input) => buildMemberContext(input, movesMap));
40030
+ assertMovesSpecified(movesRequirement, myMembers.map((member, index) => ({
40031
+ field: `myParty[${index}]`,
40032
+ name: member.input.name,
40033
+ moves: explicitMovesFor(member.entryId, movesMap) ?? member.input.moves
40034
+ })));
40035
+ const oppMembers = args.opponentParty.map((input) => buildMemberContext(input, /* @__PURE__ */ new Map()));
40833
40036
  const matrix = [];
40834
40037
  for (const mine of myMembers) for (const opp of oppMembers) {
40835
40038
  const myToOpp = maxTypeMultiplier(mine.profile.types, opp.profile.types, gen);
@@ -40837,7 +40040,7 @@ function registerSelectionAnalysisTool(server) {
40837
40040
  const speedCompare = compareSpeed(mine.profile.actualStats.spe, opp.profile.actualStats.spe);
40838
40041
  let damageEstimate = null;
40839
40042
  try {
40840
- damageEstimate = bestDamageEstimate(calculateDamageForMatchup(damageCalculator, mine.input, opp.input, mine.entryId, myLearnsetIds.get(mine.entryId) ?? /* @__PURE__ */ new Set(), movesMap, damageConditions), (enName) => moveNameResolver.toJapanese(enName));
40043
+ damageEstimate = bestDamageEstimate(calculateDamageForMatchup(damageCalculator, mine.input, opp.input, mine.entryId, movesMap, damageConditions), (enName) => moveNameResolver.toJapanese(enName));
40841
40044
  } catch {
40842
40045
  damageEstimate = null;
40843
40046
  }
@@ -40863,14 +40066,7 @@ function registerSelectionAnalysisTool(server) {
40863
40066
  text: JSON.stringify(output)
40864
40067
  });
40865
40068
  } catch (error) {
40866
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
40867
- return {
40868
- content: [{
40869
- type: "text",
40870
- text: JSON.stringify({ error: message })
40871
- }],
40872
- isError: true
40873
- };
40069
+ return toErrorResponse(error);
40874
40070
  }
40875
40071
  });
40876
40072
  }
@@ -40882,14 +40078,14 @@ const NEUTRAL_NATURE_EN = "Serious";
40882
40078
  const JOLLY_NATURE_EN = "Jolly";
40883
40079
  /** around 指定時に参照する実数値の許容幅(±N) */
40884
40080
  const AROUND_WINDOW = 10;
40885
- const TOOL_NAME$2 = "list_speed_tiers";
40886
- const TOOL_DESCRIPTION$2 = "素早さの実数値ライン一覧を取得する。各エントリには finalSpeed(無振り無補正)・withNeutralMax(準速=無補正性格で素早さに 32 SP 振り切り)・withJollyMax(最速=補正性格で素早さに 32 SP 振り切り)の 3 列をデフォルトで含めて返す。S ライン比較や対面の先後判定では準速・最速の双方を必ずユーザーに提示すること(最速だけ示すと準速個体を取りこぼす)。さらに「○○族を抜くために spe を何 SP 振れば良いか」のような S 調整振りの提案にも本ツールを起点にすること。ポケチャンは 1 SP 単位で振れるため、ブッパ (spe 32 SP 振り切り) 一択ではなく、必要なラインを抜く最小 SP を逆算して残りを別ステに回すのが基本。around で指定ポケモン付近、range で実数値範囲を指定できる。省略時は全ポケモンを返す。ポケモンチャンピオンズ仕様(Lv50・IV31・SP 0〜32)で計算。";
40081
+ const TOOL_NAME$3 = "list_speed_tiers";
40082
+ const TOOL_DESCRIPTION$3 = "素早さの実数値ライン一覧を取得する。各エントリには finalSpeed(無振り無補正)・withNeutralMax(準速=無補正性格で素早さに 32 SP 振り切り)・withJollyMax(最速=補正性格で素早さに 32 SP 振り切り)の 3 列をデフォルトで含めて返す。S ライン比較や対面の先後判定では準速・最速の双方を必ずユーザーに提示すること(最速だけ示すと準速個体を取りこぼす)。さらに「○○族を抜くために spe を何 SP 振れば良いか」のような S 調整振りの提案にも本ツールを起点にすること。ポケチャンは 1 SP 単位で振れるため、ブッパ (spe 32 SP 振り切り) 一択ではなく、必要なラインを抜く最小 SP を逆算して残りを別ステに回すのが基本。around で指定ポケモン付近、range で実数値範囲を指定できる。省略時は全ポケモンを返す。ポケモンチャンピオンズ仕様(Lv50・IV31・SP 0〜32)で計算。";
40887
40083
  const rangeSchema = z.object({
40888
40084
  min: z.number().optional(),
40889
40085
  max: z.number().optional()
40890
40086
  }).optional().describe("実数値 (finalSpeed) の範囲フィルタ");
40891
- const inputSchema$1 = {
40892
- around: z.string().optional().describe(`指定ポケモン付近(±${AROUND_WINDOW})の素早さラインのみを返す。`),
40087
+ const inputSchema$2 = {
40088
+ around: nameInputSchema.optional().describe(`指定ポケモン付近(±${AROUND_WINDOW})の素早さラインのみを返す。`),
40893
40089
  range: rangeSchema
40894
40090
  };
40895
40091
  /**
@@ -40918,15 +40114,14 @@ function resolvePokemonEntry(name) {
40918
40114
  const englishName = pokemonNameResolver.toEnglish(name) ?? (pokemonNameResolver.hasEnglishName(name) ? name : null);
40919
40115
  if (englishName === null) {
40920
40116
  const suggestions = pokemonNameResolver.suggestSimilar(name);
40921
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
40922
- throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
40117
+ throw new UserFacingError(`ポケモン「${name}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
40923
40118
  }
40924
40119
  const entry = pokemonById.get(toDataId(englishName));
40925
- if (entry === void 0) throw new Error(`ポケモン「${name}」のデータが見つかりません。`);
40120
+ if (entry === void 0) throw new UserFacingError(`ポケモン「${name}」のデータが見つかりません。`);
40926
40121
  return entry;
40927
40122
  }
40928
40123
  function registerSpeedTiersTool(server) {
40929
- server.tool(TOOL_NAME$2, TOOL_DESCRIPTION$2, inputSchema$1, async (args) => {
40124
+ server.tool(TOOL_NAME$3, TOOL_DESCRIPTION$3, inputSchema$2, async (args) => {
40930
40125
  try {
40931
40126
  const gen = Generations.get(CHAMPIONS_GEN_NUM$2);
40932
40127
  let filtered = championsPokemon.map((entry) => {
@@ -40963,25 +40158,18 @@ function registerSpeedTiersTool(server) {
40963
40158
  text: JSON.stringify({ entries: filtered })
40964
40159
  });
40965
40160
  } catch (error) {
40966
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
40967
- return {
40968
- content: [{
40969
- type: "text",
40970
- text: JSON.stringify({ error: message })
40971
- }],
40972
- isError: true
40973
- };
40161
+ return toErrorResponse(error);
40974
40162
  }
40975
40163
  });
40976
40164
  }
40977
40165
  // src/tools/calc/stats-calculation.ts
40978
40166
  const CHAMPIONS_GEN_NUM$1 = 0;
40979
40167
  const DEFAULT_NATURE_EN = "Serious";
40980
- const TOOL_NAME$1 = "calculate_stats";
40981
- const TOOL_DESCRIPTION$1 = "ポケモンの実数値を計算する。種族値・性格・能力ポイントから各ステータスの実数値を算出する。育成方針の検討や調整ラインの確認に使用する。SP 振りを提案するときは、ブッパ (各ステ 32 振り切り) を勧めるのではなく、本ツールで実数値を試算しつつ目的駆動で刻むこと(ポケチャンは 1 SP 単位で振れる / 合計上限は 66 SP / 火力調整・耐久調整・S 調整のいずれも最小限の SP で要求を満たすのが基本)。ポケモンチャンピオンズの計算式に対応。";
40168
+ const TOOL_NAME$2 = "calculate_stats";
40169
+ const TOOL_DESCRIPTION$2 = "ポケモンの実数値を計算する。種族値・性格・能力ポイントから各ステータスの実数値を算出する。育成方針の検討や調整ラインの確認に使用する。SP 振りを提案するときは、ブッパ (各ステ 32 振り切り) を勧めるのではなく、本ツールで実数値を試算しつつ目的駆動で刻むこと(ポケチャンは 1 SP 単位で振れる / 合計上限は 66 SP / 火力調整・耐久調整・S 調整のいずれも最小限の SP で要求を満たすのが基本)。ポケモンチャンピオンズの計算式に対応。";
40982
40170
  const statsCalcInputSchema = {
40983
- name: z.string().describe("ポケモン名(日本語 or 英語)"),
40984
- nature: z.string().optional().describe("性格名(省略時: まじめ)"),
40171
+ name: nameInputSchema.describe("ポケモン名(日本語 or 英語)"),
40172
+ nature: nameInputSchema.optional().describe("性格名(省略時: まじめ)"),
40985
40173
  evs: evsSchema.optional().describe("能力ポイント(SP)。各ステ 0-32、合計 0-66。省略時は全 0 (無振り)。")
40986
40174
  };
40987
40175
  /**
@@ -40992,8 +40180,7 @@ function resolvePokemonName(name) {
40992
40180
  if (englishName !== void 0) return englishName;
40993
40181
  if (pokemonNameResolver.hasEnglishName(name)) return name;
40994
40182
  const suggestions = pokemonNameResolver.suggestSimilar(name);
40995
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
40996
- throw new Error(`ポケモン「${name}」が見つかりません。${suggestionMessage}`);
40183
+ throw new UserFacingError(`ポケモン「${name}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
40997
40184
  }
40998
40185
  /**
40999
40186
  * 性格名を英語に解決する。
@@ -41004,16 +40191,15 @@ function resolveNatureName(nature) {
41004
40191
  if (englishName !== void 0) return englishName;
41005
40192
  if (natureNameResolver.hasEnglishName(nature)) return nature;
41006
40193
  const suggestions = natureNameResolver.suggestSimilar(nature);
41007
- const suggestionMessage = suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : "";
41008
- throw new Error(`性格「${nature}」が見つかりません。${suggestionMessage}`);
40194
+ throw new UserFacingError(`性格「${nature}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
41009
40195
  }
41010
40196
  function registerStatsCalculationTool(server) {
41011
- server.tool(TOOL_NAME$1, TOOL_DESCRIPTION$1, statsCalcInputSchema, async (args) => {
40197
+ server.tool(TOOL_NAME$2, TOOL_DESCRIPTION$2, statsCalcInputSchema, async (args) => {
41012
40198
  try {
41013
40199
  const gen = Generations.get(CHAMPIONS_GEN_NUM$1);
41014
40200
  const nameEn = resolvePokemonName(args.name);
41015
40201
  const entry = pokemonById.get(toDataId(nameEn));
41016
- if (entry === void 0) throw new Error(`ポケモン「${args.name}」のデータが見つかりません。`);
40202
+ if (entry === void 0) throw new UserFacingError(`ポケモン「${args.name}」のデータが見つかりません。`);
41017
40203
  const natureEn = resolveNatureName(args.nature);
41018
40204
  const nameJa = entry.nameJa ?? entry.name;
41019
40205
  const natureJa = natureNameResolver.toJapanese(natureEn) ?? natureEn;
@@ -41059,22 +40245,15 @@ function registerStatsCalculationTool(server) {
41059
40245
  text: JSON.stringify(output)
41060
40246
  });
41061
40247
  } catch (error) {
41062
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
41063
- return {
41064
- content: [{
41065
- type: "text",
41066
- text: JSON.stringify({ error: message })
41067
- }],
41068
- isError: true
41069
- };
40248
+ return toErrorResponse(error);
41070
40249
  }
41071
40250
  });
41072
40251
  }
41073
40252
  // src/tools/info/type-info.ts
41074
40253
  const CHAMPIONS_GEN_NUM = 0;
41075
- const TOOL_NAME = "get_type_info";
41076
- const TOOL_DESCRIPTION = "ポケモンのタイプの相性情報(攻撃時・防御時の倍率)を取得する。対戦でタイプ相性を確認したいときに使用する。ポケモンチャンピオンズ対応。";
41077
- const inputSchema = { type: z.string().describe("タイプ名(日本語 or 英語、例: 'ほのお'、'Fire')") };
40254
+ const TOOL_NAME$1 = "get_type_info";
40255
+ const TOOL_DESCRIPTION$1 = "ポケモンのタイプの相性情報(攻撃時・防御時の倍率)を取得する。対戦でタイプ相性を確認したいときに使用する。ポケモンチャンピオンズ対応。";
40256
+ const inputSchema$1 = { type: nameInputSchema.describe("タイプ名(日本語 or 英語、例: 'ほのお'、'Fire')") };
41078
40257
  /**
41079
40258
  * タイプ名を英語に解決する。日本語名・英語名どちらでも受け付ける。
41080
40259
  * 見つからない場合はエラーをスローする。
@@ -41084,14 +40263,14 @@ function resolveTypeNameEn(input) {
41084
40263
  const normalized = input.toLowerCase();
41085
40264
  const entry = typesById.get(normalized);
41086
40265
  if (entry !== void 0) return entry.name;
41087
- throw new Error(`タイプ「${input}」が見つかりません。`);
40266
+ throw new UserFacingError(`タイプ「${input}」が見つかりません。`);
41088
40267
  }
41089
40268
  function registerTypeInfoTool(server) {
41090
- server.tool(TOOL_NAME, TOOL_DESCRIPTION, inputSchema, async (args) => {
40269
+ server.tool(TOOL_NAME$1, TOOL_DESCRIPTION$1, inputSchema$1, async (args) => {
41091
40270
  try {
41092
40271
  const englishName = resolveTypeNameEn(args.type);
41093
40272
  const typeEntry = typesById.get(englishName.toLowerCase());
41094
- if (typeEntry === void 0) throw new Error(`タイプ「${args.type}」のデータが見つかりません。`);
40273
+ if (typeEntry === void 0) throw new UserFacingError(`タイプ「${args.type}」のデータが見つかりません。`);
41095
40274
  const gen = Generations.get(CHAMPIONS_GEN_NUM);
41096
40275
  const attackingTypeName = englishName;
41097
40276
  const attackingEffectiveness = {};
@@ -41121,51 +40300,601 @@ function registerTypeInfoTool(server) {
41121
40300
  text: JSON.stringify(output)
41122
40301
  });
41123
40302
  } catch (error) {
41124
- const message = error instanceof Error ? error.message : "不明なエラーが発生しました";
41125
- return {
41126
- content: [{
41127
- type: "text",
41128
- text: JSON.stringify({ error: message })
41129
- }],
41130
- isError: true
41131
- };
40303
+ return toErrorResponse(error);
41132
40304
  }
41133
40305
  });
41134
40306
  }
41135
- // src/server.ts
40307
+ // src/core-server.ts
41136
40308
  const SERVER_NAME = "ai-rotom";
41137
- const SERVER_VERSION = "0.0.1";
41138
- function createServer() {
40309
+ const SERVER_VERSION = "2.0.0";
40310
+ /**
40311
+ * 1 回のツール呼び出しで受け付ける引数の要素数 (配列の要素とオブジェクトのメンバーの合計) の上限。
40312
+ */
40313
+ const MAX_TOOL_INPUT_ELEMENTS = 1e3;
40314
+ /**
40315
+ * パーティ保存系を除くツールを登録した MCP サーバーを作る。
40316
+ * 保存系はファイルに書き込むので、ファイルを持たない実行環境でも読み込めるよう、ここから import しない。
40317
+ */
40318
+ function createCoreServer(instructions, movesRequirement = MOVES_OPTIONAL) {
41139
40319
  const server = new McpServer({
41140
40320
  name: SERVER_NAME,
41141
40321
  version: SERVER_VERSION
41142
- }, { instructions: SERVER_INSTRUCTIONS });
40322
+ }, {
40323
+ instructions,
40324
+ maxToolInputElements: MAX_TOOL_INPUT_ELEMENTS
40325
+ });
41143
40326
  registerAbilityInfoTool(server);
41144
40327
  registerComparePartiesTool(server);
41145
40328
  registerConditionInfoTool(server);
41146
- registerDamageCalculationTools(server);
40329
+ registerDamageCalculationTools(server, movesRequirement);
41147
40330
  registerDamageRangeTool(server);
41148
- registerFindCountersTool(server);
41149
- registerImportPartyFromTextTool(server);
41150
40331
  registerItemInfoTool(server);
41151
40332
  registerLearnsetTool(server);
41152
- registerMatchupTool(server);
40333
+ registerMatchupTool(server, movesRequirement);
41153
40334
  registerMoveInfoTool(server);
41154
40335
  registerNatureInfoTool(server);
41155
40336
  registerPartyAnalysisTool(server);
41156
40337
  registerPartyCoverageTool(server);
41157
- registerPartyTools(server);
41158
40338
  registerPokemonInfoTools(server);
41159
40339
  registerPokemonSummaryTool(server);
41160
40340
  registerSearchByAbilityTool(server);
41161
40341
  registerSearchByMoveTool(server);
41162
40342
  registerSearchByTypeEffectivenessTool(server);
41163
- registerSelectionAnalysisTool(server);
40343
+ registerSelectionAnalysisTool(server, movesRequirement);
41164
40344
  registerSpeedTiersTool(server);
41165
40345
  registerStatsCalculationTool(server);
41166
40346
  registerTypeInfoTool(server);
41167
40347
  return server;
41168
40348
  }
40349
+ const SERVER_INSTRUCTIONS = `${`
40350
+ ai-rotom はポケモンチャンピオンズ (Pokemon Champions) の対戦アドバイザー MCP サーバーです。
40351
+
40352
+ ## セッションスコープ(重要)
40353
+
40354
+ - このセッション内でポケモン関連の話題が出た場合は、すべてポケモンチャンピオンズ (Pokemon Champions) の仕様として扱ってください。
40355
+ - 従来作 (SV / 剣盾 / USUM / BDSP / LA 等) の仕様・技威力・特性効果・種族値・タイプ相性などを前提にしないでください。
40356
+ - ポケモン名・技名・特性・持ち物・タイプ・素早さ等の固有名詞や数値がユーザー発話に出た時点で、まず本サーバーのツールを呼んで事実を取得してから回答すること。記憶や推測で即答しない (下の「ツール利用方針(必須)」を参照)。
40357
+ - ポケチャン固有仕様で不明な点は推測で埋めず、ユーザーに確認してください。
40358
+
40359
+ 以降は、従来作と差異が出やすい代表的な固有仕様です。
40360
+
40361
+ ## 能力ポイント (SP) について
40362
+
40363
+ - 従来の「努力値 (EV)」は廃止され、「能力ポイント (SP)」という仕様に変更されました。
40364
+ - 各ステータス (hp/atk/def/spa/spd/spe) あたりの上限: 32 SP
40365
+ - 全ステータス合計の上限: 66 SP
40366
+ - 1 SP = 実数値 +1 で直接加算されます (従来 EV の「4 EV = 実数値 +1」ではありません)。
40367
+ - 各ステ 0〜32、合計 0〜66 の範囲内なら振り方は自由です。
40368
+ - 従来の 252 EV / 510 EV 合計上限をそのまま渡すとエラーになります。
40369
+
40370
+ ## SP 振りの実践(重要)
40371
+
40372
+ ポケチャンの SP は **1 単位で振れる**(各ステ 0〜32、合計 0〜66)ため、
40373
+ 従来作流の「とりあえず最速」「とりあえず HP252」のような **ブッパ一辺倒は最適でないことが多い**。
40374
+ AI クライアントは目的駆動で刻む振り方を提案すること。各ステに 32 振り切るより、
40375
+ 要求を満たす最小限を割り当てて余り SP を別の役割に回す方が、合計 66 SP の制約下では強い。
40376
+
40377
+ ### 火力調整(atk / spa)
40378
+ - 「主要対面相手を確定 1 発(or 確定 2 発)で落とす最低限の振り」を calculate_damage_single / calculate_damage_all_moves で逆算する。
40379
+ - 余った SP は HP / 素早さ / 別ステに回す。
40380
+
40381
+ ### 耐久調整(hp / def / spd)
40382
+ - 「主要対面相手の技を確定耐えする最低限の振り」を analyze_damage_range で逆算する。
40383
+ - 物理耐久は hp + def、特殊耐久は hp + spd の組み合わせで効率化。HP のみブッパだと無駄が出やすい。
40384
+
40385
+ ### 素早さ調整(spe)— S 調整振り
40386
+ - 「特定ラインを抜く / 同速回避するピンポイント振り」を list_speed_tiers + calculate_stats で逆算する。
40387
+ - 例: 準速 100 族(実数値 152)を抜きたいだけなら spe を 32 振り切る必要はなく、必要最小限の SP で抜ける。
40388
+ - 同速回避は相手と同じ振りに対し +1 SP 多く振る。
40389
+
40390
+ ### 提案フローのテンプレート
40391
+ 1. ユーザーに役割(耐久型 / 火力型 / 削り役 / サポート 等)と主要対面相手 2-3 体を確認する。
40392
+ 2. 火力 / 耐久 / 素早さの要求 SP を、対面相手ごとに計算ツールで逆算する。
40393
+ 3. 合計 66 SP の制約内で配分案を提示する(複数案あれば併記)。
40394
+ 4. 余り SP の使い道(HP / 素早さ微調整 / 火力上乗せ)も併記する。
40395
+
40396
+ 「ブッパで雑に最速・HP 全振り」の提案はポケチャンでは型として弱いため、明示的に要求された場合を除き避けること。
40397
+
40398
+ ## その他の固有仕様
40399
+
40400
+ - 個体値 (IV): 廃止。全ポケモン一律 31 固定として扱われます。
40401
+ - 対戦レベル: 50 固定。
40402
+ - メガシンカ: 1試合につき1回のみ使用可能。
40403
+ - テラスタル: 未対応 (ゲーム側で未実装のため)。
40404
+ - 特性の一部は計算エンジンが未対応で、ダメージ計算結果に効果が反映されません。get_ability_info で効果を確認し、必要に応じて結果の解釈時に補正してください。
40405
+ - 持ち物の一部も同様に計算エンジンが未対応で、ダメージ計算結果に効果が反映されません (フィールド・接地判定に関わるものは反映されます)。get_item_info で効果を確認してください。
40406
+ - メガシンカ後のフォルムと、一部のフォルムは覚える技 (learnset) のデータが未整備です。この場合 get_learnset はエラーになり、get_pokemon_summary の learnableMoves.count は 0、技の逆引き検索 (search_pokemon_by_move 等) では結果に出てきませんが、いずれも「技を覚えない」という意味ではありません。未整備かどうかは get_pokemon_info の learnableMoveCount が null かどうかで判別できるため、技プールを断定せずデータ未整備である旨をユーザーに伝えてください。これらの技プールはベースフォームの learnset を参照してください。
40407
+
40408
+ ## 判断と計算の役割分担
40409
+
40410
+ - 本サーバーのツールは「判断の根拠となる正確なデータを返す」ことに責務を限定しています。
40411
+ 「この選出が最適」「この構築が正解」といった最終判断は返しません。
40412
+ - 選出・構築・対策の結論は、ツールが返したデータ (タイプ相性・ダメ計・素早さ比較・対面マトリクス等) を元に AI が総合的に導いてください。
40413
+
40414
+ ## ツール利用方針(必須)
40415
+
40416
+ 以下のトピックがユーザー発話に出てきたら、必ず該当ツールを呼んで根拠データを取得してから回答すること。
40417
+ ポケチャンは従来作と種族値・技威力・特性効果等で差異が出るため、知識ベースの即答は禁止。
40418
+
40419
+ ### ポケモン検索・情報取得 (「○○ってどんなポケモン?」「○○タイプで素早いポケモンは?」等)
40420
+ - 単体の基本情報 (種族値 / タイプ / 特性 / 体重) → get_pokemon_info
40421
+ - 単体の総合プロファイル (耐性 / 覚える技 / 実数値) → get_pokemon_summary
40422
+ - タイプ・種族値での絞り込み → search_pokemon
40423
+ - 技の逆引き (この技を覚えるポケモン) → search_pokemon_by_move
40424
+ - 特性の逆引き (この特性を持つポケモン) → search_pokemon_by_ability
40425
+ - タイプ相性での逆引き (○○タイプを半減/無効化する等) → search_pokemon_by_type_effectiveness
40426
+ - 覚える技一覧 → get_learnset
40427
+
40428
+ ### 技・攻撃まわり (「○○の威力は?」「電気タイプで威力高い技は?」「攻撃範囲は?」等)
40429
+ - 技の威力 / タイプ / 効果 / PP → get_move_info
40430
+ - ある技を覚えるポケモン一覧 → search_pokemon_by_move
40431
+ - 個体 / パーティの攻撃範囲 → get_pokemon_summary / analyze_party_coverage
40432
+ - ダメージ計算 → calculate_damage_single (1 対 1 単発) / calculate_damage_all_moves (1 対 1 全技) / calculate_damage_party_matchup (6v6)
40433
+ - 確定数 / 乱数 / 耐久要求の逆算 → analyze_damage_range
40434
+
40435
+ ### 素早さ (S ライン) (「○○の素早さは?」「○○より早いポケモンは?」「S○○族は?」等)
40436
+ - 実数値計算 → calculate_stats
40437
+ - 素早さライン一覧・スカーフ込み比較 → list_speed_tiers
40438
+ - 対面での先後判定 (素早さ比較込み) → analyze_matchup
40439
+
40440
+ ### 対策候補 (「○○の対策は?」「○○に勝てるポケモンは?」等)
40441
+ - 相手の弱点タイプを get_pokemon_summary の defenses で確認する
40442
+ - 弱点タイプの攻撃技を覚えるポケモンを search_pokemon_by_type_effectiveness で検索する。タイプは 1 回に 1 つしか指定できないので、弱点が複数あればタイプごとに呼ぶ。相手の主力技のタイプを半減以下で受けるポケモンも同じツールで探せる
40443
+ - 候補ごとに analyze_matchup を呼び、双方向のダメ計・素早さ・先制技を取得する。相手の技構成がわかっていれば moves を指定する
40444
+ - どの候補を検討するか、受けて倒すのか上から倒すのかといった判断は AI が行う
40445
+
40446
+ ### その他の事実確認 (「○○の特性効果は?」「○○の効果は?」「ねっぷう撃たれたら?」等)
40447
+ - 特性効果 → get_ability_info
40448
+ - 持ち物効果 → get_item_info
40449
+ - 性格補正 → get_nature_info
40450
+ - タイプ相性 → get_type_info
40451
+ - 天候 / 状態異常 / フィールド / 壁 → get_condition_info
40452
+
40453
+ ## 計算・分析系ツールでの ability / item 指定
40454
+
40455
+ - 計算・対面分析系ツール (calculate_damage_single / calculate_damage_all_moves / calculate_damage_party_matchup / analyze_damage_range / analyze_matchup / analyze_selection) を呼ぶ前に、攻撃側・防御側の ability / item を確認してから指定すること。
40456
+ - 省略時の挙動: ability は通常特性 (pokemon.json の abilities[0]) が自動設定され、item は持ち物なし扱いとなる。そのためメガシンカ・こだわり系・半減きのみ・ちからのハチマキ 等が反映されず、実戦想定の build と乖離した結果になる。
40457
+ - 正確な計算のためには ability / item を明示的に指定することを強く推奨する。
40458
+ - 一方で、育成データ (evs・nature) が不明な場合は省略してよい (デフォルト値で計算)。
40459
+ `.trim()}\n\n${`
40460
+ ## パーティデータの扱い
40461
+
40462
+ - セッション開始時 (初回ユーザー発話への応答前) に必ず list_parties を呼び、保存済みパーティの名前一覧を把握すること。
40463
+ - ユーザーが「メインパ」「ドラゴン軸」等の保存名に言及したら load_party で詳細を取得し、分析ツールに渡すこと。
40464
+ - ユーザーが新規構築を説明した際は「保存しますか」と確認し、同意があれば save_party を呼ぶこと。
40465
+ - パーティの削除依頼は delete_party を使うこと。
40466
+ - 起動時にパーティ詳細まで自動読み込みしないこと (トークン消費を抑えるため、詳細は都度 load_party で取得する)。
40467
+
40468
+ ## パーティ登録の対話スタイル
40469
+
40470
+ ユーザーが「パーティを保存したい」「構築を覚えて」等と依頼した場合:
40471
+
40472
+ ### テキスト一括投入の場合 (ケース A)
40473
+
40474
+ - ユーザーが Showdown 風 or ポケソルテキストを貼り付けた → import_party_from_text を呼ぶ (原文をそのまま渡す)。
40475
+ - ユーザーがゲーム内画面のスクショを添付した → 画像から build を読み取り、下記の対話ケース (B) と同じ手順でポケソルテキストに整理してから import_party_from_text を呼ぶ。
40476
+
40477
+ ### 対話で埋める場合 (ケース B)
40478
+
40479
+ - ユーザーがテキストもスクショも提供しない → AI が段階的に質問する。
40480
+ - 1 匹ずつ以下の順で聞く (ユーザーが知っている情報から埋める):
40481
+ 1. ポケモン名 (日本語 or 英語)
40482
+ 2. 性格 (候補を 4-5 個提示: いじっぱり / ようき / ひかえめ / おくびょう / ずぶとい など)
40483
+ 3. 特性 (該当ポケモンの候補を提示)
40484
+ 4. もちもの (省略可能、候補があれば提示)
40485
+ 5. 技 4 つ
40486
+ 6. SP 配分 (省略時は無振り 0、指定あれば各 0〜32 / 合計 0〜66 で受け付け)
40487
+
40488
+ ### 整理ステップ (重要)
40489
+
40490
+ - 対話で情報が揃ったら、必ずポケソルテキスト形式にまとめて表示し、ユーザーに確認を取ること:
40491
+
40492
+ 例:
40493
+ ガブリアス @ こだわりスカーフ
40494
+ 特性: さめはだ
40495
+ 能力補正: いじっぱり
40496
+ 170(2)-200(32)-115(0)-90(0)-100(0)-167(32)
40497
+ じしん / ドラゴンクロー / つのドリル / いわなだれ
40498
+
40499
+ - 実数値が不明な場合は calculate_stats を呼んで補完する (パーサー仕様上、実数値行は省略可能だが、ユーザー確認用に含めることを推奨)。
40500
+ - 複数匹の場合は空行区切りで並べる。
40501
+ - ユーザー確認後 import_party_from_text(text, name, memo) を呼ぶ。
40502
+ - パーサーがエラーを返した場合は、原因を提示してユーザーに修正を確認する。
40503
+
40504
+ ### 質問の書き方ルール
40505
+
40506
+ - 質問は短く、候補があれば列挙する (「性格はどうしますか? いじっぱり / ようき / ひかえめ」のような形式)。
40507
+ - 一度に 1 項目だけ聞く (複数同時の質問は避ける)。
40508
+ - ユーザーが「後で決める」と言った項目はデフォルト値で埋める (性格=まじめ、特性=基本特性、SP=無振り 等)。
40509
+ - 不明な項目は tool 呼び出しで確認する (例: 覚える技 → get_learnset)。
40510
+
40511
+ ### 絶対に守ること
40512
+
40513
+ - 対話で得た情報を JSON 化して save_party を直接呼ばない (ハルシネーションリスク軽減のため必ずポケソルテキスト経由)。
40514
+ - ユーザー確認なしに save / import を実行しない。
40515
+ `.trim()}`;
40516
+ // src/party-store.ts
40517
+ /** ai-rotom の永続化用ディレクトリ名 (ホーム直下)。 */
40518
+ const AI_ROTOM_DIR_NAME = ".ai-rotom";
40519
+ /** パーティ永続化ファイル名。 */
40520
+ const PARTIES_FILE_NAME = "parties.json";
40521
+ /** atomic write 用の一時ファイル拡張子。 */
40522
+ const TEMP_FILE_EXT = ".tmp";
40523
+ /** JSON.stringify の indent。 */
40524
+ const JSON_INDENT = 2;
40525
+ /** 一時ファイル名用のランダムサフィックスバイト数。 */
40526
+ const TEMP_SUFFIX_BYTES = 8;
40527
+ /**
40528
+ * 永続化ファイル (`~/.ai-rotom/parties.json`) の絶対パスを返す。
40529
+ * ホームディレクトリが解決できない場合はエラーを投げる。
40530
+ */
40531
+ function resolvePartiesFilePath() {
40532
+ const home = homedir();
40533
+ if (home === "" || home === void 0 || home === null) throw new UserFacingError("ホームディレクトリが解決できませんでした。$HOME 環境変数を確認してください。");
40534
+ return join(home, AI_ROTOM_DIR_NAME, PARTIES_FILE_NAME);
40535
+ }
40536
+ /**
40537
+ * 永続化ファイルの読み込み結果。
40538
+ * 存在しない場合は空の PartiesFile を返す。
40539
+ * 破損・権限・schemaVersion 不整合の場合はエラーを投げる。
40540
+ */
40541
+ function loadPartiesFile(filePath = resolvePartiesFilePath()) {
40542
+ let raw;
40543
+ try {
40544
+ raw = readFileSync(filePath, { encoding: "utf-8" });
40545
+ } catch (error) {
40546
+ if (isNodeErrnoException(error) && error.code === "ENOENT") return {
40547
+ schemaVersion: 1,
40548
+ parties: []
40549
+ };
40550
+ throw wrapIoError("パーティファイルの読み込みに失敗しました", error);
40551
+ }
40552
+ let parsed;
40553
+ try {
40554
+ parsed = JSON.parse(raw);
40555
+ } catch (error) {
40556
+ throw new UserFacingError(`パーティファイル (${filePath}) の JSON パースに失敗しました: ${error instanceof Error ? error.message : String(error)}`);
40557
+ }
40558
+ const result = partiesFileSchema.safeParse(parsed);
40559
+ if (!result.success) throw new UserFacingError(`パーティファイル (${filePath}) のスキーマ検証に失敗しました: ${result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`);
40560
+ if (result.data.schemaVersion !== 1) throw new UserFacingError(`未対応の schemaVersion (${result.data.schemaVersion}) です。現行は 1 です。`);
40561
+ return result.data;
40562
+ }
40563
+ /**
40564
+ * 永続化ファイルを atomic に書き込む。
40565
+ * 親ディレクトリが存在しない場合は作成する。
40566
+ * 一時ファイル → rename で置き換えるため、途中失敗でも元ファイルは壊れない。
40567
+ */
40568
+ function savePartiesFile(data, filePath = resolvePartiesFilePath()) {
40569
+ const validated = partiesFileSchema.parse(data);
40570
+ const dir = dirname(filePath);
40571
+ try {
40572
+ mkdirSync(dir, { recursive: true });
40573
+ } catch (error) {
40574
+ throw wrapIoError(`パーティ保存ディレクトリ (${dir}) の作成に失敗しました`, error);
40575
+ }
40576
+ const tempPath = `${filePath}.${randomBytes(TEMP_SUFFIX_BYTES).toString("hex")}${TEMP_FILE_EXT}`;
40577
+ const serialized = JSON.stringify(validated, null, JSON_INDENT);
40578
+ try {
40579
+ writeFileSync(tempPath, serialized, {
40580
+ encoding: "utf-8",
40581
+ mode: 384
40582
+ });
40583
+ renameSync(tempPath, filePath);
40584
+ } catch (error) {
40585
+ try {
40586
+ rmSync(tempPath, { force: true });
40587
+ } catch {}
40588
+ throw wrapIoError(`パーティファイル (${filePath}) の保存に失敗しました`, error);
40589
+ }
40590
+ }
40591
+ function isNodeErrnoException(value) {
40592
+ return value instanceof Error && typeof value.code === "string";
40593
+ }
40594
+ function wrapIoError(prefix, error) {
40595
+ const message = error instanceof Error ? error.message : String(error);
40596
+ return new UserFacingError(`${prefix}${isNodeErrnoException(error) && error.code !== void 0 ? ` [${error.code}]` : ""}: ${message}`);
40597
+ }
40598
+ // src/party-text.ts
40599
+ /** ポケソルテキストで性格を省略した場合のデフォルト。 */
40600
+ const DEFAULT_NATURE_NAME = "まじめ";
40601
+ /**
40602
+ * ポケソルテキストを空行区切りで個別ブロックに分割する。
40603
+ * 改行 (LF / CRLF) のどちらにも対応する。
40604
+ * 空白のみのブロックは除外する。
40605
+ */
40606
+ function splitPokesolTextBlocks(text) {
40607
+ return text.replace(/\r\n/g, "\n").split(/\n\s*\n/).map((block) => block.trim()).filter((block) => block.length > 0);
40608
+ }
40609
+ /**
40610
+ * パーサー出力 (`PokesolTextParseReult`) を `PartyMember` に変換する。
40611
+ * - `abilityNames[1..]` (括弧内のメガ前特性) が存在すれば最も元の状態 (末尾) を
40612
+ * `ability` として保存 (通常状態の特性が基本。メガ進化時の特性変化は計算側の責務)
40613
+ * - `natureName` が null の場合は `DEFAULT_NATURE_NAME` で補完
40614
+ * - `terastalName` が存在する場合はポケチャン未対応のため無視
40615
+ * - `moveNames` が空配列の場合は `moves` フィールド自体を省く
40616
+ *
40617
+ * 補完・無視を行った場合はブロック番号付きの warnings を返す。
40618
+ */
40619
+ function mapPokesolResultToPartyMember(result, blockNumber) {
40620
+ const warnings = [];
40621
+ if (result.pokemonName === null || result.pokemonName === "") throw new UserFacingError(`ブロック ${blockNumber}: ポケモン名が読み取れませんでした。`);
40622
+ const member = { name: result.pokemonName };
40623
+ if (result.itemName !== null) member.item = result.itemName;
40624
+ const { ability, ignoredAbilities } = selectAbility(result.abilityNames);
40625
+ if (ability !== void 0) {
40626
+ member.ability = ability;
40627
+ if (ignoredAbilities.length > 0) {
40628
+ const ignored = ignoredAbilities.map((name) => `「${name}」`).join("");
40629
+ warnings.push(`ブロック ${blockNumber}: メガ進化特性${ignored}は無視し、メガ前特性「${ability}」を ability として保存しました。`);
40630
+ }
40631
+ }
40632
+ if (result.natureName !== null) member.nature = result.natureName;
40633
+ else {
40634
+ member.nature = DEFAULT_NATURE_NAME;
40635
+ warnings.push(`ブロック ${blockNumber}: 性格が省略されていたためデフォルト「${DEFAULT_NATURE_NAME}」を補完しました。`);
40636
+ }
40637
+ if (result.terastalName !== null && result.terastalName !== "") warnings.push(`ブロック ${blockNumber}: テラスタイプ「${result.terastalName}」はポケモンチャンピオンズ未対応のため無視しました。`);
40638
+ const evs = buildEvsFromResult(result.evs);
40639
+ if (evs !== void 0) member.evs = evs;
40640
+ if (result.moveNames.length > 0) member.moves = [...result.moveNames];
40641
+ else warnings.push(`ブロック ${blockNumber}: 技行が省略されていたため moves を空で登録しました。`);
40642
+ return {
40643
+ member,
40644
+ warnings
40645
+ };
40646
+ }
40647
+ /**
40648
+ * パーサー出力の `abilityNames` から `PartyMember.ability` に保存する特性を選ぶ。
40649
+ * `abilityNames` は `[現在の特性, ...括弧内の以前の特性]` の順で、
40650
+ * 特性名が省略された位置 (`特性: (さめはだ)` の先頭など) は null になる。
40651
+ *
40652
+ * - 括弧内に特性があれば、最も元の状態である末尾の特性を採用する
40653
+ * - 括弧内が全て空なら現在の特性を採用する
40654
+ * - 採用しなかった特性 (重複を除く) は ignoredAbilities として返す
40655
+ */
40656
+ function selectAbility(abilityNames) {
40657
+ const names = abilityNames.filter((name) => name !== null);
40658
+ const [currentAbility, ...previousAbilities] = abilityNames;
40659
+ const ability = previousAbilities.filter((name) => name !== null).at(-1) ?? currentAbility ?? void 0;
40660
+ return {
40661
+ ability,
40662
+ ignoredAbilities: [...new Set(names)].filter((name) => name !== ability)
40663
+ };
40664
+ }
40665
+ /**
40666
+ * パーサー出力の SP (努力値フィールド) を `EvsInput` に変換する。
40667
+ * 全て 0 の場合は undefined を返し、`PartyMember.evs` を省く。
40668
+ */
40669
+ function buildEvsFromResult(parserEvs) {
40670
+ const mapped = {
40671
+ hp: parserEvs.hp,
40672
+ atk: parserEvs.attack,
40673
+ def: parserEvs.defense,
40674
+ spa: parserEvs.specialAttack,
40675
+ spd: parserEvs.specialDefense,
40676
+ spe: parserEvs.speed
40677
+ };
40678
+ return Object.values(mapped).some((value) => value !== void 0 && value !== 0) ? mapped : void 0;
40679
+ }
40680
+ // src/tools/party/import-party-from-text.ts
40681
+ const TOOL_NAME = "import_party_from_text";
40682
+ const TOOL_DESCRIPTION = "ポケソルテキスト (Showdown 風に 1 匹あたり 3〜6 行・複数匹は空行区切り) からパーティを一括取り込みして保存する (upsert)。各メンバーはポケモン名 / 特性 / 性格 / 技 / 持ち物をポケチャン内の既知データと照合する。エラーがある場合は部分保存せず全体を失敗させる。";
40683
+ /** ポケソルテキスト入力の最大文字数 (6 匹 × 数百文字 + メモ想定)。 */
40684
+ const MAX_POKESOL_TEXT_LENGTH = 8e3;
40685
+ const defaultNowProvider$1 = () => /* @__PURE__ */ new Date();
40686
+ const defaultStoreIO$1 = {
40687
+ load: () => loadPartiesFile(),
40688
+ save: (data) => savePartiesFile(data)
40689
+ };
40690
+ const inputSchema = {
40691
+ text: z.string().min(1, { message: "ポケソルテキストは 1 文字以上で指定してください。" }).max(MAX_POKESOL_TEXT_LENGTH, { message: `ポケソルテキストは ${MAX_POKESOL_TEXT_LENGTH} 文字以下で指定してください。` }).describe("ポケソルテキスト。1 匹あたり 3〜6 行 (ポケモン名[@持ち物] / テラスタイプ行 省略可 / 特性 / 能力補正 / 実数値(SP) 省略可 / 技 省略可)。複数匹は空行で区切る。"),
40692
+ name: z.string().min(1, { message: "パーティ名は 1 文字以上で指定してください。" }).max(50, { message: `パーティ名は 50 文字以下で指定してください。` }).describe("保存名 (識別子。同名は上書き)。"),
40693
+ memo: z.string().max(MAX_PARTY_MEMO_LENGTH, { message: `メモは ${MAX_PARTY_MEMO_LENGTH} 文字以下で指定してください。` }).optional().describe("構築メモ (自由記述)。")
40694
+ };
40695
+ /**
40696
+ * NameResolver の既知名 (日英どちらでも) として存在するかを判定する。
40697
+ * 未知の場合は類似候補付きのメッセージを投げる。
40698
+ */
40699
+ function assertKnownName(resolver, name, label, blockNumber) {
40700
+ if (resolver.hasJapaneseName(name) || resolver.hasEnglishName(name)) return;
40701
+ const suggestions = resolver.suggestSimilar(name, 3);
40702
+ throw new UserFacingError(`ブロック ${blockNumber}: ${label}「${name}」が見つかりません。${suggestions.length > 0 ? ` もしかして: ${suggestions.join(", ")}` : ""}`);
40703
+ }
40704
+ /**
40705
+ * PartyMember の各名前フィールドを NameResolver で検証する。
40706
+ * 未知名があれば該当ブロックのエラーとして throw。
40707
+ */
40708
+ function validateMemberNames(member, blockNumber) {
40709
+ assertKnownName(pokemonNameResolver, member.name, "ポケモン名", blockNumber);
40710
+ if (member.nature !== void 0) assertKnownName(natureNameResolver, member.nature, "性格", blockNumber);
40711
+ if (member.ability !== void 0) assertKnownName(abilityNameResolver, member.ability, "特性", blockNumber);
40712
+ if (member.item !== void 0) assertKnownName(itemNameResolver, member.item, "持ち物", blockNumber);
40713
+ if (member.moves !== void 0) for (const move of member.moves) assertKnownName(moveNameResolver, move, "技", blockNumber);
40714
+ }
40715
+ /**
40716
+ * 本ツールの全処理 (split → parse → map → validate → persist) を実行する。
40717
+ * テストから直接呼び出せるようエクスポートする。
40718
+ */
40719
+ function runImportPartyFromText(input, deps = {}) {
40720
+ const storeIO = deps.storeIO ?? defaultStoreIO$1;
40721
+ const now = deps.now ?? defaultNowProvider$1;
40722
+ const blocks = splitPokesolTextBlocks(input.text);
40723
+ if (blocks.length < 1) throw new UserFacingError(`パーティには 1 匹以上を含めてください (検出: ${blocks.length} 匹)。`);
40724
+ if (blocks.length > 6) throw new UserFacingError(`パーティには 6 匹までしか含められません (検出: ${blocks.length} 匹)。`);
40725
+ const warnings = [];
40726
+ const members = [];
40727
+ blocks.forEach((block, index) => {
40728
+ const blockNumber = index + 1;
40729
+ let parsed;
40730
+ try {
40731
+ parsed = parse(block);
40732
+ } catch (error) {
40733
+ throw new UserFacingError(`ブロック ${blockNumber} のパースに失敗しました: ${error instanceof Error ? error.message : String(error)}`);
40734
+ }
40735
+ const mapped = mapPokesolResultToPartyMember(parsed, blockNumber);
40736
+ validateMemberNames(mapped.member, blockNumber);
40737
+ members.push(mapped.member);
40738
+ warnings.push(...mapped.warnings);
40739
+ });
40740
+ const file = storeIO.load();
40741
+ const existingIndex = file.parties.findIndex((p) => p.name === input.name);
40742
+ const nowIso = now().toISOString();
40743
+ const createdAt = existingIndex >= 0 ? file.parties[existingIndex].createdAt : nowIso;
40744
+ const party = {
40745
+ name: input.name,
40746
+ members,
40747
+ createdAt,
40748
+ updatedAt: nowIso
40749
+ };
40750
+ if (input.memo !== void 0) party.memo = input.memo;
40751
+ const validation = partySchema.safeParse(party);
40752
+ if (!validation.success) throw new UserFacingError(validation.error.message);
40753
+ const nextParties = [...file.parties];
40754
+ if (existingIndex >= 0) nextParties[existingIndex] = party;
40755
+ else nextParties.push(party);
40756
+ storeIO.save({
40757
+ schemaVersion: 1,
40758
+ parties: nextParties
40759
+ });
40760
+ return {
40761
+ saved: true,
40762
+ party,
40763
+ warnings,
40764
+ filePath: resolvePartiesFilePath(),
40765
+ overwrote: existingIndex >= 0
40766
+ };
40767
+ }
40768
+ /**
40769
+ * import_party_from_text ツールをサーバーに登録する。
40770
+ */
40771
+ function registerImportPartyFromTextTool(server, deps = {}) {
40772
+ server.tool(TOOL_NAME, TOOL_DESCRIPTION, inputSchema, async (args) => {
40773
+ try {
40774
+ return toTextResponse(runImportPartyFromText(args, deps));
40775
+ } catch (error) {
40776
+ return toErrorResponse(error);
40777
+ }
40778
+ });
40779
+ }
40780
+ // src/tools/party/party-tools.ts
40781
+ const SAVE_TOOL_NAME = "save_party";
40782
+ const SAVE_TOOL_DESCRIPTION = "パーティを保存する (upsert)。同名のパーティが既に存在する場合は上書きされる。createdAt は新規時のみ現在時刻が記録され、同名上書きの場合は保持される。updatedAt は毎回現在時刻に更新される。";
40783
+ const LOAD_TOOL_NAME = "load_party";
40784
+ const LOAD_TOOL_DESCRIPTION = "保存済みパーティを name 指定で 1 件取得する。存在しない場合はエラーを返す。";
40785
+ const LIST_TOOL_NAME = "list_parties";
40786
+ const LIST_TOOL_DESCRIPTION = "保存済みパーティの一覧 (サマリ) を返す。各要素は { name, memo, updatedAt, memberCount } のみで、メンバー詳細は含まない。詳細は load_party を使用する。";
40787
+ const DELETE_TOOL_NAME = "delete_party";
40788
+ const DELETE_TOOL_DESCRIPTION = "保存済みパーティを name 指定で削除する。存在しない場合はエラーを返す。";
40789
+ const defaultNowProvider = () => /* @__PURE__ */ new Date();
40790
+ const defaultStoreIO = {
40791
+ load: () => loadPartiesFile(),
40792
+ save: (data) => savePartiesFile(data)
40793
+ };
40794
+ const nameField = z.string().min(1, { message: "名前は 1 文字以上で指定してください。" }).max(100, { message: `名前は 100 文字以下で指定してください。` });
40795
+ const partyMemberInputSchema = z.object({
40796
+ name: nameField.describe("ポケモン名 (日本語 or 英語)。"),
40797
+ nature: nameField.optional().describe("性格名 (日本語 or 英語)。"),
40798
+ ability: nameField.optional().describe("特性名 (日本語 or 英語)。"),
40799
+ item: nameField.optional().describe("持ち物名 (日本語 or 英語)。"),
40800
+ evs: evsSchema.optional().describe("能力ポイント (SP) 配分。"),
40801
+ moves: z.array(nameField).max(4, { message: `技は 4 個までです。` }).optional().describe("技リスト (最大 4)。")
40802
+ }).describe("パーティメンバー 1 匹分のビルド情報。");
40803
+ const partyNameField = z.string().min(1, { message: "パーティ名は 1 文字以上で指定してください。" }).max(50, { message: `パーティ名は 50 文字以下で指定してください。` });
40804
+ const saveInputSchema = {
40805
+ name: partyNameField.describe("パーティの識別子 (同名は上書き)。"),
40806
+ memo: z.string().max(MAX_PARTY_MEMO_LENGTH, { message: `メモは ${MAX_PARTY_MEMO_LENGTH} 文字以下で指定してください。` }).optional().describe("自由記述メモ。"),
40807
+ members: z.array(partyMemberInputSchema).min(1, { message: `パーティには 1 匹以上を含めてください。` }).max(6, { message: `パーティには 6 匹までしか含められません。` }).describe("1〜6 匹のメンバー。")
40808
+ };
40809
+ const loadInputSchema = { name: partyNameField.describe("取得するパーティ名。") };
40810
+ const deleteInputSchema = { name: partyNameField.describe("削除するパーティ名。") };
40811
+ const listInputSchema = {};
40812
+ function toSummary(party) {
40813
+ const summary = {
40814
+ name: party.name,
40815
+ updatedAt: party.updatedAt,
40816
+ memberCount: party.members.length
40817
+ };
40818
+ if (party.memo !== void 0) summary.memo = party.memo;
40819
+ return summary;
40820
+ }
40821
+ /**
40822
+ * パーティ永続化 4 ツールをサーバーに登録する。
40823
+ * deps は主にテスト用。本番は省略してデフォルト (ファイル I/O + 現在時刻) を使う。
40824
+ */
40825
+ function registerPartyTools(server, deps = {}) {
40826
+ const storeIO = deps.storeIO ?? defaultStoreIO;
40827
+ const now = deps.now ?? defaultNowProvider;
40828
+ server.tool(SAVE_TOOL_NAME, SAVE_TOOL_DESCRIPTION, saveInputSchema, async (args) => {
40829
+ try {
40830
+ const file = storeIO.load();
40831
+ const nowIso = now().toISOString();
40832
+ const existingIndex = file.parties.findIndex((p) => p.name === args.name);
40833
+ const createdAt = existingIndex >= 0 ? file.parties[existingIndex].createdAt : nowIso;
40834
+ const party = {
40835
+ name: args.name,
40836
+ members: args.members,
40837
+ createdAt,
40838
+ updatedAt: nowIso
40839
+ };
40840
+ if (args.memo !== void 0) party.memo = args.memo;
40841
+ if (existingIndex >= 0) file.parties[existingIndex] = party;
40842
+ else file.parties.push(party);
40843
+ storeIO.save({
40844
+ schemaVersion: 1,
40845
+ parties: file.parties
40846
+ });
40847
+ return toTextResponse({
40848
+ saved: true,
40849
+ overwrote: existingIndex >= 0,
40850
+ party,
40851
+ filePath: resolvePartiesFilePath()
40852
+ });
40853
+ } catch (error) {
40854
+ return toErrorResponse(error);
40855
+ }
40856
+ });
40857
+ server.tool(LOAD_TOOL_NAME, LOAD_TOOL_DESCRIPTION, loadInputSchema, async (args) => {
40858
+ try {
40859
+ const party = storeIO.load().parties.find((p) => p.name === args.name);
40860
+ if (party === void 0) throw new UserFacingError(`パーティ「${args.name}」が見つかりません。list_parties で一覧を確認してください。`);
40861
+ return toTextResponse({ party });
40862
+ } catch (error) {
40863
+ return toErrorResponse(error);
40864
+ }
40865
+ });
40866
+ server.tool(LIST_TOOL_NAME, LIST_TOOL_DESCRIPTION, listInputSchema, async () => {
40867
+ try {
40868
+ return toTextResponse({ parties: storeIO.load().parties.map(toSummary) });
40869
+ } catch (error) {
40870
+ return toErrorResponse(error);
40871
+ }
40872
+ });
40873
+ server.tool(DELETE_TOOL_NAME, DELETE_TOOL_DESCRIPTION, deleteInputSchema, async (args) => {
40874
+ try {
40875
+ const file = storeIO.load();
40876
+ const nextParties = file.parties.filter((p) => p.name !== args.name);
40877
+ if (nextParties.length === file.parties.length) throw new UserFacingError(`パーティ「${args.name}」が見つかりません。`);
40878
+ storeIO.save({
40879
+ schemaVersion: 1,
40880
+ parties: nextParties
40881
+ });
40882
+ return toTextResponse({
40883
+ deleted: true,
40884
+ name: args.name
40885
+ });
40886
+ } catch (error) {
40887
+ return toErrorResponse(error);
40888
+ }
40889
+ });
40890
+ }
40891
+ // src/server.ts
40892
+ function createServer() {
40893
+ const server = createCoreServer(SERVER_INSTRUCTIONS);
40894
+ registerImportPartyFromTextTool(server);
40895
+ registerPartyTools(server);
40896
+ return server;
40897
+ }
41169
40898
  async function startServer() {
41170
40899
  const server = createServer();
41171
40900
  const transport = new StdioServerTransport();