import z from "schemastery";
import { BlockAssembler, ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
/** Build a mulberry32 PRNG from a seed. */
function mulberry32(seed) {
	let a = seed >>> 0;
	return () => {
		a = a + 1831565813 >>> 0;
		let t = a;
		t = Math.imul(t ^ t >>> 15, t | 1);
		t ^= t + Math.imul(t ^ t >>> 7, t | 61);
		return ((t ^ t >>> 14) >>> 0) / 4294967296;
	};
}
/** Human-readable trait name. */
function traitName(id) {
	return TRAITS.find((trait) => trait.id === id)?.name ?? id;
}
/** The 24-unit public pool (ids 1..24, costs 1/2/3). */
const UNIT_POOL = [
	{
		id: 1,
		name: "冰女",
		cost: 1,
		race: "frost",
		class: "mage",
		hp: 500,
		atk: 42,
		atkSpeed: .75,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.5
		}
	},
	{
		id: 2,
		name: "小鹿",
		cost: 1,
		race: "barbarian",
		class: "marksman",
		hp: 460,
		atk: 40,
		atkSpeed: .85,
		range: 4,
		skill: {
			kind: "damage",
			every: 5,
			power: 1.3
		}
	},
	{
		id: 3,
		name: "石像鬼",
		cost: 1,
		race: "stellar",
		class: "guardian",
		hp: 620,
		atk: 30,
		atkSpeed: .6,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.2,
			aoe: true
		}
	},
	{
		id: 4,
		name: "火鸡",
		cost: 1,
		race: "barbarian",
		class: "blade",
		hp: 480,
		atk: 44,
		atkSpeed: .8,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.5
		}
	},
	{
		id: 5,
		name: "幽魂",
		cost: 1,
		race: "shadow",
		class: "assassin",
		hp: 450,
		atk: 46,
		atkSpeed: .9,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.6
		}
	},
	{
		id: 6,
		name: "小精灵",
		cost: 1,
		race: "stellar",
		class: "mage",
		hp: 420,
		atk: 44,
		atkSpeed: .7,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.5
		}
	},
	{
		id: 7,
		name: "老铁匠",
		cost: 1,
		race: "barbarian",
		class: "guardian",
		hp: 640,
		atk: 32,
		atkSpeed: .6,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.4
		}
	},
	{
		id: 8,
		name: "白鸽",
		cost: 1,
		race: "frost",
		class: "priest",
		hp: 480,
		atk: 36,
		atkSpeed: .7,
		range: 1.5,
		skill: {
			kind: "heal-all",
			every: 4,
			power: 1.5
		}
	},
	{
		id: 9,
		name: "暗影鼠",
		cost: 1,
		race: "shadow",
		class: "assassin",
		hp: 440,
		atk: 45,
		atkSpeed: .85,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.5
		}
	},
	{
		id: 10,
		name: "见习剑士",
		cost: 1,
		race: "warmonger",
		class: "blade",
		hp: 500,
		atk: 42,
		atkSpeed: .75,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.5
		}
	},
	{
		id: 11,
		name: "剑圣",
		cost: 2,
		race: "warmonger",
		class: "blade",
		hp: 620,
		atk: 62,
		atkSpeed: .85,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 2
		}
	},
	{
		id: 12,
		name: "冰霜守卫",
		cost: 2,
		race: "frost",
		class: "guardian",
		hp: 760,
		atk: 40,
		atkSpeed: .6,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.6
		}
	},
	{
		id: 13,
		name: "暗影法师",
		cost: 2,
		race: "shadow",
		class: "mage",
		hp: 560,
		atk: 58,
		atkSpeed: .7,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 2
		}
	},
	{
		id: 14,
		name: "星灵射手",
		cost: 2,
		race: "stellar",
		class: "marksman",
		hp: 560,
		atk: 56,
		atkSpeed: .9,
		range: 4,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.8
		}
	},
	{
		id: 15,
		name: "蛮族勇士",
		cost: 2,
		race: "barbarian",
		class: "blade",
		hp: 700,
		atk: 55,
		atkSpeed: .7,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 2
		}
	},
	{
		id: 16,
		name: "神官",
		cost: 2,
		race: "frost",
		class: "priest",
		hp: 580,
		atk: 44,
		atkSpeed: .65,
		range: 1.5,
		skill: {
			kind: "heal-all",
			every: 3,
			power: 1
		}
	},
	{
		id: 17,
		name: "猎手",
		cost: 2,
		race: "warmonger",
		class: "marksman",
		hp: 540,
		atk: 58,
		atkSpeed: .95,
		range: 4,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.9
		}
	},
	{
		id: 18,
		name: "影武者",
		cost: 2,
		race: "shadow",
		class: "assassin",
		hp: 560,
		atk: 60,
		atkSpeed: 1,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 2.1
		}
	},
	{
		id: 19,
		name: "冰霜巨龙",
		cost: 3,
		race: "frost",
		class: "mage",
		hp: 800,
		atk: 70,
		atkSpeed: .7,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 2.2,
			aoe: true
		}
	},
	{
		id: 20,
		name: "战神之王",
		cost: 3,
		race: "warmonger",
		class: "blade",
		hp: 900,
		atk: 80,
		atkSpeed: .75,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 2.4
		}
	},
	{
		id: 21,
		name: "暗影领主",
		cost: 3,
		race: "shadow",
		class: "mage",
		hp: 760,
		atk: 78,
		atkSpeed: .7,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 2.5
		}
	},
	{
		id: 22,
		name: "星灵女王",
		cost: 3,
		race: "stellar",
		class: "marksman",
		hp: 700,
		atk: 74,
		atkSpeed: 1,
		range: 4,
		skill: {
			kind: "damage",
			every: 4,
			power: 1.8
		}
	},
	{
		id: 23,
		name: "蛮族之王",
		cost: 3,
		race: "barbarian",
		class: "guardian",
		hp: 1100,
		atk: 60,
		atkSpeed: .55,
		range: 1.5,
		skill: {
			kind: "damage",
			every: 4,
			power: 2
		}
	},
	{
		id: 24,
		name: "大主教",
		cost: 3,
		race: "stellar",
		class: "priest",
		hp: 780,
		atk: 52,
		atkSpeed: .6,
		range: 1.5,
		skill: {
			kind: "heal-all",
			every: 3,
			power: 1.3
		}
	}
];
/** All trait definitions (races first, then classes, in display order). */
const TRAITS = [
	{
		id: "frost",
		kind: "race",
		name: "冰裔",
		tiers: [{
			threshold: 2,
			desc: "冰裔生命上限+15%",
			effect: {
				hpPct: .15,
				scope: "self"
			}
		}, {
			threshold: 4,
			desc: "冰裔生命上限+35%",
			effect: {
				hpPct: .35,
				scope: "self"
			}
		}]
	},
	{
		id: "shadow",
		kind: "race",
		name: "暗影",
		tiers: [{
			threshold: 2,
			desc: "暗影攻击力+20%",
			effect: {
				atkPct: .2,
				scope: "self"
			}
		}, {
			threshold: 4,
			desc: "暗影攻击力+45%",
			effect: {
				atkPct: .45,
				scope: "self"
			}
		}]
	},
	{
		id: "warmonger",
		kind: "race",
		name: "战神",
		tiers: [{
			threshold: 2,
			desc: "战神攻速+15%",
			effect: {
				atkSpeedPct: .15,
				scope: "self"
			}
		}, {
			threshold: 4,
			desc: "战神攻速+35%",
			effect: {
				atkSpeedPct: .35,
				scope: "self"
			}
		}]
	},
	{
		id: "stellar",
		kind: "race",
		name: "星灵",
		tiers: [{
			threshold: 2,
			desc: "星灵技能伤害+25%",
			effect: {
				skillPct: .25,
				scope: "self"
			}
		}, {
			threshold: 3,
			desc: "星灵技能伤害+50%",
			effect: {
				skillPct: .5,
				scope: "self"
			}
		}]
	},
	{
		id: "barbarian",
		kind: "race",
		name: "蛮族",
		tiers: [{
			threshold: 2,
			desc: "蛮族生命上限+20%、攻击力+10%",
			effect: {
				hpPct: .2,
				atkPct: .1,
				scope: "self"
			}
		}, {
			threshold: 4,
			desc: "蛮族生命上限+40%、攻击力+25%",
			effect: {
				hpPct: .4,
				atkPct: .25,
				scope: "self"
			}
		}]
	},
	{
		id: "mage",
		kind: "class",
		name: "法师",
		tiers: [{
			threshold: 2,
			desc: "法师技能伤害+25%",
			effect: {
				skillPct: .25,
				scope: "self"
			}
		}, {
			threshold: 4,
			desc: "法师技能伤害+60%",
			effect: {
				skillPct: .6,
				scope: "self"
			}
		}]
	},
	{
		id: "blade",
		kind: "class",
		name: "剑士",
		tiers: [{
			threshold: 2,
			desc: "剑士攻击力+25%",
			effect: {
				atkPct: .25,
				scope: "self"
			}
		}, {
			threshold: 4,
			desc: "剑士攻击力+50%",
			effect: {
				atkPct: .5,
				scope: "self"
			}
		}]
	},
	{
		id: "marksman",
		kind: "class",
		name: "射手",
		tiers: [{
			threshold: 2,
			desc: "射手攻速+20%",
			effect: {
				atkSpeedPct: .2,
				scope: "self"
			}
		}, {
			threshold: 4,
			desc: "射手攻速+45%",
			effect: {
				atkSpeedPct: .45,
				scope: "self"
			}
		}]
	},
	{
		id: "guardian",
		kind: "class",
		name: "守卫",
		tiers: [{
			threshold: 2,
			desc: "守卫生命上限+200",
			effect: {
				hpFlat: 200,
				scope: "self"
			}
		}, {
			threshold: 4,
			desc: "守卫生命上限+500",
			effect: {
				hpFlat: 500,
				scope: "self"
			}
		}]
	},
	{
		id: "assassin",
		kind: "class",
		name: "刺客",
		tiers: [{
			threshold: 2,
			desc: "刺客暴击率+30%",
			effect: {
				critPct: .3,
				scope: "self"
			}
		}, {
			threshold: 4,
			desc: "刺客暴击率+60%",
			effect: {
				critPct: .6,
				scope: "self"
			}
		}]
	},
	{
		id: "priest",
		kind: "class",
		name: "牧师",
		tiers: [{
			threshold: 2,
			desc: "全体友方生命上限+10%",
			effect: {
				hpPct: .1,
				scope: "all"
			}
		}, {
			threshold: 3,
			desc: "全体友方生命上限+20%",
			effect: {
				hpPct: .2,
				scope: "all"
			}
		}]
	}
];
/** Shop cost odds per level: [1费, 2费, 3费]. */
const SHOP_ODDS = [
	[
		1,
		0,
		0
	],
	[
		.7,
		.3,
		0
	],
	[
		.5,
		.4,
		.1
	],
	[
		.35,
		.45,
		.2
	],
	[
		.25,
		.45,
		.3
	],
	[
		.15,
		.45,
		.4
	],
	[
		.1,
		.4,
		.5
	],
	[
		.05,
		.35,
		.6
	]
];
/** Experience needed to advance from `level` to `level + 1`. */
function expNeeded(level) {
	return level + 2;
}
/** Look a unit definition up by pool id. */
function unitDef(defId) {
	return UNIT_POOL.find((def) => def.id === defId);
}
/** Star stat scale (2★ ≈ 1.8×, 3★ ≈ 3.24× of the 1★ base). */
function starScale(star) {
	return star === 1 ? 1 : star === 2 ? 1.8 : 3.24;
}
/** Build a concrete unit instance from a pool definition. */
function makeUnit(def, star, id) {
	const scale = starScale(star);
	const hp = Math.round(def.hp * scale);
	return {
		id,
		defId: def.id,
		name: def.name,
		cost: def.cost,
		star,
		race: def.race,
		class: def.class,
		hp,
		maxHp: hp,
		atk: Math.round(def.atk * scale),
		atkSpeed: def.atkSpeed,
		range: def.range,
		skill: { ...def.skill }
	};
}
/** Roll one shop of SHOP_SIZE distinct units for a level. */
function rollShop(level, rng) {
	const odds = SHOP_ODDS[Math.max(1, Math.min(level, 8)) - 1];
	const pick = () => {
		const roll = rng();
		let acc = 0;
		let cost = 1;
		for (let i = 0; i < odds.length; i += 1) {
			acc += odds[i];
			if (roll < acc) {
				cost = i + 1;
				break;
			}
		}
		const candidates = UNIT_POOL.filter((def) => def.cost === cost);
		return candidates[Math.floor(rng() * candidates.length)];
	};
	const shop = [];
	let guard = 0;
	while (shop.length < 5 && guard < 200) {
		guard += 1;
		const entry = pick();
		if (shop.some((existing) => existing.defId === entry.id)) continue;
		shop.push({
			defId: entry.id,
			name: entry.name,
			cost: entry.cost,
			race: entry.race,
			class: entry.class
		});
	}
	return shop;
}
/** Deep-clone a game state (the wire shape is JSON-safe). */
function cloneGameState(state) {
	return JSON.parse(JSON.stringify(state));
}
/** Number of units currently deployed by a side. */
function boardCount(side) {
	return side.board.filter((unit) => unit !== null).length;
}
/** Whether a cell index is inside the 4×7 board. */
function inBoard(row, col) {
	return row >= 0 && row < 4 && col >= 0 && col < 7;
}
/** Cell index for a [row, col] pair. */
function cellIndex(row, col) {
	return row * 7 + col;
}
/** Per-trait deployed counts of a side. */
function traitCounts(side) {
	const counts = /* @__PURE__ */ new Map();
	for (const unit of side.board) {
		if (unit === null) continue;
		counts.set(unit.race, (counts.get(unit.race) ?? 0) + 1);
		counts.set(unit.class, (counts.get(unit.class) ?? 0) + 1);
	}
	return counts;
}
/** The traits of a side whose threshold is met, with the met tier. */
function activeTraits(side) {
	const counts = traitCounts(side);
	const active = [];
	for (const trait of TRAITS) {
		const count = counts.get(trait.id) ?? 0;
		let met;
		for (const tier of trait.tiers) if (count >= tier.threshold) met = tier;
		if (met !== void 0) active.push({
			trait,
			tier: met
		});
	}
	return active;
}
/** Rough power estimate of a side's board (cost × star summed). */
function estimatedPower(side) {
	let power = 0;
	for (const unit of side.board) if (unit !== null) power += unit.cost * unit.star;
	return power;
}
/** Locate a unit by id; returns its location. */
function findUnit(side, id) {
	const benchIndex = side.bench.findIndex((unit) => unit.id === id);
	if (benchIndex !== -1) return {
		where: "bench",
		index: benchIndex
	};
	const boardIndex = side.board.findIndex((unit) => unit?.id === id);
	if (boardIndex !== -1) return {
		where: "board",
		index: boardIndex
	};
	return null;
}
/** Merge triples of identical name+star units (bench first, then board in cell order). */
function mergeStars(state, side) {
	for (;;) {
		const counts = /* @__PURE__ */ new Map();
		const collect = (unit) => {
			const key = `${unit.name}|${unit.star}`;
			counts.set(key, (counts.get(key) ?? 0) + 1);
		};
		for (const unit of side.bench) collect(unit);
		for (const unit of side.board) if (unit !== null) collect(unit);
		let targetKey;
		for (const [key, count] of counts) if (count >= 3) {
			targetKey = key;
			break;
		}
		if (targetKey === void 0) return;
		const [name, starText] = targetKey.split("|");
		const star = Number(starText);
		if (star >= 3) return;
		const def = UNIT_POOL.find((candidate) => candidate.name === name);
		if (def === void 0) return;
		let removed = 0;
		let keptId;
		const consume = (unit) => {
			if (unit.name !== name || unit.star !== star) return false;
			keptId = unit.id;
			return true;
		};
		side.bench = side.bench.filter((unit) => {
			if (removed < 3 && consume(unit)) {
				removed += 1;
				return false;
			}
			return true;
		});
		for (let index = 0; index < side.board.length && removed < 3; index += 1) {
			const unit = side.board[index];
			if (unit !== null && consume(unit)) {
				side.board[index] = null;
				removed += 1;
			}
		}
		side.bench.push(makeUnit(def, star + 1, keptId ?? state.nextUnitId));
		if (keptId === void 0) state.nextUnitId += 1;
	}
}
/**
* Apply one prep action to a side, mutating the state. Returns an error
* string when the action is illegal; `undefined` on success. The whole
* action list of an AI decision is validated by applying every action to a
* clone — any failure rejects the batch and triggers corrective feedback.
*/
function applyAction(state, side, action) {
	const player = state.sides[side - 1];
	switch (action.action) {
		case "buy": {
			const entry = player.shop.find((candidate) => candidate.name === action.name);
			if (entry === void 0) return `商店中没有名为「${action.name}」的棋子`;
			if (player.gold < entry.cost) return `金币不足（购买「${entry.name}」需要 ${entry.cost}，当前 ${player.gold}）`;
			if (player.bench.length >= 9) return `备战区已满（上限 9）`;
			const def = unitDef(entry.defId);
			if (def === void 0) return `未知棋子「${entry.name}」`;
			player.gold -= entry.cost;
			player.bench.push(makeUnit(def, 1, state.nextUnitId));
			state.nextUnitId += 1;
			mergeStars(state, player);
			return;
		}
		case "sell": {
			const found = findUnit(player, action.chess_id);
			if (found === null) return `未找到棋子（chess_id: ${action.chess_id}）`;
			const unit = found.where === "bench" ? player.bench[found.index] : player.board[found.index];
			const refund = unit.cost + (unit.star - 1) * 2;
			if (found.where === "bench") player.bench.splice(found.index, 1);
			else player.board[found.index] = null;
			player.gold += refund;
			return;
		}
		case "move": {
			const [row, col] = action.pos;
			if (!Number.isInteger(row) || !Number.isInteger(col) || !inBoard(row, col)) return `目标位置越界：[${row}, ${col}]（范围 0-3 行、0-6 列）`;
			const index = cellIndex(row, col);
			const found = findUnit(player, action.chess_id);
			if (found === null) return `未找到棋子（chess_id: ${action.chess_id}）`;
			const occupant = player.board[index];
			if (occupant !== null) return occupant.id === action.chess_id ? void 0 : `目标位置已被占用：[${row}, ${col}]`;
			const unit = found.where === "bench" ? player.bench[found.index] : player.board[found.index];
			if (found.where === "bench") {
				if (boardCount(player) >= player.level) return `上场棋子数已达上限（当前等级 ${player.level}）`;
				player.bench.splice(found.index, 1);
			} else player.board[found.index] = null;
			player.board[index] = unit;
			return;
		}
		case "upgrade":
			if (player.gold < 4) return `金币不足（购买经验需要 4，当前 ${player.gold}）`;
			player.gold -= 4;
			player.exp += 4;
			while (player.level < 8 && player.exp >= expNeeded(player.level)) {
				player.exp -= expNeeded(player.level);
				player.level += 1;
			}
			return;
		case "refresh":
			if (player.gold < 2) return `金币不足（刷新商店需要 2，当前 ${player.gold}）`;
			player.gold -= 2;
			player.shop = rollShop(player.level, mulberry32(state.seed ^ player.side));
			return;
		case "end_prep": return;
		/* v8 ignore next -- closed-union exhaustiveness guard */
		default: return "未知操作";
	}
}
//#endregion
//#region src/game/prompt.ts
/**
* Prompt framing for AI prep decisions: the default system prompt (rules,
* strict return format, worked examples) and the user-message assembler
* that renders one side's game state into the structured state text the
* model decides from. Shared by the node half (per-request framing) and the
* tests; the browser half only stores the custom prompt text and sends it
* back verbatim.
* @module dsh-auto-chess/game/prompt
*/
/**
* The default system prompt: the full minimal-auto-chess rule surface
* (board, units, star merging, traits with thresholds and effects, shop and
* economy, battle and damage), the strict JSON-array return format, a
* correct worked example, and an explicit wrong example. Users may edit
* this text in the browser half; the edited text replaces it verbatim per
* action request.
*/
const DEFAULT_SYSTEM_PROMPT = [
	"你是《简化自走棋》的一名玩家。请根据给定的局面，为你控制的阵营做出准备阶段的操作决策，并严格按照规定的 JSON 格式返回操作数组。",
	"",
	"# 游戏规则",
	`- 你与对手各控制一个阵营（蓝方/红方），初始生命值 100。每回合分为「准备阶段 → 自动战斗 → 结算」。`,
	`- 战斗自动进行：棋子自动索敌、移动、攻击，每累计一定次数攻击会触发技能。失败方按对方存活棋子数 ×2 扣除生命值，生命归零即输。`,
	`- 每个回合你最多可以执行 4 个操作（买棋、卖棋、布阵、购买经验、刷新商店、结束准备）。`,
	"",
	"# 棋盘",
	`- 你的布阵区域是 4 行 × 7 列，坐标写作 [row, col]（row 为 0-3，col 为 0-6）。`,
	`- 上场棋子数不能超过你的等级；备战区（未上场的棋子）上限 9 个。`,
	"",
	"# 棋子",
	"- 棋子分为 1 费、2 费、3 费。每颗棋子有生命（hp）、攻击力（atk）、攻速（每秒攻击次数）、攻击距离、种族、职业与技能。",
	"- 星阶：3 个同名同星棋子自动合成为 1 个更高星棋子（一星→二星→三星）。二星属性约为一星的 1.8 倍，三星约为 3.24 倍。",
	"- 合成会统计备战区与棋盘上所有的同名同星棋子，所以棋子上场不会影响后续合成。",
	"- 技能：每个棋子每累计 N 次攻击都会触发一次技能（造成技能伤害或治疗友方）。",
	"- 棋子 id：以局面文本中最新给出的 id 为准。购买触发合成后，被合成的旧棋子会消失，合成后的棋子保留「最后被消耗那颗」的 id（通常就是你刚买入的那颗）；因此批量操作中，先买后布阵时请使用刚买入棋子的 id，不要使用已被合成消耗的旧 id。",
	"",
	"# 种族与职业（羁绊）",
	"上场棋子的同种族/同职业数量达到阈值时触发加成，只计算已上场棋子，取满足的最高档：",
	...TRAITS.flatMap((trait) => [`- ${trait.name}（${trait.kind === "race" ? "种族" : "职业"}）${trait.tiers.map((tier) => `${tier.threshold}：${tier.desc}`).join("，")}`]),
	"",
	"# 商店与经济",
	`- 商店每回合免费刷新 5 颗棋子；主动刷新花费 2 金币。购买花费棋子费用（1/2/3 金币）。`,
	"- 卖出返还金币：费用 + (星阶-1) × 2（一星卖 1/2/3 金，二星多返 2 金，三星多返 4 金）。",
	`- 每回合结算收入 = 基础 5 + 利息 min(金币÷10, 5) + 连胜/连败奖励 + 胜利 +1。`,
	"- 连胜/连败奖励：2 连胜起 +1，4 连胜起 +2，6 连胜起 +3（连胜与连败都算）。",
	`- 升级：花费 4 金币购买 4 点经验。升级所需经验 = 等级 + 2（例如 4 级升 5 级需要 6 点）。等级提高上场人数上限与高费棋子的刷新概率，等级上限 8。`,
	"",
	"# 操作格式（必须严格遵守）",
	`只返回一个 JSON 数组（最多 4 个操作），按顺序执行；不要输出任何思考过程、解释、Markdown 代码块或前后缀（思考会占用输出预算，导致回复被截断）：`,
	"- 购买商店棋子：{\"action\":\"buy\", \"name\":\"棋子名\"}",
	"- 卖出：{\"action\":\"sell\", \"chess_id\":棋子id}",
	"- 布阵/移动：{\"action\":\"move\", \"chess_id\":棋子id, \"pos\":[row, col]}",
	"- 购买经验：{\"action\":\"upgrade\"}",
	"- 刷新商店：{\"action\":\"refresh\"}",
	"- 结束准备：{\"action\":\"end_prep\"}（建议放在最后一个操作）",
	"- 若不想执行任何操作，直接返回 [{\"action\":\"end_prep\"}]",
	"",
	"# 正确案例",
	"局面：你金币 12，等级 4，备战区已有 2 个「冰女」，商店里有「冰女」和「剑圣」，你想合成二星冰女并把它放到棋盘 (1,3)。",
	"返回：[{\"action\":\"buy\",\"name\":\"冰女\"},{\"action\":\"move\",\"chess_id\":6,\"pos\":[1,3]},{\"action\":\"end_prep\"}]",
	"（共 3 个操作，总花费 1 金币，符合数量与预算限制）",
	"",
	"# 错误示范（禁止返回）",
	"\"我觉得应该买剑圣。[{\"action\":\"buy\",\"name\":\"剑圣\"}]\" —— 带解释的文字不是合法输出；",
	"{\"action\":\"buy\",\"name\":\"剑圣\"} —— 必须是数组，不能是单个对象；",
	`操作数超过 4 个时，只执行前 4 个（多余的会被忽略）；总花费超过金币、买入商店里没有的棋子、把棋子移动到已占用的格子等，会导致整批操作被拒绝，你会收到纠正提示并重新决策。`,
	"",
	"# 基本策略",
	"1. 只要还有上场名额（已上场数 < 等级）且备战区有棋子，就必须用 move 把棋子上场：上场不会影响星阶合成（合成统计备战区与棋盘上的同名同星棋子），还能腾出备战区空位；空位优先放能触发羁绊或高星的棋子。",
	"2. 优先凑同种族/同职业羁绊（例如 2 冰裔、2 法师），并让触发羁绊的棋子上场。",
	"3. 购买同名同星棋子合成高星；2 费、3 费核心棋子值得重点培养。",
	"4. 守卫/坦克放前排（靠敌方一侧，col 4-6），射手/法师/刺客等输出放后排（col 0-2）。",
	"5. 金币低于 10 时慎重刷新商店（每 10 金币可多拿 1 利息，上限 5）。",
	"6. 有足够金币时优先购买经验升级，扩大上场人数。",
	"7. 凑不齐羁绊的废棋可以卖掉换经济（卖出会返还金币）。"
].join("\n");
/** The deployed-unit scout line: count, star breakdown, trait counts, power estimate. */
function enemyScoutText(enemy) {
	const units = enemy.board.filter((unit) => unit !== null);
	const count = units.length;
	if (count === 0) return "对手未上场任何棋子。";
	const star2 = units.filter((unit) => unit.star === 2).length;
	const star3 = units.filter((unit) => unit.star === 3).length;
	const breakdown = [];
	if (star2 > 0) breakdown.push(`${star2}个二星`);
	if (star3 > 0) breakdown.push(`${star3}个三星`);
	const parts = [];
	const counts = traitCounts(enemy);
	for (const trait of TRAITS) {
		const value = counts.get(trait.id) ?? 0;
		if (value > 0) parts.push(`${value}个「${trait.name}」${trait.kind === "race" ? "种族" : "职业"}`);
	}
	const hits = activeTraits(enemy).map((entry) => `${entry.tier.threshold}${entry.trait.name}`);
	const hint = hits.length > 0 ? `可能凑成了${hits.join("、")}羁绊` : "尚未触发羁绊";
	return `对手上场${count}个棋子${breakdown.length > 0 ? `（其中${breakdown.join("、")}）` : ""}，包含${parts.join("、")}，${hint}。预估战力约 ${estimatedPower(enemy)}。`;
}
/** The last-battle result line for one side. */
function lastResultText(state, side) {
	const player = state.sides[side - 1];
	const enemy = state.sides[side === 1 ? 1 : 0];
	if (player.lastResult === null) return "暂无（第一回合）。";
	if (player.lastResult === "win") return `你赢了，剩余${player.lastSurvivors}个棋子存活。`;
	if (player.lastResult === "loss") return `你输了，对方剩余${enemy.lastSurvivors}个棋子存活。`;
	return "平局。";
}
/** The trait line for the acting side (counts plus triggered thresholds). */
function traitLine(side) {
	const counts = traitCounts(side);
	const active = activeTraits(side);
	const parts = [];
	for (const trait of TRAITS) {
		const count = counts.get(trait.id) ?? 0;
		if (count === 0) continue;
		const met = active.find((entry) => entry.trait.id === trait.id);
		parts.push(met !== void 0 ? `${trait.name}×${count}（已触发${met.tier.threshold}${trait.name}：${met.tier.desc}）` : `${trait.name}×${count}（未触发）`);
	}
	return parts.length > 0 ? parts.join("、") : "无";
}
/**
* Frame the user message for one AI prep decision: the acting side's full
* state in the structured text format the default prompt describes, plus
* (on a retry) the previous illegal reply and the rejection reason.
*/
function buildActionUserMessage(state, side, previous, reason) {
	const player = state.sides[side - 1];
	const enemy = state.sides[side === 1 ? 1 : 0];
	const bench = player.bench.map((unit) => ({
		id: unit.id,
		name: unit.name,
		cost: unit.cost,
		star: unit.star,
		hp: unit.hp,
		atk: unit.atk,
		race: traitName(unit.race),
		class: traitName(unit.class)
	}));
	const board = [];
	for (let index = 0; index < player.board.length; index += 1) {
		const unit = player.board[index];
		if (unit === null) continue;
		board.push({
			pos: [Math.floor(index / 7), index % 7],
			id: unit.id,
			name: unit.name,
			star: unit.star
		});
	}
	const shop = player.shop.map((entry) => ({
		name: entry.name,
		cost: entry.cost,
		race: traitName(entry.race),
		class: traitName(entry.class)
	}));
	const lines = [
		`你正在玩一场简化自走棋。当前是你的准备阶段（第${state.round}回合）。`,
		`你的生命值: ${player.hp}，对手生命值: ${enemy.hp}。`,
		`你的金币: ${player.gold}，升级所需经验: ${player.exp}/${expNeeded(player.level)}（当前等级${player.level}）。`,
		`你的上场名额: 已上场 ${boardCount(player)} 个 / 上限 ${player.level}（还可上场 ${Math.max(0, player.level - boardCount(player))} 个），备战区有 ${player.bench.length} 个棋子未上场。`,
		`你的当前羁绊: ${traitLine(player)}。`,
		`你的备战区棋子: ${JSON.stringify(bench)}`,
		`棋盘上已布阵: ${JSON.stringify(board)}`,
		`商店刷出棋子: ${JSON.stringify(shop)}`,
		`上一轮战斗结果: ${lastResultText(state, side)}`,
		`对手已知阵容: ${enemyScoutText(enemy)}`
	];
	if (previous !== void 0 && reason !== void 0) {
		lines.push("", `警告：你上一次的返回不合法（${reason}），完整输出如下：`, previous);
		lines.push("你的上一次操作已被拒绝，局面没有任何变化。请重新观察局面，只返回合法的 JSON 操作数组，不要输出任何思考过程或解释。");
		lines.push("注意：棋子 id 请以局面文本中「你的备战区棋子」「棋盘上已布阵」的 JSON 为准；购买触发合成后旧 id 会消失，请使用最新给出的 id。");
	}
	lines.push("", "请决定你要执行的操作，返回JSON数组，可能的操作包括：", "- {\"action\":\"buy\", \"name\":\"剑圣\"}", "- {\"action\":\"sell\", \"chess_id\":6}", "- {\"action\":\"move\", \"chess_id\":6, \"pos\":[1,4]}", "- {\"action\":\"upgrade\"} (购买经验)", "- {\"action\":\"refresh\"} (刷新商店，花费2金币)", "- {\"action\":\"end_prep\"} (结束准备)", "", `你最多可以执行4个操作，但总花费不能超过金币。请保证操作合法。`, "若还有上场名额且备战区有棋子，请务必用 move 把棋子上场（备战区棋子不上场就不参与战斗）。");
	return lines.join("\n");
}
//#endregion
//#region src/index.ts
/** Cordis plugin name (diagnostics only). */
const name = "auto-chess";
/** Services required before the board routes can mount. */
const inject = ["webServer", "llm"];
/** Loader schema with deployment defaults (no library defaults). */
const Config = z.object({
	actionTimeoutMs: z.number().step(1).min(1e3).default(3e5),
	maxActionOutputTokens: z.number().step(1).min(8).default(32e3),
	maxActionAttempts: z.number().step(1).min(1).max(3).default(3)
});
/** Route prefix owned by this plugin (the browser half calls under it). */
const AUTO_CHESS_PATH = "/plugins/auto-chess";
/** Stable plugin identity stamped into auxiliary LLM request sources. */
const PLUGIN_ID = "dsh-auto-chess";
/** Tolerant extraction of the JSON array region from a model reply (first `[` … last `]`). */
function jsonArrayRegion(text) {
	const start = text.indexOf("[");
	const end = text.lastIndexOf("]");
	if (start === -1 || end <= start) return void 0;
	return text.slice(start, end + 1);
}
/** Narrow an unknown parsed element to a ChessAction, returning a reason string on failure. */
function parseActionElement(value) {
	if (value === null || typeof value !== "object" || Array.isArray(value)) return { error: "操作必须是 JSON 对象" };
	const candidate = value;
	switch (candidate.action) {
		case "buy":
			if (typeof candidate.name !== "string" || candidate.name.length === 0) return { error: "buy 需要非空 name" };
			return { action: {
				action: "buy",
				name: candidate.name
			} };
		case "sell": {
			const id = candidate.chess_id;
			if (typeof id !== "number" || !Number.isInteger(id)) return { error: "sell 需要整数 chess_id" };
			return { action: {
				action: "sell",
				chess_id: id
			} };
		}
		case "move": {
			const id = candidate.chess_id;
			const pos = candidate.pos;
			if (typeof id !== "number" || !Number.isInteger(id)) return { error: "move 需要整数 chess_id" };
			if (!Array.isArray(pos) || pos.length !== 2 || !Number.isInteger(pos[0]) || !Number.isInteger(pos[1]) || typeof pos[0] !== "number" || typeof pos[1] !== "number") return { error: "move 的 pos 必须是 [row, col] 整数坐标" };
			return { action: {
				action: "move",
				chess_id: id,
				pos: [pos[0], pos[1]]
			} };
		}
		case "upgrade": return { action: { action: "upgrade" } };
		case "refresh": return { action: { action: "refresh" } };
		case "end_prep": return { action: { action: "end_prep" } };
		default: return { error: `未知操作类型「${String(candidate.action)}」` };
	}
}
/**
* Parse and shape-check one model reply into an {@link ActionReply}. The
* reply may wrap the JSON in prose or a code fence (models do), so the
* array region is extracted before parsing; element shapes and the
* MAX_ACTIONS cap are enforced here, while game legality is checked by
* applying the actions (see the route).
* @param text - the assembled model reply text.
* @returns the parsed reply.
*/
function parseActionReply(text) {
	const region = jsonArrayRegion(text);
	if (region === void 0) return {
		kind: "invalid",
		reason: "回复中没有 JSON 数组"
	};
	let parsed;
	try {
		parsed = JSON.parse(region);
	} catch {
		return {
			kind: "invalid",
			reason: "回复中的 JSON 无法解析"
		};
	}
	if (!Array.isArray(parsed)) return {
		kind: "invalid",
		reason: "回复不是 JSON 数组"
	};
	if (parsed.length === 0) return {
		kind: "invalid",
		reason: "回复是空数组"
	};
	const actions = [];
	for (const element of parsed.slice(0, 4)) {
		const result = parseActionElement(element);
		if ("error" in result) return {
			kind: "invalid",
			reason: result.error
		};
		actions.push(result.action);
	}
	return {
		kind: "actions",
		actions
	};
}
/** Minimal structural validation of a game state (deep legality is the engine's job). */
function isGameState(value) {
	if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
	const candidate = value;
	if (typeof candidate.round !== "number" || typeof candidate.nextUnitId !== "number" || typeof candidate.seed !== "number" || typeof candidate.over !== "boolean") return false;
	const sides = candidate.sides;
	if (!Array.isArray(sides) || sides.length !== 2) return false;
	return sides.every((side) => {
		if (side === null || typeof side !== "object" || Array.isArray(side)) return false;
		const s = side;
		return typeof s.hp === "number" && typeof s.gold === "number" && typeof s.level === "number" && typeof s.exp === "number" && Array.isArray(s.bench) && Array.isArray(s.board) && Array.isArray(s.shop);
	});
}
/**
* Validate an untrusted action-request body into a typed request.
* @param value - the parsed request body.
* @returns the validated request.
* @throws {Error} with a user-readable reason on the first invalid field.
*/
function validateActionRequest(value) {
	if (value === null || typeof value !== "object" || Array.isArray(value)) throw new Error("请求体必须是 JSON 对象");
	const candidate = value;
	if (typeof candidate.provider !== "string" || candidate.provider.length === 0) throw new Error("provider 必须是非空字符串");
	if (typeof candidate.model !== "string" || candidate.model.length === 0) throw new Error("model 必须是非空字符串");
	if (candidate.side !== 1 && candidate.side !== 2) throw new Error("side 必须是 1 或 2");
	if (!isGameState(candidate.state)) throw new Error("state 缺少必要的游戏字段（sides/hp/gold/level/exp/bench/board/shop）");
	if (candidate.thinking !== void 0 && candidate.thinking !== "off" && candidate.thinking !== "high" && candidate.thinking !== "max") throw new Error("thinking 必须是 \"off\"、\"high\" 或 \"max\"");
	if (candidate.actionTimeoutMs !== void 0 && (typeof candidate.actionTimeoutMs !== "number" || !Number.isInteger(candidate.actionTimeoutMs) || candidate.actionTimeoutMs < 1e3)) throw new Error("actionTimeoutMs 必须是 >= 1000 的整数毫秒数");
	if (candidate.maxActionOutputTokens !== void 0 && (typeof candidate.maxActionOutputTokens !== "number" || !Number.isInteger(candidate.maxActionOutputTokens) || candidate.maxActionOutputTokens < 8)) throw new Error("maxActionOutputTokens 必须是 >= 8 的整数");
	const system = candidate.system;
	if (system !== void 0 && typeof system !== "string") throw new Error("system 必须是字符串");
	const previous = candidate.previous;
	if (previous !== void 0 && typeof previous !== "string") throw new Error("previous 必须是字符串");
	const reason = candidate.reason;
	if (reason !== void 0 && typeof reason !== "string") throw new Error("reason 必须是字符串");
	return {
		provider: candidate.provider,
		model: candidate.model,
		side: candidate.side,
		state: candidate.state,
		...typeof system === "string" ? { system } : {},
		...candidate.thinking !== void 0 ? { thinking: candidate.thinking } : {},
		...candidate.actionTimeoutMs !== void 0 ? { actionTimeoutMs: candidate.actionTimeoutMs } : {},
		...candidate.maxActionOutputTokens !== void 0 ? { maxActionOutputTokens: candidate.maxActionOutputTokens } : {},
		...typeof previous === "string" ? { previous } : {},
		...typeof reason === "string" ? { reason } : {}
	};
}
/** Translate a terminal finish reason into an action failure. */
function finishError(finish) {
	switch (finish.kind) {
		case "stop": return;
		case "error":
		case "aborted": {
			const error = new Error(finish.failure.message);
			error.code = finish.failure.code;
			return error;
		}
		case "max-tokens": return /* @__PURE__ */ new Error("auto-chess: AI 回复超过最大输出长度");
		case "tool-calls": return /* @__PURE__ */ new Error("auto-chess: AI 意外请求了工具调用");
		/* v8 ignore next -- closed-union exhaustiveness guard */
		default: return /* @__PURE__ */ new Error(`auto-chess: unsupported finish reason "${String(finish.kind)}"`);
	}
}
/**
* Failure codes the action loop treats as transient, mirroring the harness's
* default provider retry policy (dsh-llm retry-policy.ts): a stream that
* dropped mid-response or a transient provider failure deserves one more
* attempt before the request gives up. Auth, validation, and cancellation
* failures stay fatal.
*/
const RETRYABLE_ACTION_FAILURE_CODES = /* @__PURE__ */ new Set([
	"EMPTY_RESPONSE",
	"RATE_LIMIT",
	"SERVER",
	"TIMEOUT",
	"TRANSPORT"
]);
/**
* Whether a thrown action-stream failure is transient and worth one retry.
* @param error - the error thrown by {@link streamActionText}.
* @returns true when the failure carries one of the retryable codes.
*/
function isRetryableActionFailure(error) {
	const code = error?.code;
	return typeof code === "string" && RETRYABLE_ACTION_FAILURE_CODES.has(code);
}
/**
* Run one AI action attempt: stream the framed state through the chosen
* provider/model route and assemble the reply text plus any reasoning
* blocks. The requested thinking level is forwarded only when the selected
* model advertises that exact effort; an unsupported level falls back to
* the model's own default instead of failing the attempt.
* @param ctx - host context exposing the llm service.
* @param request - the validated action request.
* @param system - the system prompt for this attempt.
* @param user - the user message for this attempt.
* @param maxTokens - the output-token cap for this attempt (per-request override or config default).
* @param signal - cancellation (request deadline / plugin disposal).
* @returns the assembled reply text, the reasoning text, and the truncation flag.
* @throws when the stream fails or the model produced no text at all.
*/
async function streamActionText(ctx, request, system, user, maxTokens, signal) {
	let reasoningEffort;
	if (request.thinking !== void 0) {
		if ((await ctx.llm.resolveModelInfo(request.provider, request.model, signal)).reasoning?.efforts.some((effort) => effort.id === request.thinking)) reasoningEffort = ReasoningEffortId(request.thinking);
	}
	const options = {
		provider: request.provider,
		model: request.model,
		messages: [user],
		system,
		maxTokens,
		signal,
		...reasoningEffort !== void 0 ? { reasoningEffort } : {}
	};
	const assembler = new BlockAssembler();
	for await (const chunk of ctx.llm.stream(options)) {
		signal.throwIfAborted();
		assembler.push(chunk);
	}
	signal.throwIfAborted();
	const truncated = assembler.finish.kind === "max-tokens";
	const terminal = finishError(assembler.finish);
	if (terminal !== void 0 && !truncated) throw terminal;
	const blocks = assembler.blocks();
	const text = blocks.filter((block) => block.type === "text").map((block) => block.text).join(" ").trim();
	if (text.length === 0 && !truncated) throw new Error("auto-chess: AI 没有返回任何内容");
	return {
		text,
		reasoning: blocks.filter((block) => block.type === "reasoning").map((block) => block.text).join(" ").trim(),
		truncated
	};
}
/**
* Mount the auto-chess plugin: the three routes plus the action-request
* lifecycle.
* @param ctx - host cordis context.
* @param config - validated loader configuration.
*/
function apply(ctx, config) {
	const resolved = {
		actionTimeoutMs: config.actionTimeoutMs,
		maxActionOutputTokens: config.maxActionOutputTokens,
		maxActionAttempts: config.maxActionAttempts
	};
	/** Collect the request body into a parsed JSON value. */
	const readJson = async (req) => {
		const chunks = [];
		for await (const chunk of req) chunks.push(chunk);
		const raw = Buffer.concat(chunks).toString("utf8");
		if (raw.length === 0) return {};
		return JSON.parse(raw);
	};
	ctx.effect(() => {
		const dispose = ctx.webServer.register({
			kind: "prefix",
			path: AUTO_CHESS_PATH,
			handler: async (req, res) => {
				const writeJson = (status, body) => {
					res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
					res.end(JSON.stringify(body));
				};
				try {
					const segments = new URL(req.url ?? "/", "http://dsh.internal").pathname.slice(19).split("/").filter(Boolean);
					if (req.method === "GET" && segments.length === 1 && segments[0] === "prompt") {
						writeJson(200, { prompt: DEFAULT_SYSTEM_PROMPT });
						return;
					}
					if (req.method === "GET" && segments.length === 1 && segments[0] === "models") {
						const groups = [];
						const failures = [];
						for (const provider of ctx.llm.listProviders()) {
							let models;
							try {
								models = await ctx.llm.listModels(provider.id);
							} catch (error) {
								failures.push({
									provider: provider.id,
									error: error instanceof Error ? error.message : String(error)
								});
								continue;
							}
							groups.push({
								provider: provider.id,
								displayName: provider.name,
								models: models.map((model) => ({
									id: model.id,
									name: model.name
								}))
							});
						}
						writeJson(200, {
							groups,
							failures
						});
						return;
					}
					if (req.method === "POST" && segments.length === 1 && segments[0] === "action") {
						const request = validateActionRequest(await readJson(req));
						const effectiveTimeoutMs = request.actionTimeoutMs ?? resolved.actionTimeoutMs;
						const effectiveMaxTokens = request.maxActionOutputTokens ?? resolved.maxActionOutputTokens;
						const controller = new AbortController();
						const timer = setTimeout(() => {
							controller.abort(/* @__PURE__ */ new Error("auto-chess: AI 决策超时"));
						}, effectiveTimeoutMs);
						try {
							const system = request.system !== void 0 && request.system.trim().length > 0 ? request.system : DEFAULT_SYSTEM_PROMPT;
							let lastText;
							let lastReason;
							let lastReasoning = "";
							for (let attempt = 1; attempt <= resolved.maxActionAttempts; attempt += 1) {
								const user = createUserMessage({
									content: [{
										type: "text",
										text: buildActionUserMessage(request.state, request.side, lastText, lastReason)
									}],
									source: {
										kind: "plugin",
										plugin: PLUGIN_ID
									}
								});
								let attemptText;
								try {
									attemptText = await streamActionText(ctx, request, system, user, effectiveMaxTokens, controller.signal);
								} catch (error) {
									if (!isRetryableActionFailure(error)) throw error;
									lastText = void 0;
									lastReason = error instanceof Error ? error.message : String(error);
									lastReasoning = "";
									ctx.logger.warn("auto-chess: transient AI action failure: %s", lastReason);
									if (attempt < resolved.maxActionAttempts) continue;
									break;
								}
								const text = attemptText.text;
								lastReasoning = attemptText.reasoning;
								const reply = parseActionReply(text);
								if (reply.kind === "actions") {
									const clone = cloneGameState(request.state);
									const verdicts = [];
									const failures = [];
									for (const action of reply.actions) {
										const error = applyAction(clone, request.side, action);
										verdicts.push({
											action,
											ok: error === void 0,
											...error !== void 0 ? { error } : {}
										});
										if (error !== void 0) failures.push(`${JSON.stringify(action)}：${error}`);
									}
									if (failures.length === 0) {
										writeJson(200, {
											actions: verdicts,
											reasoning: lastReasoning
										});
										return;
									}
									lastText = text;
									lastReason = `以下操作不合法：${failures.join("；")}`;
									continue;
								}
								if (reply.kind === "error") {
									writeJson(200, {
										error: `AI 报告：${reply.message}`,
										reasoning: lastReasoning
									});
									return;
								}
								lastText = text;
								lastReason = attemptText.truncated ? "AI 回复被截断（超过最大输出长度），可能未输出完整的 JSON" : reply.reason;
							}
							writeJson(200, {
								error: `AI 连续 ${resolved.maxActionAttempts} 次未能给出合法操作（最后原因：${lastReason ?? "未知"}）`,
								reasoning: lastReasoning,
								...lastText !== void 0 ? { lastText } : {},
								...lastReason !== void 0 ? { lastReason } : {}
							});
						} finally {
							clearTimeout(timer);
						}
						return;
					}
					writeJson(404, { error: "unknown auto-chess route" });
				} catch (error) {
					writeJson(400, { error: error instanceof Error ? error.message : String(error) });
				}
			}
		});
		return () => {
			dispose();
		};
	}, "auto-chess: routes + action lifecycle");
}
//#endregion
export { AUTO_CHESS_PATH, Config, DEFAULT_SYSTEM_PROMPT, apply, buildActionUserMessage, inject, isRetryableActionFailure, name, parseActionReply, validateActionRequest };
