From 5098005a5c77a19a4e0cea8f246e292fc63461aa Mon Sep 17 00:00:00 2001 From: Filipe Cavalcante Date: Mon, 16 Nov 2026 13:49:53 -0300 Subject: [PATCH 1/7] Add an optional local MCP server Path of Building can now serve the Model Context Protocol over Streamable HTTP on 127.0.0.1, so MCP clients can read and drive the open build. It is off by default and enabled from Options, Local MCP server. - McpHttp and McpProtocol handle HTTP and JSON-RPC without sockets, serving protocol version 2026-07-28 and the initialize-based 2025 versions on the same endpoint, with Host, Origin and bearer token checks. - McpServer polls non-blocking sockets from main:OnFrame and keeps frames running while the window is in the background, throttled when idle. - McpTools holds the tools; this adds status, the builds list, opening, saving and exporting builds, side bar stats, level and notes, and simulate. - Small refactors so the server reuses existing logic: main:ProcessModeChange, build:ProcessBuildFlag, build:HasUnsavedChanges, ItemsTab:GetSlotReplacementOverride and PassiveTreeView:ParseSearchString. --- spec/System/TestMcpServer_spec.lua | 290 +++++++++++ src/Classes/ItemsTab.lua | 21 +- src/Classes/PassiveTreeView.lua | 34 +- src/Modules/Build.lua | 43 +- src/Modules/Main.lua | 44 +- src/Modules/McpHttp.lua | 186 +++++++ src/Modules/McpProtocol.lua | 663 +++++++++++++++++++++++++ src/Modules/McpServer.lua | 440 +++++++++++++++++ src/Modules/McpTools.lua | 519 ++++++++++++++++++++ src/Modules/McpTools/Build.lua | 750 +++++++++++++++++++++++++++++ src/Modules/McpTools/Compare.lua | 6 + src/Modules/McpTools/Config.lua | 6 + src/Modules/McpTools/Items.lua | 6 + src/Modules/McpTools/Skills.lua | 6 + src/Modules/McpTools/Tree.lua | 6 + 15 files changed, 2973 insertions(+), 47 deletions(-) create mode 100644 spec/System/TestMcpServer_spec.lua create mode 100644 src/Modules/McpHttp.lua create mode 100644 src/Modules/McpProtocol.lua create mode 100644 src/Modules/McpServer.lua create mode 100644 src/Modules/McpTools.lua create mode 100644 src/Modules/McpTools/Build.lua create mode 100644 src/Modules/McpTools/Compare.lua create mode 100644 src/Modules/McpTools/Config.lua create mode 100644 src/Modules/McpTools/Items.lua create mode 100644 src/Modules/McpTools/Skills.lua create mode 100644 src/Modules/McpTools/Tree.lua diff --git a/spec/System/TestMcpServer_spec.lua b/spec/System/TestMcpServer_spec.lua new file mode 100644 index 00000000000..577ba70c6ec --- /dev/null +++ b/spec/System/TestMcpServer_spec.lua @@ -0,0 +1,290 @@ +local McpProtocol = LoadModule("Modules/McpProtocol") +local McpHttp = LoadModule("Modules/McpHttp") + +local PORT = 49290 +local TOKEN = "0123456789abcdef0123456789abcdef" +local MODERN = McpProtocol.MODERN_VERSION + +local protocol + +local function request(method, params, opts) + opts = opts or { } + local message = { jsonrpc = "2.0", id = opts.id == nil and 1 or opts.id, method = method, params = params } + if opts.notification then + message.id = nil + end + local headers = { + host = opts.host or ("127.0.0.1:" .. PORT), + authorization = opts.authorization or ("Bearer " .. TOKEN), + ["content-type"] = "application/json", + origin = opts.origin, + } + for name, value in pairs(opts.headers or { }) do + headers[name] = value + end + local response + protocol:HandleHttp({ + method = opts.httpMethod or "POST", + path = opts.path or "/mcp", + version = "1.1", + headers = headers, + body = opts.body or McpProtocol.Encode(message), + }, function(r) + response = r + end) + assert.is_truthy(response, "no response") + local body = response.body ~= "" and McpProtocol.Decode(response.body) or nil + return response.status, body, response +end + +-- A request in the 2026-07-28 form: _meta in params, metadata in headers. +local function modern(method, params, opts) + params = params or { } + params._meta = { ["io.modelcontextprotocol/protocolVersion"] = MODERN, ["io.modelcontextprotocol/clientCapabilities"] = McpProtocol.Object() } + opts = opts or { } + opts.headers = opts.headers or { } + opts.headers["mcp-protocol-version"] = opts.headers["mcp-protocol-version"] or MODERN + opts.headers["mcp-method"] = opts.headers["mcp-method"] or method + if method == "tools/call" or method == "prompts/get" then + opts.headers["mcp-name"] = opts.headers["mcp-name"] or params.name + end + return request(method, params, opts) +end + +local function callTool(name, args, allowError) + local status, body = request("tools/call", { name = name, arguments = args or McpProtocol.Object() }) + assert.are.equals(200, status) + assert.is_nil(body.error) + if body.result.isError and not allowError then + error(name .. " failed: " .. tostring(body.result.content[1].text), 2) + end + return body.result.structuredContent, body.result +end + +local function toolError(name, args) + local _, result = callTool(name, args, true) + assert.is_true(result.isError, "expected an error from " .. name) + return result.content[1].text +end + +describe("MCP server", function() + before_each(function() + main.mcpServer.token = TOKEN + protocol = main.mcpServer:NewProtocol(PORT) + newBuild() + end) + + after_each(function() + -- Dev Mode saves a changed build when the next test replaces it; there is nowhere to save it here. + build.abortSave = true + -- No test may leave one of PoB's dialogs open. + local popup = main.popups[1] + while main.popups[1] do + main:ClosePopup() + end + assert.is_nil(popup, popup and ("dialog left open: " .. tostring(popup.title))) + end) + + describe("HTTP parsing", function() + it("parses a request with a body and keeps the rest", function() + local req, rest = McpHttp.ParseRequest("POST /mcp HTTP/1.1\r\nHost: x\r\nContent-Length: 2\r\n\r\n{}GET") + assert.are.equals("POST", req.method) + assert.are.equals("{}", req.body) + assert.are.equals("x", req.headers.host) + assert.are.equals("GET", rest) + end) + it("waits for an incomplete body", function() + local req, rest = McpHttp.ParseRequest("POST /mcp HTTP/1.1\r\nContent-Length: 10\r\n\r\n{}") + assert.is_nil(req) + assert.is_nil(rest) + end) + it("decodes a chunked body", function() + local req = McpHttp.ParseRequest("POST /mcp HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\n\r\n") + assert.are.equals("{}", req.body) + end) + it("refuses a POST without a length and oversized bodies", function() + local _, status = McpHttp.ParseRequest("POST /mcp HTTP/1.1\r\nHost: x\r\n\r\n") + assert.are.equals(411, status) + _, status = McpHttp.ParseRequest("POST /mcp HTTP/1.1\r\nContent-Length: 999999999999\r\n\r\n") + assert.are.equals(413, status) + end) + end) + + describe("transport security", function() + it("refuses other hosts, foreign origins and a missing token", function() + assert.are.equals(403, (request("tools/list", nil, { host = "evil.example:49290" }))) + assert.are.equals(403, (request("tools/list", nil, { origin = "https://evil.example" }))) + assert.are.equals(401, (request("tools/list", nil, { authorization = "Bearer wrong" }))) + assert.are.equals(200, (request("tools/list", nil, { origin = "http://localhost:" .. PORT }))) + end) + it("only serves POST on /mcp", function() + assert.are.equals(405, (request("tools/list", nil, { httpMethod = "GET" }))) + assert.are.equals(404, (request("tools/list", nil, { path = "/other" }))) + end) + it("refuses batches and invalid JSON", function() + assert.are.equals(400, (request(nil, nil, { body = "[{}]" }))) + local status, body = request(nil, nil, { body = "{nope" }) + assert.are.equals(400, status) + assert.are.equals(-32700, body.error.code) + end) + end) + + describe("legacy protocol versions", function() + it("negotiates initialize", function() + local status, body = request("initialize", { protocolVersion = "2025-06-18", capabilities = { }, clientInfo = { name = "test", version = "1" } }) + assert.are.equals(200, status) + assert.are.equals("2025-06-18", body.result.protocolVersion) + assert.are.equals("path-of-building", body.result.serverInfo.name) + assert.is_truthy(body.result.capabilities.tools) + assert.is_nil(body.result.resultType) + _, body = request("initialize", { protocolVersion = "1999-01-01" }) + assert.are.equals(McpProtocol.LEGACY_VERSIONS[1], body.result.protocolVersion) + end) + it("accepts notifications without a body", function() + local status, _, response = request("notifications/initialized", nil, { notification = true }) + assert.are.equals(202, status) + assert.are.equals("", response.body) + end) + it("answers ping and lists tools with annotations", function() + local _, body = request("ping") + assert.is_truthy(body.result) + _, body = request("tools/list") + local byName = { } + for _, tool in ipairs(body.result.tools) do + byName[tool.name] = tool + assert.are.equals("object", tool.inputSchema.type) + assert.is_truthy(tool.description:len() > 80, tool.name .. " needs a fuller description") + end + assert.is_true(byName.build_stats.annotations.readOnlyHint) + assert.is_false(byName.build_open.annotations.readOnlyHint) + assert.is_true(byName.build_open.annotations.destructiveHint) + end) + it("reports an unknown tool as a protocol error and bad arguments as a tool error", function() + local _, body = request("tools/call", { name = "nope" }) + assert.are.equals(-32602, body.error.code) + local message = toolError("build_stats", { fields = "Life" }) + assert.is_truthy(message:find("arguments.fields must be array", 1, true)) + message = toolError("build_stats", { colour = true }) + assert.is_truthy(message:find("not a known argument", 1, true)) + end) + end) + + describe("protocol version " .. MODERN, function() + it("serves server/discover and tools/list with caching hints", function() + local status, body = modern("server/discover") + assert.are.equals(200, status) + assert.are.equals("complete", body.result.resultType) + assert.is_truthy(body.result.supportedVersions[1] == MODERN) + assert.are.equals("path-of-building", body.result._meta["io.modelcontextprotocol/serverInfo"].name) + _, body = modern("tools/list") + assert.are.equals("complete", body.result.resultType) + assert.is_truthy(body.result.ttlMs >= 0) + assert.are.equals("private", body.result.cacheScope) + end) + it("checks the request metadata headers", function() + local status, body = modern("tools/list", nil, { headers = { ["mcp-method"] = "tools/call" } }) + assert.are.equals(400, status) + assert.are.equals(-32020, body.error.code) + status, body = modern("tools/call", { name = "app_status" }, { headers = { ["mcp-name"] = "build_stats" } }) + assert.are.equals(400, status) + assert.are.equals(-32020, body.error.code) + status, body = modern("tools/call", { name = "app_status" }, { headers = { ["mcp-name"] = "=?base64?YXBwX3N0YXR1cw==?=" } }) + assert.are.equals(200, status) + assert.is_false(body.result.isError) + end) + it("rejects unsupported versions and unknown methods", function() + local status, body = request("tools/list", { _meta = { ["io.modelcontextprotocol/protocolVersion"] = "2099-01-01", ["io.modelcontextprotocol/clientCapabilities"] = { } } }, + { headers = { ["mcp-protocol-version"] = "2099-01-01", ["mcp-method"] = "tools/list" } }) + assert.are.equals(400, status) + assert.are.equals(-32022, body.error.code) + assert.are.equals(MODERN, body.error.data.supported[1]) + status, body = modern("nothing/here") + assert.are.equals(404, status) + assert.are.equals(-32601, body.error.code) + end) + end) + + describe("prompts and resources", function() + it("lists and fills prompts", function() + local _, body = request("prompts/list") + assert.is_truthy(#body.result.prompts >= 3) + _, body = request("prompts/get", { name = "compare_with_guide", arguments = { guide = "https://pobb.in/x" } }) + assert.is_truthy(body.result.messages[1].content.text:find("https://pobb.in/x", 1, true)) + _, body = request("prompts/get", { name = "compare_with_guide", arguments = { } }) + assert.are.equals(-32602, body.error.code) + end) + it("reads the open build as XML", function() + local _, body = request("resources/read", { uri = "pob://build/current.xml" }) + assert.is_truthy(body.result.contents[1].text:find(" 0) + end) + + it("simulates an item exactly as equipping it", function() + local itemText = "Rarity: RARE\nTest Hat\nIron Hat\nQuality: 0\n+80 to maximum Life\n+40% to Fire Resistance\n" + local result = callTool("simulate", { slot = "Helmet", item = itemText, fields = { "Life", "FireResist" } }) + assert.is_truthy(#result.changes > 0) + local predictedLife = result.values.Life.after + -- The build itself did not change. + assert.are.equals(result.values.Life.before, build.calcsTab.mainOutput.Life) + build.itemsTab:CreateDisplayItemFromRaw(itemText, true) + build.itemsTab:AddDisplayItem() + runCallback("OnFrame") + assert.are.equals(build.calcsTab.mainOutput.Life, predictedLife) + end) + + it("simulates allocating a passive with its path", function() + local target + for _, node in pairs(build.spec.nodes) do + if node.path and #node.path == 2 and node.type == "Normal" and not node.alloc then + target = node + break + end + end + assert.is_truthy(target) + local result = callTool("simulate", { add_nodes = { target.id } }) + assert.is_truthy(result.simulated[1]:find("2 points", 1, true)) + assert.is_nil(build.spec.allocNodes[target.id]) + end) + + it("exports XML that opens as the same build", function() + -- (Deflate and Inflate are stubs when running headless, so share codes are covered by hand.) + callTool("build_edit", { level = 87 }) + local export = callTool("build_export", { format = "xml" }) + local opened = callTool("build_open", { code = export.xml, discard_unsaved = true }) + assert.are.equals(87, opened.opened.level) + assert.is_true(opened.opened.unsaved) + end) + + it("refuses to replace a build with unsaved changes", function() + build.controls.characterLevel:SetText("50", true) + local message = toolError("build_open", { new = true }) + assert.is_truthy(message:find("unsaved changes", 1, true)) + local opened = callTool("build_open", { new = true, class = "Witch", ascendancy = "Necromancer", discard_unsaved = true }) + assert.are.equals("Witch", opened.opened.class) + assert.are.equals("Necromancer", opened.opened.ascendancy) + end) + + it("edits the level and notes and marks the build unsaved", function() + build:ResetModFlags() + local result = callTool("build_edit", { level = 72, notes = "Hello" }) + assert.are.equals(72, result.level) + assert.are.equals("manual", result.levelMode) + assert.are.equals("Hello", build.notesTab.controls.edit.buf) + assert.is_true(build:HasUnsavedChanges()) + end) + end) +end) diff --git a/src/Classes/ItemsTab.lua b/src/Classes/ItemsTab.lua index 3e619288a60..9bc5615905d 100644 --- a/src/Classes/ItemsTab.lua +++ b/src/Classes/ItemsTab.lua @@ -4257,6 +4257,21 @@ local function buildSpecForJewelComparison(itemsTab, compareSlot, replacementIte return spec end +--- Calculator override that puts an item into a slot in place of the one equipped there, +--- rebuilding the passive tree for jewels that change it. +--- Passing the equipped item itself (or nil) gives the override for removing it. +---@param compareSlot ItemSlotControl +---@param item Item|nil +---@return table override, Item|nil selItem +function ItemsTabClass:GetSlotReplacementOverride(compareSlot, item) + local selItem = self.items[compareSlot.selItemId] + local override = { repSlotName = compareSlot.slotName, repItem = item ~= selItem and item or nil } + if compareSlot.nodeId and (itemChangesPassiveTree(selItem) or itemChangesPassiveTree(item)) then + override.spec = buildSpecForJewelComparison(self, compareSlot, override.repItem) + end + return override, selItem +end + function ItemsTabClass:GetSocketDescriptionLine(item) -- Sockets/links local group = 0 @@ -4997,11 +5012,7 @@ function ItemsTabClass:AddItemStatDifferences(tooltip, item, base, slot) end local function getReplacedItemAndOutput(compareSlot) - local selItem = self.items[compareSlot.selItemId] - local override = { repSlotName = compareSlot.slotName, repItem = item ~= selItem and item or nil } - if compareSlot.nodeId and (itemChangesPassiveTree(selItem) or itemChangesPassiveTree(item)) then - override.spec = buildSpecForJewelComparison(self, compareSlot, override.repItem) - end + local override, selItem = self:GetSlotReplacementOverride(compareSlot, item) local output = calcFunc(override) return selItem, output end diff --git a/src/Classes/PassiveTreeView.lua b/src/Classes/PassiveTreeView.lua index c7f8976b473..59e219bb5a5 100644 --- a/src/Classes/PassiveTreeView.lua +++ b/src/Classes/PassiveTreeView.lua @@ -790,22 +790,7 @@ function PassiveTreeViewClass:Draw(build, viewPort, inputEvents) if self.searchStrCached ~= self.searchStr then self.searchStrCached = self.searchStr - local function prepSearch(search) - search = search:lower() - --gsub("([%[%]%%])", "%%%1") - local searchWords = {} - for matchstring, v in search:gmatch('"([^"]*)"') do - searchWords[#searchWords+1] = matchstring - search = search:gsub('"'..matchstring:gsub("([%(%)])", "%%%1")..'"', "") - end - for matchstring, v in search:gmatch("(%S*)") do - if matchstring:match("%S") ~= nil then - searchWords[#searchWords+1] = matchstring - end - end - return searchWords - end - self.searchParams = prepSearch(self.searchStr) + self.searchParams = self:ParseSearchString(self.searchStr) for nodeId, node in pairs(spec.nodes) do self.searchStrResults[nodeId] = #self.searchParams > 0 and self:DoesNodeMatchSearchParams(node) @@ -1331,6 +1316,23 @@ function PassiveTreeViewClass:Focus(x, y, viewPort, build) self.zoomY = -y * scale end +-- Split the search box text into the words DoesNodeMatchSearchParams looks for; "quoted text" stays one word +function PassiveTreeViewClass:ParseSearchString(search) + search = search:lower() + --gsub("([%[%]%%])", "%%%1") + local searchWords = {} + for matchstring, v in search:gmatch('"([^"]*)"') do + searchWords[#searchWords+1] = matchstring + search = search:gsub('"'..matchstring:gsub("([%(%)])", "%%%1")..'"', "") + end + for matchstring, v in search:gmatch("(%S*)") do + if matchstring:match("%S") ~= nil then + searchWords[#searchWords+1] = matchstring + end + end + return searchWords +end + function PassiveTreeViewClass:DoesNodeMatchSearchParams(node) if node.type == "ClassStart" or (node.type == "Mastery" and not node.masteryEffects) then return diff --git a/src/Modules/Build.lua b/src/Modules/Build.lua index c472060134d..e0fbbfd385d 100644 --- a/src/Modules/Build.lua +++ b/src/Modules/Build.lua @@ -1255,22 +1255,7 @@ function buildMode:OnFrame(inputEvents) self.controls.ascendDrop:CheckDroppedWidth(true) self:UpdateSecondaryAscendancyDropdown() - if self.buildFlag then - -- Wipe Global Cache - wipeGlobalCache() - - -- Rebuild calculation output tables - self.outputRevision = self.outputRevision + 1 - self.buildFlag = false - self.skillsTab:UpdateSocketGroups() - self.calcsTab:BuildOutput() - if self.controls.breakdown.pinned and self.breakdownInputs then - self.controls.breakdown:SetBreakdownData() - self.controls.breakdown:SetBreakdownData(unpack(self.breakdownInputs)) - end - self:RefreshStatList() - self.configTab.calcFunc, self.configTab.calcBase = self.calcsTab:GetMiscCalculator() - end + self:ProcessBuildFlag() if main.showThousandsSeparators ~= self.lastShowThousandsSeparators then self:RefreshStatList() end @@ -1324,7 +1309,7 @@ function buildMode:OnFrame(inputEvents) end end - self.unsaved = self.modFlag or self.notesTab.modFlag or self.partyTab.modFlag or self.configTab.modFlag or self.treeTab.modFlag or self.treeTab.searchFlag or self.spec.modFlag or self.skillsTab.modFlag or self.itemsTab.modFlag or self.calcsTab.modFlag + self.unsaved = self:HasUnsavedChanges() SetDrawLayer(5) @@ -1350,6 +1335,30 @@ function buildMode:OnFrame(inputEvents) end end +function buildMode:HasUnsavedChanges() + return self.modFlag or self.notesTab.modFlag or self.partyTab.modFlag or self.configTab.modFlag or self.treeTab.modFlag or self.treeTab.searchFlag or self.spec.modFlag or self.skillsTab.modFlag or self.itemsTab.modFlag or self.calcsTab.modFlag +end + +-- Recalculate the build if anything flagged it as changed (buildFlag) +function buildMode:ProcessBuildFlag() + if self.buildFlag then + -- Wipe Global Cache + wipeGlobalCache() + + -- Rebuild calculation output tables + self.outputRevision = self.outputRevision + 1 + self.buildFlag = false + self.skillsTab:UpdateSocketGroups() + self.calcsTab:BuildOutput() + if self.controls.breakdown.pinned and self.breakdownInputs then + self.controls.breakdown:SetBreakdownData() + self.controls.breakdown:SetBreakdownData(unpack(self.breakdownInputs)) + end + self:RefreshStatList() + self.configTab.calcFunc, self.configTab.calcBase = self.calcsTab:GetMiscCalculator() + end +end + function buildMode:SetDisplayStat(hovered, pin) if not hovered or (not pin and self.controls.breakdown.pinned) then -- if this is a hover popup, clear when the user moved mouse out of frame diff --git a/src/Modules/Main.lua b/src/Modules/Main.lua index 294fb64c24b..22405380a9d 100644 --- a/src/Modules/Main.lua +++ b/src/Modules/Main.lua @@ -151,6 +151,9 @@ function main:Init() self.tree = { } self:LoadTree(latestTreeVersion) + -- Local MCP server; its settings are read with the others and it starts only when enabled + self.mcpServer = LoadModule("Modules/McpServer") + if self.userPath then self:ChangeUserPath(self.userPath, ignoreBuild) end @@ -374,16 +377,11 @@ end function main:Shutdown() self:CallMode("Shutdown") self:SaveSettings() + self.mcpServer:Stop() end -function main:OnFrame() - self.screenW, self.screenH = GetVirtualScreenSize() - - if self.screenH > self.screenW then - self.portraitMode = true - else - self.portraitMode = false - end +-- Switch to the mode requested with SetMode, if any. +function main:ProcessModeChange() while self.newMode do if self.mode then self:CallMode("Shutdown") @@ -396,6 +394,17 @@ function main:OnFrame() end self.newModeChangeToTree = false end +end + +function main:OnFrame() + self.screenW, self.screenH = GetVirtualScreenSize() + + if self.screenH > self.screenW then + self.portraitMode = true + else + self.portraitMode = false + end + self:ProcessModeChange() self.viewPort = { x = 0, y = 0, width = self.screenW, height = self.screenH } @@ -484,6 +493,9 @@ function main:OnFrame() end itemLib.wiki.triggered = false + -- Answer MCP requests between frames; it looks at this frame's input to tell whether the window is in use + self.mcpServer:Poll(self.inputEvents) + wipeTable(self.inputEvents) -- TODO: this pattern may pose memory management issues for classes that don't exist for the lifetime of the program @@ -573,6 +585,8 @@ function main:LoadSettings(ignoreBuild) } end end + elseif node.elem == "McpServer" then + self.mcpServer:LoadSettings(node) elseif node.elem == "Misc" then if node.attrib.buildSortMode then self.buildSortMode = node.attrib.buildSortMode @@ -776,6 +790,7 @@ function main:SaveSettings() t_insert(sharedItemList, set) end t_insert(setXML, sharedItemList) + t_insert(setXML, self.mcpServer:SaveSettings()) t_insert(setXML, { elem = "Misc", attrib = { buildSortMode = self.buildSortMode, connectionProtocol = tostring(launch.connectionProtocol), @@ -859,6 +874,7 @@ function main:ChangeUserPath(newUserPath, ignoreBuild) MakeDir(self.buildPath) self:LoadSettings(ignoreBuild) self:LoadSharedItems() + self.mcpServer:Apply() end --- Opens the popup for the "Options" menu --- @param savedState table|nil optional passing of saved values, in case of reopening `{nodePowerTheme, colorPositive, ...}` @@ -897,7 +913,7 @@ function main:OpenOptionsPopup(savedState) } -- NOTE: Height needs to be adjusted if more menu options are added - local oneColumnHeightReq = 850 -- Min height required to not split menu into two columns + local oneColumnHeightReq = 876 -- Min height required to not split menu into two columns local columnWidth = 600 local startingY = 20 @@ -1077,6 +1093,16 @@ function main:OpenOptionsPopup(savedState) end) controls.disableScrollControlInteraction.tooltipText = "Disable changing the values in controls such as dropdowns or numeric inputs when using the scroll wheel." + nextRow() + controls.mcpServer = new("ButtonControl"):ButtonControl({ "TOPLEFT", controls.sectionAnchor, "TOPLEFT" }, { currentX + defaultLabelPlacementX, currentY, 100, 18 }, "Configure...", function() + self.mcpServer:OpenSettingsPopup() + end) + controls.mcpServerLabel = new("LabelControl"):LabelControl({ "RIGHT", controls.mcpServer, "LEFT" }, { defaultLabelSpacingPx, 0, 0, 16 }, "^7Local MCP server:") + controls.mcpServerStatus = new("LabelControl"):LabelControl({ "LEFT", controls.mcpServer, "RIGHT" }, { 8, 0, 0, 16 }, function() + return self.mcpServer:IsRunning() and "^2On" or "^8Off" + end) + controls.mcpServer.tooltipText = "Lets MCP clients on this computer read and change the build open in Path of Building.\nOff by default." + nextRow() local leftColumnMaxY = currentY -- store left column height diff --git a/src/Modules/McpHttp.lua b/src/Modules/McpHttp.lua new file mode 100644 index 00000000000..7a825c9bf6f --- /dev/null +++ b/src/Modules/McpHttp.lua @@ -0,0 +1,186 @@ +-- Path of Building +-- +-- Module: MCP HTTP +-- Minimal HTTP/1.1 message handling for the local MCP server (Modules/McpServer). +-- It only parses requests and composes responses; it never touches a socket, +-- so it runs (and is tested) without LuaSocket. +-- +local s_format = string.format +local t_concat = table.concat +local t_insert = table.insert + +local M = { } + +-- Largest request the server accepts. MCP requests are small JSON-RPC +-- messages; the largest realistic one carries a build XML or code. +M.MAX_HEADER_BYTES = 16 * 1024 +M.MAX_BODY_BYTES = 8 * 1024 * 1024 + +local reasonPhrases = { + [200] = "OK", + [202] = "Accepted", + [400] = "Bad Request", + [401] = "Unauthorized", + [403] = "Forbidden", + [404] = "Not Found", + [405] = "Method Not Allowed", + [411] = "Length Required", + [413] = "Content Too Large", + [415] = "Unsupported Media Type", + [431] = "Request Header Fields Too Large", + [500] = "Internal Server Error", + [501] = "Not Implemented", + [503] = "Service Unavailable", +} + +-- Decode a chunked body. Returns body, rest (bytes after it), or nil if more +-- data is needed, or false, error message. +local function decodeChunked(data) + local parts = { } + local pos = 1 + local size = 0 + while true do + local lineEnd = data:find("\r\n", pos, true) + if not lineEnd then + return nil + end + local chunkSize = tonumber(data:sub(pos, lineEnd - 1):match("^%s*(%x+)"), 16) + if not chunkSize then + return false, "invalid chunk size" + end + pos = lineEnd + 2 + if chunkSize == 0 then + -- Skip trailers until the empty line that ends the message. + while true do + local trailerEnd = data:find("\r\n", pos, true) + if not trailerEnd then + return nil + end + local isEmpty = trailerEnd == pos + pos = trailerEnd + 2 + if isEmpty then + return t_concat(parts), data:sub(pos) + end + end + end + size = size + chunkSize + if size > M.MAX_BODY_BYTES then + return false, "body too large" + end + if #data < pos + chunkSize + 1 then + return nil + end + t_insert(parts, data:sub(pos, pos + chunkSize - 1)) + pos = pos + chunkSize + if data:sub(pos, pos + 1) ~= "\r\n" then + return false, "invalid chunk terminator" + end + pos = pos + 2 + end +end + +--- Try to read one request from the start of a buffer. +--- @param buffer string Bytes received so far on a connection. +--- @return table|nil request { method, path, version, headers = { [lowercase name] = value }, body }; nil when more bytes are needed +--- @return string|number rest Bytes after the request, or an HTTP status code when the request is malformed +--- @return string? message Explanation of the error, when rest is a status code +function M.ParseRequest(buffer) + local headerEnd = buffer:find("\r\n\r\n", 1, true) + if not headerEnd then + if #buffer > M.MAX_HEADER_BYTES then + return nil, 431, "request headers too large" + end + return nil, nil + end + if headerEnd > M.MAX_HEADER_BYTES then + return nil, 431, "request headers too large" + end + local head = buffer:sub(1, headerEnd - 1) + local requestLine, headerText = head:match("^([^\r\n]*)\r?\n?(.*)$") + local method, path, version = requestLine:match("^(%u+) (%S+) HTTP/(%d%.%d)$") + if not method then + return nil, 400, "malformed request line" + end + local headers = { } + for line in headerText:gmatch("[^\r\n]+") do + local name, value = line:match("^([^:%s]+):%s*(.-)%s*$") + if not name then + return nil, 400, "malformed header line" + end + name = name:lower() + if headers[name] then + headers[name] = headers[name] .. ", " .. value + else + headers[name] = value + end + end + local rest = buffer:sub(headerEnd + 4) + local body = "" + local encoding = headers["transfer-encoding"] + if encoding then + if not encoding:lower():match("^%s*chunked%s*$") then + return nil, 501, "unsupported transfer encoding" + end + local decoded, after = decodeChunked(rest) + if decoded == nil then + return nil, nil + elseif decoded == false then + return nil, after == "body too large" and 413 or 400, after + end + body, rest = decoded, after + elseif headers["content-length"] then + local length = tonumber(headers["content-length"]:match("^%d+$")) + if not length then + return nil, 400, "invalid Content-Length" + end + if length > M.MAX_BODY_BYTES then + return nil, 413, "body too large" + end + if #rest < length then + return nil, nil + end + body, rest = rest:sub(1, length), rest:sub(length + 1) + elseif method == "POST" then + return nil, 411, "Content-Length required" + end + return { + method = method, + path = path, + version = version, + headers = headers, + body = body, + }, rest +end + +--- Whether the connection stays open after answering this request. +function M.KeepAlive(request) + local connection = (request.headers["connection"] or ""):lower() + if request.version == "1.0" then + return connection:find("keep%-alive") ~= nil + end + return connection:find("close") == nil +end + +--- Compose an HTTP response. +--- @param status number +--- @param headers table|nil Extra headers, { name = value } +--- @param body string|nil +--- @param keepAlive boolean +function M.FormatResponse(status, headers, body, keepAlive) + body = body or "" + local lines = { s_format("HTTP/1.1 %d %s", status, reasonPhrases[status] or "Unknown") } + local names = { } + for name in pairs(headers or { }) do + t_insert(names, name) + end + table.sort(names) + for _, name in ipairs(names) do + t_insert(lines, name .. ": " .. headers[name]) + end + t_insert(lines, "Content-Length: " .. #body) + t_insert(lines, "Cache-Control: no-store") + t_insert(lines, "Connection: " .. (keepAlive and "keep-alive" or "close")) + return t_concat(lines, "\r\n") .. "\r\n\r\n" .. body +end + +return M diff --git a/src/Modules/McpProtocol.lua b/src/Modules/McpProtocol.lua new file mode 100644 index 00000000000..03fbf26b781 --- /dev/null +++ b/src/Modules/McpProtocol.lua @@ -0,0 +1,663 @@ +-- Path of Building +-- +-- Module: MCP Protocol +-- The Model Context Protocol over Streamable HTTP, for the local MCP server +-- (Modules/McpServer). It turns one parsed HTTP request (Modules/McpHttp) into +-- one HTTP response. It does no socket work, so it runs (and is tested) +-- without LuaSocket. +-- +-- Two protocol eras are served on the same endpoint, as the specification +-- allows for "dual-era" servers +-- (https://modelcontextprotocol.io/specification/2026-07-28/basic/versioning): +-- * 2026-07-28: stateless. Every request carries its protocol version and the +-- client's capabilities in params._meta and in HTTP headers. +-- * 2025-11-25, 2025-06-18 and 2025-03-26: the client opens with `initialize`. +-- No session id is issued (optional in those versions), so every request +-- is still handled on its own. +-- Responses are always application/json; the server never opens an SSE stream. +-- +local dkjson = require("dkjson") +local base64 = require("base64") + +local t_insert = table.insert +local t_concat = table.concat +local s_format = string.format + +local M = { } + +M.MODERN_VERSION = "2026-07-28" +M.LEGACY_VERSIONS = { "2025-11-25", "2025-06-18", "2025-03-26" } +M.ENDPOINT = "/mcp" + +-- JSON-RPC error codes +local PARSE_ERROR = -32700 +local INVALID_REQUEST = -32600 +local METHOD_NOT_FOUND = -32601 +local INVALID_PARAMS = -32602 +local INTERNAL_ERROR = -32603 +local HEADER_MISMATCH = -32020 +local UNSUPPORTED_VERSION = -32022 + +-- How long (ms) a client may reuse list results. They only change when Path of +-- Building is updated. +local LIST_TTL_MS = 5 * 60 * 1000 + +local META_VERSION = "io.modelcontextprotocol/protocolVersion" +local META_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities" +local META_SERVER_INFO = "io.modelcontextprotocol/serverInfo" + +local objectMeta = { __jsontype = "object" } +local arrayMeta = { __jsontype = "array" } + +--- Mark a table so it encodes as a JSON object even when empty. +function M.Object(t) + return setmetatable(t or { }, objectMeta) +end + +--- Mark a table so it encodes as a JSON array even when empty. +function M.Array(t) + return setmetatable(t or { }, arrayMeta) +end + +M.null = dkjson.null + +function M.Encode(value) + return dkjson.encode(value) +end + +function M.Decode(text) + -- dkjson marks decoded objects and arrays with __jsontype metatables. + local value, _, err = dkjson.decode(text, 1, nil) + return value, err +end + +local function isObject(value) + if type(value) ~= "table" then + return false + end + local meta = getmetatable(value) + if meta and meta.__jsontype then + return meta.__jsontype == "object" + end + return next(value) == nil or value[1] == nil +end + +local function isArray(value) + if type(value) ~= "table" then + return false + end + local meta = getmetatable(value) + if meta and meta.__jsontype then + return meta.__jsontype == "array" + end + return next(value) == nil or value[1] ~= nil +end + +local function isInteger(value) + return type(value) == "number" and value == math.floor(value) and value > -math.huge and value < math.huge +end + +------------------------------------------------------------------------------ +-- Argument validation: the JSON Schema subset the tool schemas use. +------------------------------------------------------------------------------ + +local function typeMatches(schemaType, value) + if schemaType == "object" then + return isObject(value) + elseif schemaType == "array" then + return isArray(value) + elseif schemaType == "string" then + return type(value) == "string" + elseif schemaType == "integer" then + return isInteger(value) + elseif schemaType == "number" then + return type(value) == "number" + elseif schemaType == "boolean" then + return type(value) == "boolean" + elseif schemaType == "null" then + return value == nil + end + return true +end + +local function describeType(schemaType) + if type(schemaType) == "table" then + return t_concat(schemaType, " or ") + end + return schemaType +end + +local function validate(schema, value, path, errors) + if type(schema) ~= "table" then + return + end + if schema.anyOf then + for _, option in ipairs(schema.anyOf) do + local optionErrors = { } + validate(option, value, path, optionErrors) + if not optionErrors[1] then + return + end + end + t_insert(errors, s_format("%s does not match any allowed form", path)) + return + end + if schema.type then + local ok = false + if type(schema.type) == "table" then + for _, schemaType in ipairs(schema.type) do + ok = ok or typeMatches(schemaType, value) + end + else + ok = typeMatches(schema.type, value) + end + if not ok then + t_insert(errors, s_format("%s must be %s", path, describeType(schema.type))) + return + end + end + if schema.enum then + local found = false + for _, allowed in ipairs(schema.enum) do + if allowed == value then + found = true + break + end + end + if not found then + local list = { } + for _, allowed in ipairs(schema.enum) do + t_insert(list, tostring(allowed)) + end + t_insert(errors, s_format("%s must be one of: %s", path, t_concat(list, ", "))) + return + end + end + if type(value) == "number" then + if schema.minimum and value < schema.minimum then + t_insert(errors, s_format("%s must be at least %s", path, tostring(schema.minimum))) + end + if schema.maximum and value > schema.maximum then + t_insert(errors, s_format("%s must be at most %s", path, tostring(schema.maximum))) + end + elseif type(value) == "string" then + if schema.minLength and #value < schema.minLength then + t_insert(errors, s_format("%s must not be empty", path)) + end + if schema.maxLength and #value > schema.maxLength then + t_insert(errors, s_format("%s is longer than %d characters", path, schema.maxLength)) + end + end + if type(value) == "table" and isArray(value) and schema.items then + if schema.maxItems and #value > schema.maxItems then + t_insert(errors, s_format("%s has more than %d entries", path, schema.maxItems)) + end + for i, item in ipairs(value) do + validate(schema.items, item, s_format("%s[%d]", path, i - 1), errors) + end + end + if type(value) == "table" and isObject(value) and (schema.properties or schema.required or schema.additionalProperties ~= nil) then + local properties = schema.properties or { } + for _, name in ipairs(schema.required or { }) do + if value[name] == nil then + t_insert(errors, s_format("%s.%s is required", path, name)) + end + end + for name, propertyValue in pairs(value) do + if properties[name] then + validate(properties[name], propertyValue, path .. "." .. tostring(name), errors) + elseif schema.additionalProperties == false then + local known = { } + for knownName in pairs(properties) do + t_insert(known, knownName) + end + table.sort(known) + t_insert(errors, s_format("%s.%s is not a known argument (known: %s)", path, tostring(name), t_concat(known, ", "))) + elseif type(schema.additionalProperties) == "table" then + validate(schema.additionalProperties, propertyValue, path .. "." .. tostring(name), errors) + end + end + end +end + +--- Check a value against a tool's input schema. +--- @return string|nil error A message listing every problem, or nil when valid +function M.ValidateArguments(schema, value) + local errors = { } + validate(schema, value, "arguments", errors) + if errors[1] then + return t_concat(errors, "; ") + end +end + +------------------------------------------------------------------------------ +-- Server +------------------------------------------------------------------------------ + +local Server = { } +Server.__index = Server + +--- Create a protocol handler. +--- @param options table +--- port number: the port the server listens on (for Host and Origin checks) +--- getToken function: returns the bearer token clients must send +--- serverInfo table: { name, title, version } +--- instructions string: guidance for the client's model +--- tools table: { list = function() -> defs, call = function(def, args, finish) } +--- finish(result) with a JSON-able table, or finish(nil, message) for an error +--- prompts table|nil: { list = function() -> defs, get = function(name, args) -> result | nil, message } +--- resources table|nil: { list = function() -> defs, read = function(uri) -> contents | nil, message } +--- log function|nil: log(method, detail, ok, message) for every handled request +function M.New(options) + return setmetatable({ options = options }, Server) +end + +local function constantTimeEquals(a, b) + if type(a) ~= "string" or type(b) ~= "string" or #a ~= #b then + return false + end + local diff = 0 + for i = 1, #a do + diff = bit.bor(diff, bit.bxor(a:byte(i), b:byte(i))) + end + return diff == 0 +end + +-- Header values may be RFC 2047 encoded ("=?base64?...?=") when they carry +-- characters a header cannot (streamable-http, "Mcp-Name"). +local function decodeHeaderValue(value) + if type(value) ~= "string" then + return value + end + local encoded = value:match("^=%?base64%?(.*)%?=$") + if encoded then + return base64.decode(encoded) + end + return value +end + +local function jsonResponse(status, payload, extraHeaders) + local headers = { ["Content-Type"] = "application/json" } + for name, value in pairs(extraHeaders or { }) do + headers[name] = value + end + local ok, body = pcall(M.Encode, payload) + if not ok then + status = 500 + body = M.Encode({ jsonrpc = "2.0", id = M.null, error = { code = INTERNAL_ERROR, message = "response could not be encoded: " .. tostring(body) } }) + end + return { status = status, headers = headers, body = body } +end + +local function rpcError(id, code, message, data) + local err = { code = code, message = message } + if data ~= nil then + err.data = data + end + return { jsonrpc = "2.0", id = id == nil and M.null or id, error = err } +end + +local function errorResponse(status, id, code, message, data) + return jsonResponse(status, rpcError(id, code, message, data)) +end + +-- Requests from browsers carry an Origin header. Only pages served by this +-- server's own address could be legitimate, and it serves none, but they are +-- accepted so local tooling that sets Origin keeps working. Anything else is +-- refused, which blocks DNS rebinding and cross-site requests. +function Server:OriginAllowed(origin) + if origin == nil then + return true + end + local host, port = origin:lower():match("^https?://([^/:]+):?(%d*)/?$") + if not host then + return false + end + if host ~= "127.0.0.1" and host ~= "localhost" then + return false + end + return port == "" or tonumber(port) == self.options.port +end + +function Server:HostAllowed(hostHeader) + if not hostHeader then + return false + end + local host, port = hostHeader:lower():match("^([^:]+):?(%d*)$") + if host ~= "127.0.0.1" and host ~= "localhost" then + return false + end + return port == "" or tonumber(port) == self.options.port +end + +function Server:Authorized(authorization) + local token = self.options.getToken() + if not token or token == "" then + return false + end + local given = authorization and authorization:match("^[Bb]earer%s+(%S+)%s*$") + return constantTimeEquals(given, token) +end + +local function isLegacyVersion(version) + for _, legacy in ipairs(M.LEGACY_VERSIONS) do + if legacy == version then + return true + end + end + return false +end + +local function supportedVersions() + local list = { M.MODERN_VERSION } + for _, legacy in ipairs(M.LEGACY_VERSIONS) do + t_insert(list, legacy) + end + return list +end + +function Server:Capabilities() + local capabilities = { tools = M.Object({ listChanged = false }) } + if self.options.prompts then + capabilities.prompts = M.Object({ listChanged = false }) + end + if self.options.resources then + capabilities.resources = M.Object({ listChanged = false, subscribe = false }) + end + return M.Object(capabilities) +end + +function Server:ServerInfo() + local info = self.options.serverInfo + return M.Object({ name = info.name, title = info.title, version = info.version }) +end + +-- Tool definitions as sent in tools/list. +local function toolListEntry(def) + local entry = { + name = def.name, + title = def.title, + description = def.description, + inputSchema = def.inputSchema, + annotations = def.annotations, + } + if def.outputSchema then + entry.outputSchema = def.outputSchema + end + return entry +end + +local function textResult(text, isError) + return { content = { { type = "text", text = text } }, isError = isError == true } +end + +-- A successful tool result: structured content, and the same JSON as text +-- for clients that only read text ("SHOULD also return the serialized JSON"). +local function structuredResult(value) + local ok, text = pcall(M.Encode, value) + if not ok then + return textResult("Path of Building produced a result that could not be encoded: " .. tostring(text), true) + end + return { content = { { type = "text", text = text } }, structuredContent = value, isError = false } +end + +--- Handle one HTTP request; calls respond(response) exactly once, possibly +--- later (tool calls can finish on a later frame). +--- response: { status, headers, body } +function Server:HandleHttp(request, respond) + local headers = request.headers + local path = request.path:match("^[^?]*") + if not self:HostAllowed(headers["host"]) then + return respond(errorResponse(403, nil, INVALID_REQUEST, "Host header must be 127.0.0.1 or localhost with this server's port")) + end + if not self:OriginAllowed(headers["origin"]) then + return respond(errorResponse(403, nil, INVALID_REQUEST, "Origin not allowed")) + end + if path ~= M.ENDPOINT then + return respond(jsonResponse(404, { error = "not found; the MCP endpoint is " .. M.ENDPOINT })) + end + if request.method ~= "POST" then + -- No server-initiated stream (GET) and no sessions to end (DELETE). + local response = jsonResponse(405, { error = "only POST is supported" }) + response.headers["Allow"] = "POST" + return respond(response) + end + if not self:Authorized(headers["authorization"]) then + local response = errorResponse(401, nil, INVALID_REQUEST, + "missing or wrong bearer token; copy it from Path of Building, Options, MCP server, and send it as 'Authorization: Bearer '") + response.headers["WWW-Authenticate"] = 'Bearer realm="Path of Building"' + return respond(response) + end + local contentType = (headers["content-type"] or ""):lower() + if not contentType:match("^application/json") then + return respond(errorResponse(415, nil, INVALID_REQUEST, "Content-Type must be application/json")) + end + local message, decodeErr = M.Decode(request.body) + if message == nil then + return respond(errorResponse(400, nil, PARSE_ERROR, "invalid JSON: " .. tostring(decodeErr))) + end + if isArray(message) and type(message) == "table" and message[1] ~= nil then + return respond(errorResponse(400, nil, INVALID_REQUEST, "JSON-RPC batches are not supported; send one message per request")) + end + if not isObject(message) or message.jsonrpc ~= "2.0" then + return respond(errorResponse(400, nil, INVALID_REQUEST, "expected a JSON-RPC 2.0 message")) + end + if message.method == nil then + -- A response to a server request; this server sends none, so there is nothing to match it to. + return respond({ status = 202, headers = { }, body = "" }) + end + if type(message.method) ~= "string" then + return respond(errorResponse(400, message.id, INVALID_REQUEST, "method must be a string")) + end + if message.id == nil then + -- Notifications (notifications/initialized, notifications/cancelled, ...) need no answer. + return respond({ status = 202, headers = { }, body = "" }) + end + if type(message.id) ~= "string" and type(message.id) ~= "number" then + return respond(errorResponse(400, nil, INVALID_REQUEST, "id must be a string or a number")) + end + local params = message.params + if params ~= nil and not isObject(params) then + return respond(errorResponse(400, message.id, INVALID_REQUEST, "params must be an object")) + end + params = params or { } + + local meta = isObject(params._meta) and params._meta or nil + local modernVersion = meta and meta[META_VERSION] + local era + if message.method == "initialize" and not modernVersion then + era = "legacy" + elseif modernVersion ~= nil then + era = "modern" + local err = self:CheckModernRequest(message, params, meta, headers) + if err then + return respond(err) + end + else + era = "legacy" + local headerVersion = headers["mcp-protocol-version"] + if headerVersion and headerVersion ~= M.MODERN_VERSION and not isLegacyVersion(headerVersion) then + return respond(errorResponse(400, message.id, UNSUPPORTED_VERSION, "unsupported protocol version " .. headerVersion, + { supported = supportedVersions(), requested = headerVersion })) + end + if headerVersion == M.MODERN_VERSION then + return respond(errorResponse(400, message.id, INVALID_PARAMS, + "requests for protocol version " .. M.MODERN_VERSION .. " must carry " .. META_VERSION .. " in params._meta")) + end + end + + local function finish(result, rpcErr, status) + if rpcErr then + local httpStatus = status or 200 + if self.options.log then + self.options.log(message.method, self:Detail(message.method, params), false, rpcErr.message) + end + return respond(jsonResponse(httpStatus, rpcError(message.id, rpcErr.code, rpcErr.message, rpcErr.data))) + end + if era == "modern" then + result.resultType = result.resultType or "complete" + result._meta = M.Object({ [META_SERVER_INFO] = self:ServerInfo() }) + end + return respond(jsonResponse(200, { jsonrpc = "2.0", id = message.id, result = result })) + end + + local ok, err = pcall(self.Dispatch, self, message.method, params, era, finish) + if not ok then + finish(nil, { code = INTERNAL_ERROR, message = tostring(err) }) + end +end + +-- Validate the request metadata the 2026-07-28 revision requires +-- (basic/index "_meta", transports/streamable-http "Request Metadata Headers"). +function Server:CheckModernRequest(message, params, meta, headers) + local version = meta[META_VERSION] + if type(version) ~= "string" then + return errorResponse(400, message.id, INVALID_PARAMS, META_VERSION .. " must be a string") + end + if version ~= M.MODERN_VERSION then + return errorResponse(400, message.id, UNSUPPORTED_VERSION, "unsupported protocol version " .. version, + { supported = supportedVersions(), requested = version }) + end + if not isObject(meta[META_CAPABILITIES]) then + return errorResponse(400, message.id, INVALID_PARAMS, META_CAPABILITIES .. " is required in params._meta") + end + local headerVersion = headers["mcp-protocol-version"] + if headerVersion ~= version then + return errorResponse(400, message.id, HEADER_MISMATCH, + s_format("MCP-Protocol-Version header (%s) does not match params._meta (%s)", tostring(headerVersion), version)) + end + if decodeHeaderValue(headers["mcp-method"]) ~= message.method then + return errorResponse(400, message.id, HEADER_MISMATCH, + s_format("Mcp-Method header (%s) does not match the method (%s)", tostring(headers["mcp-method"]), message.method)) + end + local nameField = (message.method == "tools/call" or message.method == "prompts/get") and "name" + or message.method == "resources/read" and "uri" + if nameField then + local headerName = decodeHeaderValue(headers["mcp-name"]) + if headerName ~= params[nameField] then + return errorResponse(400, message.id, HEADER_MISMATCH, + s_format("Mcp-Name header (%s) does not match params.%s (%s)", tostring(headerName), nameField, tostring(params[nameField]))) + end + end +end + +-- A short description of a request for the activity log. +function Server:Detail(method, params) + if method == "tools/call" or method == "prompts/get" then + return params.name + elseif method == "resources/read" then + return params.uri + end +end + +local function cacheable(result) + result.ttlMs = LIST_TTL_MS + -- Results are only served to clients holding this installation's token. + result.cacheScope = "private" + return result +end + +function Server:Dispatch(method, params, era, finish) + local options = self.options + local modern = era == "modern" + if method == "initialize" then + local requested = params.protocolVersion + local version = isLegacyVersion(requested) and requested or M.LEGACY_VERSIONS[1] + local result = { + protocolVersion = version, + capabilities = self:Capabilities(), + serverInfo = self:ServerInfo(), + instructions = options.instructions, + } + if options.log then + options.log(method, requested, true) + end + return finish(result) + elseif method == "server/discover" then + if not modern then + return finish(nil, { code = METHOD_NOT_FOUND, message = "server/discover requires protocol version " .. M.MODERN_VERSION }) + end + local result = cacheable({ + supportedVersions = supportedVersions(), + capabilities = self:Capabilities(), + instructions = options.instructions, + }) + return finish(result) + elseif method == "ping" and not modern then + return finish(M.Object()) + elseif method == "tools/list" then + local tools = { } + for _, def in ipairs(options.tools.list()) do + t_insert(tools, toolListEntry(def)) + end + local result = { tools = M.Array(tools) } + return finish(modern and cacheable(result) or result) + elseif method == "tools/call" then + local name = params.name + local def + for _, candidate in ipairs(options.tools.list()) do + if candidate.name == name then + def = candidate + break + end + end + if not def then + return finish(nil, { code = INVALID_PARAMS, message = "Unknown tool: " .. tostring(name) }) + end + local args = params.arguments + if args == nil then + args = M.Object() + end + local function done(result, errMessage) + if options.log then + options.log(method, name, errMessage == nil, errMessage) + end + if errMessage ~= nil then + return finish(textResult(tostring(errMessage), true)) + end + return finish(structuredResult(result)) + end + local invalid = M.ValidateArguments(def.inputSchema, args) + if invalid then + return done(nil, "Invalid arguments: " .. invalid) + end + return options.tools.call(def, args, done) + elseif method == "prompts/list" and options.prompts then + local prompts = { } + for _, def in ipairs(options.prompts.list()) do + t_insert(prompts, { name = def.name, title = def.title, description = def.description, arguments = def.arguments }) + end + local result = { prompts = M.Array(prompts) } + return finish(modern and cacheable(result) or result) + elseif method == "prompts/get" and options.prompts then + local result, err = options.prompts.get(params.name, params.arguments or { }) + if not result then + return finish(nil, { code = INVALID_PARAMS, message = err }) + end + if options.log then + options.log(method, params.name, true) + end + return finish(result) + elseif method == "resources/list" and options.resources then + local result = { resources = M.Array(options.resources.list()) } + return finish(modern and cacheable(result) or result) + elseif method == "resources/templates/list" and options.resources then + local result = { resourceTemplates = M.Array() } + return finish(modern and cacheable(result) or result) + elseif method == "resources/read" and options.resources then + local contents, err = options.resources.read(params.uri) + if not contents then + return finish(nil, { code = INVALID_PARAMS, message = err or "Resource not found", data = { uri = params.uri } }) + end + local result = { contents = M.Array(contents) } + if modern then + -- The open build changes as the user works. + result.ttlMs = 0 + result.cacheScope = "private" + end + return finish(result) + end + return finish(nil, { code = METHOD_NOT_FOUND, message = "Method not found: " .. method }, modern and 404 or 200) +end + +return M diff --git a/src/Modules/McpServer.lua b/src/Modules/McpServer.lua new file mode 100644 index 00000000000..863d8592375 --- /dev/null +++ b/src/Modules/McpServer.lua @@ -0,0 +1,440 @@ +-- Path of Building +-- +-- Module: MCP Server +-- A local Model Context Protocol server, so MCP clients can read and drive the +-- build open in Path of Building. Off by default; enabled from Options. +-- +-- It listens on 127.0.0.1 only, speaks Streamable HTTP (Modules/McpHttp, +-- Modules/McpProtocol) and requires a bearer token that is stored in +-- Settings.xml. Sockets are non-blocking and polled once per frame from +-- main:OnFrame, so every tool runs on the main thread between frames, using +-- the same objects the UI uses (Modules/McpTools). +-- +local t_insert = table.insert +local t_remove = table.remove +local m_max = math.max +local m_min = math.min +local s_format = string.format + +local McpHttp = LoadModule("Modules/McpHttp") +local McpProtocol = LoadModule("Modules/McpProtocol") + +local DEFAULT_PORT = 49290 +local MAX_CONNECTIONS = 8 +local RECEIVE_BYTES = 64 * 1024 +-- A connection with no request in flight is closed after this long. +local IDLE_CONNECTION_S = 120 +-- While nobody uses the window, Poll waits this long for network activity +-- instead of returning at once (see Poll). +local IDLE_WAIT_S = 0.1 +local USER_IDLE_MS = 2000 +local LOG_SIZE = 50 + +local server = { + enabled = false, + port = DEFAULT_PORT, + token = nil, + connections = { }, + log = { }, + requestCount = 0, +} + +-- A random token. Lua has no source of secure random numbers, so this hashes +-- several values that differ between runs and machines. +local function newToken() + local sha = require("sha2") + local entropy = { + tostring(os.time()), tostring(os.clock()), tostring(GetTime()), tostring({ }), tostring(server), + tostring(collectgarbage("count")), tostring(GetCursorPos()), tostring(main and main.userPath), + } + math.randomseed(os.time() + math.floor(os.clock() * 1000000) % 1000000) + for _ = 1, 16 do + t_insert(entropy, tostring(math.random())) + end + return sha.sha256(table.concat(entropy, "|")):sub(1, 48) +end + +function server:EnsureToken() + if not self.token or not self.token:match("^%x+$") or #self.token < 32 then + self.token = newToken() + end + return self.token +end + +function server:Url() + return s_format("http://127.0.0.1:%d%s", self.port, McpProtocol.ENDPOINT) +end + +function server:ClientConfig() + return table.concat({ + '{', + ' "mcpServers": {', + ' "path-of-building": {', + ' "type": "http",', + ' "url": "' .. self:Url() .. '",', + ' "headers": { "Authorization": "Bearer ' .. self:EnsureToken() .. '" }', + ' }', + ' }', + '}', + }, "\n") +end + +function server:AddLog(label, ok, message) + t_insert(self.log, 1, { time = os.time(), label = label, ok = ok, message = message }) + while #self.log > LOG_SIZE do + t_remove(self.log) + end +end + +function server:LoadSettings(node) + self.enabled = node.attrib.enabled == "true" + self.port = tonumber(node.attrib.port) or DEFAULT_PORT + self.token = node.attrib.token +end + +function server:SaveSettings() + return { elem = "McpServer", attrib = { + enabled = tostring(self.enabled), + port = tostring(self.port), + token = self.token, + } } +end + +-- The tools, prompts and resources (loaded on first use). +function server:GetTools() + self.tools = self.tools or LoadModule("Modules/McpTools") + return self.tools +end + +-- A protocol handler for the tools, as the listener uses (also used by tests). +function server:NewProtocol(port) + local tools = self:GetTools() + return McpProtocol.New({ + port = port, + getToken = function() return self.token end, + serverInfo = { name = "path-of-building", title = "Path of Building", version = tostring(launch.versionNumber) }, + instructions = tools.instructions, + tools = tools.tools, + prompts = tools.prompts, + resources = tools.resources, + log = function(method, detail, ok, message) + self.requestCount = self.requestCount + 1 + self:AddLog(detail and (method .. " " .. tostring(detail)) or method, ok, message) + end, + }) +end + +function server:Start() + self:Stop() + self.error = nil + local socket = prerequire("socket") + if not socket then + self.error = "LuaSocket is not available" + ConPrintf("MCP server: %s", self.error) + return false + end + self.socket = socket + self:EnsureToken() + local listener = socket.tcp() + local ok, err = listener:bind("127.0.0.1", self.port) + if ok then + ok, err = listener:listen(MAX_CONNECTIONS) + end + if not ok then + listener:close() + self.error = s_format("cannot listen on 127.0.0.1:%d (%s)", self.port, tostring(err)) + ConPrintf("MCP server: %s", self.error) + return false + end + listener:settimeout(0) + self.listener = listener + self.protocol = self:NewProtocol(self.port) + -- SimpleGraphic skips OnFrame for a window that is unfocused, not under the + -- cursor and has no suspended coroutine (ui_main.cpp, ui_main_c::Frame), so + -- requests would wait until someone touches the window. A coroutine kept + -- suspended while the server runs keeps frames coming; Poll throttles them + -- while nobody uses the window. + self.keepAlive = coroutine.create(function() + while self.listener do + coroutine.yield() + end + end) + coroutine.resume(self.keepAlive) + ConPrintf("MCP server: listening on %s", self:Url()) + self:AddLog("Listening on " .. self:Url(), true) + return true +end + +function server:Stop() + for _, connection in ipairs(self.connections) do + pcall(connection.sock.close, connection.sock) + end + wipeTable(self.connections) + if self.listener then + self.listener:close() + self.listener = nil + ConPrintf("MCP server: stopped") + end + if self.keepAlive and coroutine.status(self.keepAlive) == "suspended" then + -- Let it return now that self.listener is nil. + coroutine.resume(self.keepAlive) + end + self.keepAlive = nil +end + +-- Apply the enabled flag and port, starting or stopping the listener. +function server:Apply() + if self.enabled then + return self:Start() + end + self:Stop() + self.error = nil + return true +end + +function server:IsRunning() + return self.listener ~= nil +end + +function server:StatusText() + if self.listener then + return s_format("^2Listening on %s", self:Url()) + elseif self.error then + return "^1Error: " .. self.error + end + return "^8Off" +end + +-- Whether someone used the window recently: an input event, or the cursor +-- moving inside the window. +function server:UserActive(inputEvents) + local now = GetTime() + if inputEvents and inputEvents[1] then + self.lastInput = now + end + local x, y = GetCursorPos() + if x ~= self.lastCursorX or y ~= self.lastCursorY then + if x and y and main.screenW and x >= 0 and y >= 0 and x < main.screenW and y < main.screenH then + self.lastInput = now + end + self.lastCursorX, self.lastCursorY = x, y + end + return now - (self.lastInput or 0) < USER_IDLE_MS +end + +-- Long jobs PoB runs as coroutines (item database load, power report, trade +-- generator) want full frame rate. +function server:OtherWorkRunning() + for co in pairs(coroutine._list()) do + if co ~= self.keepAlive and coroutine.status(co) == "suspended" then + return true + end + end + for _, connection in ipairs(self.connections) do + if connection.busy or connection.out ~= "" or connection.buffer ~= "" then + return true + end + end + return false +end + +local function flush(connection) + if connection.out == "" then + return true + end + local sent, err, partial = connection.sock:send(connection.out) + if sent then + connection.out = "" + return true + elseif err == "timeout" then + connection.out = connection.out:sub((partial or 0) + 1) + return true + end + return false +end + +function server:HandleRequest(connection, request) + connection.busy = true + local keepAlive = McpHttp.KeepAlive(request) + local answered = false + self.protocol:HandleHttp(request, function(response) + if answered then + return + end + answered = true + connection.busy = false + connection.lastActive = os.clock() + if connection.closed then + return + end + connection.out = connection.out .. McpHttp.FormatResponse(response.status, response.headers, response.body, keepAlive) + if not keepAlive then + connection.closeAfterFlush = true + end + end) +end + +--- Called once per frame from main:OnFrame. +function server:Poll(inputEvents) + if not self.listener then + return + end + self.tools.OnFrame() + local socket = self.socket + -- With nobody using the window and nothing else to do, wait for a + -- request here instead of rendering another idle frame at once. select + -- returns as soon as a connection or request arrives; the wait matches + -- the 100 ms SimpleGraphic sleeps between frames of an inactive window. + if not self:UserActive(inputEvents) and not self:OtherWorkRunning() then + local watch = { self.listener } + for _, connection in ipairs(self.connections) do + t_insert(watch, connection.sock) + end + socket.select(watch, nil, IDLE_WAIT_S) + end + while true do + local sock = self.listener:accept() + if not sock then + break + end + if #self.connections >= MAX_CONNECTIONS then + sock:close() + else + sock:settimeout(0) + t_insert(self.connections, { sock = sock, buffer = "", out = "", lastActive = os.clock() }) + end + end + for i = #self.connections, 1, -1 do + local connection = self.connections[i] + local keep = flush(connection) + if keep and connection.closeAfterFlush and connection.out == "" then + keep = false + end + -- Read what has arrived, unless a request is still being answered: + -- requests on one connection are answered in order. + while keep and not connection.busy and not connection.closeAfterFlush do + local data, err, partial = connection.sock:receive(RECEIVE_BYTES) + data = data or partial + if data and data ~= "" then + connection.buffer = connection.buffer .. data + connection.lastActive = os.clock() + end + if err == "closed" then + keep = connection.buffer ~= "" + connection.peerClosed = true + end + if not data or data == "" or err then + break + end + end + if keep and not connection.busy and connection.buffer ~= "" and not connection.closeAfterFlush then + local request, rest, message = McpHttp.ParseRequest(connection.buffer) + if request then + connection.buffer = rest + self:HandleRequest(connection, request) + keep = flush(connection) + elseif rest then + -- Malformed request: answer and close. + connection.buffer = "" + connection.out = connection.out .. McpHttp.FormatResponse(rest, { ["Content-Type"] = "text/plain" }, message, false) + connection.closeAfterFlush = true + flush(connection) + elseif connection.peerClosed then + keep = false + end + end + if connection.peerClosed and not connection.busy and connection.out == "" and connection.buffer == "" then + keep = false + end + if keep and not connection.busy and os.clock() - connection.lastActive > IDLE_CONNECTION_S then + keep = false + end + if not keep then + -- A request still being answered is abandoned: its reply is dropped. + connection.closed = true + pcall(connection.sock.close, connection.sock) + t_remove(self.connections, i) + end + end +end + +------------------------------------------------------------------------------ +-- Settings dialog (Options, "Configure...") +------------------------------------------------------------------------------ + +function server:OpenSettingsPopup() + local controls = { } + local enabled = self.enabled + local port = self.port + local width = 560 + + controls.enabled = new("CheckBoxControl"):CheckBoxControl({ "TOPLEFT", nil, "TOPLEFT" }, { 200, 20, 20 }, "^7Enable MCP server:", function(state) + enabled = state + end) + controls.enabled.state = enabled + controls.enabled.tooltipText = "Lets MCP clients on this computer read and change the build open in Path of Building.\n" + .. "Only connections from this computer that send the token below are accepted." + + controls.port = new("EditControl"):EditControl({ "TOPLEFT", nil, "TOPLEFT" }, { 200, 46, 80, 20 }, tostring(port), nil, "%D", 5, function(buf) + port = tonumber(buf) + end) + controls.portLabel = new("LabelControl"):LabelControl({ "RIGHT", controls.port, "LEFT" }, { -4, 0, 0, 16 }, "^7Port:") + + controls.status = new("LabelControl"):LabelControl({ "TOPLEFT", nil, "TOPLEFT" }, { 200, 74, 0, 16 }, function() + return self:StatusText() + end) + controls.statusLabel = new("LabelControl"):LabelControl({ "RIGHT", controls.status, "LEFT" }, { -4, 0, 0, 16 }, "^7Status:") + + controls.token = new("LabelControl"):LabelControl({ "TOPLEFT", nil, "TOPLEFT" }, { 200, 100, 0, 16 }, function() + local token = self:EnsureToken() + return "^7" .. token:sub(1, 8) .. "..." + end) + controls.tokenLabel = new("LabelControl"):LabelControl({ "RIGHT", controls.token, "LEFT" }, { -4, 0, 0, 16 }, "^7Token:") + controls.copyToken = new("ButtonControl"):ButtonControl({ "TOPLEFT", nil, "TOPLEFT" }, { 290, 98, 90, 20 }, "Copy", function() + Copy(self:EnsureToken()) + end) + controls.newToken = new("ButtonControl"):ButtonControl({ "LEFT", controls.copyToken, "RIGHT" }, { 8, 0, 90, 20 }, "New token", function() + self.token = newToken() + main:SaveSettings() + end) + controls.newToken.tooltipText = "Clients using the old token stop working until their configuration is updated." + + controls.copyConfig = new("ButtonControl"):ButtonControl({ "TOPLEFT", nil, "TOPLEFT" }, { 200, 126, 180, 20 }, "Copy client configuration", function() + Copy(self:ClientConfig()) + end) + controls.copyConfig.tooltipText = "Copies a JSON configuration with this server's address and token,\n" + .. "in the 'mcpServers' format most MCP clients read." + + controls.logLabel = new("LabelControl"):LabelControl({ "TOPLEFT", nil, "TOPLEFT" }, { 20, 158, 0, 16 }, function() + return s_format("^7Recent requests (%d since start):", self.requestCount) + end) + local logLines = 10 + for i = 1, logLines do + controls["log" .. i] = new("LabelControl"):LabelControl({ "TOPLEFT", nil, "TOPLEFT" }, { 28, 160 + i * 18, 0, 14 }, function() + local entry = self.log[i] + if not entry then + return "" + end + local text = s_format("^8%s %s%s", os.date("%H:%M:%S", entry.time), entry.ok and "^7" or "^1", entry.label) + if entry.message and not entry.ok then + text = text .. "^8 - " .. entry.message:gsub("\n", " "):sub(1, 60) + end + return text + end) + end + + local buttonY = 160 + (logLines + 1) * 18 + 12 + controls.save = new("ButtonControl"):ButtonControl({ "TOPLEFT", nil, "TOPLEFT" }, { width / 2 - 90, buttonY, 80, 20 }, "Save", function() + self.enabled = enabled + self.port = m_min(m_max(port or DEFAULT_PORT, 1024), 65535) + self:Apply() + main:SaveSettings() + main:ClosePopup() + end) + controls.close = new("ButtonControl"):ButtonControl({ "TOPLEFT", nil, "TOPLEFT" }, { width / 2 + 10, buttonY, 80, 20 }, "Close", function() + main:ClosePopup() + end) + main:OpenPopup(width, buttonY + 32, "MCP Server", controls, "save", nil, "close") +end + +return server diff --git a/src/Modules/McpTools.lua b/src/Modules/McpTools.lua new file mode 100644 index 00000000000..6c3ac094b7d --- /dev/null +++ b/src/Modules/McpTools.lua @@ -0,0 +1,519 @@ +-- Path of Building +-- +-- Module: MCP Tools +-- The tools, prompts and resources the local MCP server (Modules/McpServer) +-- offers. Tools are grouped by tab in Modules/McpTools/*.lua and work on the +-- same objects as the UI, so every number they report is Path of Building's. +-- +-- Rules every tool follows: +-- * Nothing replaces the open build while it has unsaved changes, unless +-- the caller explicitly discards them. +-- * Nothing that changes the build, or opens one of PoB's own dialogs, runs +-- while the user has a dialog open. +-- * Changes mark the build as unsaved, so PoB asks before closing it; only +-- build_save writes files. +-- * Dialogs and selections a tool uses to do its work are put back as they were. +-- +local McpProtocol = LoadModule("Modules/McpProtocol") + +local t_insert = table.insert +local t_concat = table.concat +local s_format = string.format +local m_min = math.min +local m_max = math.max + +local M = { } +local defs = { } +local defsByName = { } +local pending = { } + +-- Helpers shared by the tool files. +local T = { } + +T.Object = McpProtocol.Object +T.Array = McpProtocol.Array + +--- Stop the tool with a message for the client. +function T.Fail(message, ...) + if select("#", ...) > 0 then + message = s_format(message, ...) + end + error({ mcpFailure = message }, 0) +end + +--- Remove PoB colour codes (^7, ^xRRGGBB) from display text. +function T.Clean(text) + if type(text) ~= "string" then + return text + end + return (text:gsub("%^x%x%x%x%x%x%x", ""):gsub("%^%d", "")) +end + +--- Text that will be shown in PoB's UI. PoB's font only has ASCII glyphs +--- (unless a Unicode font is in use), so other characters are replaced the +--- way pasted text is (sanitiseText). Returns the text and whether it changed. +function T.Sanitise(text) + if main.unicode or type(text) ~= "string" then + return text, false + end + local clean = sanitiseText(text) + return clean, clean ~= text +end + +--- A number fit for JSON (dkjson refuses NaN and infinities). +function T.Number(value) + if type(value) ~= "number" or value ~= value or value == math.huge or value == -math.huge then + return nil + end + return value +end + +--- Round to a sensible precision for reporting. +function T.Round(value, digits) + value = T.Number(value) + if not value then + return nil + end + return round(value, digits or 4) +end + +--- The open build, or fail with a message saying what to do. +function T.Build() + local build = main.modes["BUILD"] + if main.mode ~= "BUILD" or not build.targetVersion or not build.spec then + T.Fail("No build is open in Path of Building (it shows the build list). Open one with build_open first.") + end + return build +end + +--- Recalculate the build now, as PoB would on the next frame. +function T.Recalculate(build) + build.buildFlag = true + build:ProcessBuildFlag() +end + +--- Which parts of the build hold unsaved changes. +function T.UnsavedParts(build) + local parts = { } + local flags = { + { build.modFlag, "build" }, { build.notesTab.modFlag, "notes" }, { build.partyTab.modFlag, "party" }, + { build.configTab.modFlag, "config" }, { build.treeTab.modFlag or build.spec.modFlag, "tree" }, + { build.treeTab.searchFlag, "tree search" }, { build.skillsTab.modFlag, "skills" }, + { build.itemsTab.modFlag, "items" }, { build.calcsTab.modFlag, "calcs" }, + } + for _, flag in ipairs(flags) do + if flag[1] then + t_insert(parts, flag[2]) + end + end + return parts +end + +--- Fail unless the open build may be replaced: no dialog open, and no +--- unsaved changes unless the caller discards them. +function T.CheckCanReplaceBuild(args) + if main.popups[1] then + T.Fail("A dialog is open in Path of Building; ask the user to finish or close it first.") + end + if main.mode == "BUILD" then + local build = main.modes["BUILD"] + if build.targetVersion and build.spec and build:HasUnsavedChanges() then + if not args.discard_unsaved then + T.Fail("The build open in Path of Building (%s) has unsaved changes (%s). Save it with build_save, or ask the user; " + .. "pass discard_unsaved: true only if the user agreed to lose them.", build.buildName or "?", t_concat(T.UnsavedParts(build), ", ")) + end + -- Dev Mode saves a closing build to its file; do not write changes the user chose to discard. + build.abortSave = true + end + end +end + +--- Switch PoB to a build now (main:SetMode, then the switch PoB would do on +--- the next frame), and check that it opened. +function T.SwitchToBuild(...) + main:SetMode("BUILD", ...) + main:ProcessModeChange() + local build = main.modes["BUILD"] + if main.mode == "BUILD" and build.spec and not build.targetVersion then + -- PoB asks whether to convert a build made for an older game version. + main:ClosePopup() + build:CloseBuild() + main:ProcessModeChange() + T.Fail("This build was made for an older version of Path of Exile and has to be converted; open it in Path of Building to choose.") + end + if main.mode ~= "BUILD" or not build.spec then + main:ProcessModeChange() + T.Fail("Path of Building could not open the build; check that it is a valid Path of Building build.") + end + return build +end + +--- Find an entry by name: exact (case-insensitive) match first, then a +--- unique partial match. Fails with the closest names when nothing matches. +--- @param list table +--- @param query string +--- @param getName function(entry) -> string +--- @param what string Description for messages ("socket group") +function T.Find(list, query, getName, what) + if type(query) ~= "string" then + T.Fail("%s must be a name", what) + end + local wanted = query:lower() + local partial = { } + for _, entry in ipairs(list) do + local name = getName(entry) + if name then + local lower = T.Clean(name):lower() + if lower == wanted then + return entry + elseif lower:find(wanted, 1, true) then + t_insert(partial, entry) + end + end + end + if #partial == 1 then + return partial[1] + end + local names = { } + for _, entry in ipairs(#partial > 1 and partial or list) do + local name = getName(entry) + if name and #names < 15 then + t_insert(names, T.Clean(name)) + end + end + if #partial > 1 then + T.Fail("%s '%s' matches several: %s", what, query, t_concat(names, "; ")) + end + T.Fail("No %s named '%s'. Available: %s", what, query, #names > 0 and t_concat(names, "; ") or "none") +end + +--- Page through a list. Returns the slice and paging details for the result. +function T.Page(list, args, defaultLimit, maxLimit) + local limit = m_min(m_max(math.floor(args.limit or defaultLimit), 1), maxLimit or 200) + local offset = m_max(math.floor(args.offset or 0), 0) + local slice = { } + for i = offset + 1, m_min(offset + limit, #list) do + t_insert(slice, list[i]) + end + local page = { total = #list, offset = offset, returned = #slice } + if offset + limit < #list then + page.next_offset = offset + limit + end + return T.Array(slice), page +end + +--- Schema for the common paging arguments. +function T.PageArgs(defaultLimit, maxLimit) + return { + limit = { type = "integer", minimum = 1, maximum = maxLimit or 200, description = s_format("How many entries to return (default %d).", defaultLimit) }, + offset = { type = "integer", minimum = 0, description = "How many entries to skip, for the next page (use next_offset from the previous result)." }, + } +end + +--- A tool result that arrives later (a download PoB runs, for example). +--- starter(resolve) must eventually call resolve(result) or resolve(nil, message). +function T.Defer(starter, timeoutSeconds) + return { mcpDeferred = starter, timeout = timeoutSeconds or 60 } +end + +--- A PoB tooltip stand-in that records its lines, for PoB functions that +--- report through a tooltip (stat comparisons, for example). +function T.LineCollector() + local collector = { lines = { } } + function collector:AddLine(_, text) + for line in tostring(text):gmatch("[^\n]+") do + local clean = T.Clean(line):gsub("^%s+", ""):gsub("%s+$", "") + if clean ~= "" then + t_insert(self.lines, clean) + end + end + end + function collector:AddSeparator() end + function collector:Clear() + wipeTable(self.lines) + end + return collector +end + +--- Register a tool. +--- def: name, title, description, input (properties), required (list), +--- readOnly, destructive, idempotent, openWorld (annotations), +--- needsBuild (default true), modifies (changes the open build), +--- replacesBuild, usesDialog (opens one of PoB's dialogs while it runs), +--- run(args, ctx) -> result table | nil, message | T.Defer(...) +function T.Tool(def) + assert(not defsByName[def.name], "duplicate MCP tool " .. def.name) + def.inputSchema = { + type = "object", + properties = T.Object(def.input or { }), + additionalProperties = false, + } + if def.required and def.required[1] then + def.inputSchema.required = def.required + end + def.annotations = T.Object({ + title = def.title, + readOnlyHint = def.readOnly == true, + destructiveHint = not def.readOnly and def.destructive == true, + idempotentHint = def.idempotent == true, + openWorldHint = def.openWorld == true, + }) + t_insert(defs, def) + defsByName[def.name] = def + return def +end + +T.discardUnsavedArg = { + type = "boolean", + description = "Replace the open build even though it has unsaved changes, losing them. Only pass true when the user has agreed.", +} + +local function failureMessage(err) + if type(err) == "table" and err.mcpFailure then + return err.mcpFailure + end + return "Path of Building raised an error: " .. tostring(err) +end + +-- Run a tool with the shared guards, then report through finish. +local function callTool(def, args, finish) + if def.needsBuild ~= false then + local ok, err = pcall(T.Build) + if not ok then + return finish(nil, failureMessage(err)) + end + end + if (def.modifies or def.replacesBuild or def.usesDialog) and main.popups[1] then + return finish(nil, "A dialog is open in Path of Building; ask the user to finish or close it first, then try again.") + end + local ctx = { changed = false } + function ctx:Changed() + self.changed = true + end + local popupsBefore = #main.popups + -- The output before a change, to report what the change did as the side bar would. + local outputBefore = def.modifies and main.mode == "BUILD" and main.modes["BUILD"].calcsTab and main.modes["BUILD"].calcsTab.mainOutput + + local function complete(ok, result, message) + -- Close any dialog the tool opened and left behind. + while #main.popups > popupsBefore do + main:ClosePopup() + end + if ok and ctx.changed and main.mode == "BUILD" then + local build = main.modes["BUILD"] + -- Edits made here bypass the controls that would set a tab's flag. + build.modFlag = true + build:ProcessBuildFlag() + if outputBefore and type(result) == "table" and result.statChanges == nil then + local collector = T.LineCollector() + build:AddStatComparesToTooltip(collector, outputBefore, build.calcsTab.mainOutput, "Changes:") + local changes = { } + for _, line in ipairs(collector.lines) do + if line ~= "Changes:" then + t_insert(changes, line) + end + end + result.statChanges = T.Array(changes) + end + end + if not ok then + return finish(nil, failureMessage(result)) + elseif result == nil then + return finish(nil, message or "the tool returned no result") + end + return finish(result) + end + + local ok, result, message = pcall(def.run, args, ctx) + if ok and type(result) == "table" and result.mcpDeferred then + local entry = { deadline = os.clock() + result.timeout, timeout = result.timeout } + entry.resolve = function(value, err) + if entry.done then + return + end + entry.done = true + for i, other in ipairs(pending) do + if other == entry then + table.remove(pending, i) + break + end + end + local resolvedOk, resolved, resolvedMessage = true, value, err + if type(err) == "table" then + resolvedOk, resolved = false, err + end + complete(resolvedOk, resolved, resolvedMessage) + end + t_insert(pending, entry) + local started, startErr = pcall(result.mcpDeferred, function(value, err) + -- Resolvers may themselves fail with T.Fail; report that as the result. + local resolveOk, resolveErr = pcall(entry.resolve, value, err) + if not resolveOk then + entry.resolve(nil, { mcpFailure = failureMessage(resolveErr) }) + end + end) + if not started then + entry.resolve(nil, { mcpFailure = failureMessage(startErr) }) + end + return + end + return complete(ok, result, message) +end + +--- Called every frame by the server: fails deferred calls that took too long. +function M.OnFrame() + local now = os.clock() + for i = #pending, 1, -1 do + local entry = pending[i] + if now > entry.deadline then + entry.resolve(nil, { mcpFailure = s_format("No answer within %d seconds; try again later.", entry.timeout) }) + end + end +end + +function M.HasPending() + return pending[1] ~= nil +end + +M.tools = { + list = function() + return defs + end, + call = callTool, +} + +------------------------------------------------------------------------------ +-- Resources +------------------------------------------------------------------------------ + +local BUILD_XML_URI = "pob://build/current.xml" + +M.resources = { + list = function() + local list = { } + if main.mode == "BUILD" and main.modes["BUILD"].targetVersion then + t_insert(list, { + uri = BUILD_XML_URI, + name = "current-build", + title = "Open build (XML)", + description = "The build open in Path of Building, as the XML it would save, including unsaved changes.", + mimeType = "application/xml", + }) + end + return list + end, + read = function(uri) + if uri ~= BUILD_XML_URI then + return nil, "Resource not found: " .. tostring(uri) + end + local ok, build = pcall(T.Build) + if not ok then + return nil, failureMessage(build) + end + local xml = build:SaveDB("code") + if not xml then + return nil, "Path of Building could not compose the build XML" + end + return { { uri = BUILD_XML_URI, mimeType = "application/xml", text = xml } } + end, +} + +------------------------------------------------------------------------------ +-- Prompts +------------------------------------------------------------------------------ + +local promptDefs = { + { + name = "analyze_build", + title = "Analyze the open build", + description = "Review the build open in Path of Building: offence, defence, warnings and the cheapest improvements.", + arguments = { { name = "focus", description = "Optional focus, for example 'bossing', 'mapping' or 'defence'.", required = false } }, + text = function(args) + return "Analyze the build that is open in Path of Building" .. (args.focus and args.focus ~= "" and (", focusing on " .. args.focus) or "") .. ".\n" + .. "1. Read build_stats (with warnings) and config_get to know the enemy and buff assumptions.\n" + .. "2. Read tree_get, items_get and skills_get.\n" + .. "3. Report strengths, weaknesses and anything PoB warns about.\n" + .. "4. Before recommending a change, measure it with simulate and quote the numbers it returns. Do not change the build unless asked." + end, + }, + { + name = "compare_with_guide", + title = "Compare with a guide build", + description = "Load a guide build into the Compare tab and list what differs from the open build.", + arguments = { { name = "guide", description = "Build link (pobb.in, pob.codes, poe.ninja, ...) or build code.", required = true } }, + text = function(args) + return "Compare the build open in Path of Building with this guide build: " .. tostring(args.guide) .. "\n" + .. "1. Add it with compare_builds (action add) and read the report (action report) for the stat, tree, item, skill and config differences.\n" + .. "2. Summarise what the guide has that the open build lacks, ordered by impact.\n" + .. "3. Measure the most important differences with simulate before recommending them, and do not change the build unless asked." + end, + }, + { + name = "best_upgrade", + title = "Find the best upgrade for a slot", + description = "Search for and measure candidate items for one equipment slot.", + arguments = { + { name = "slot", description = "Equipment slot, for example 'Helmet' or 'Ring 1'.", required = true }, + { name = "goal", description = "What to improve, for example 'more damage' or 'more life and resistances'.", required = false }, + }, + text = function(args) + return "Find the best upgrade for the " .. tostring(args.slot) .. " slot of the build open in Path of Building" + .. (args.goal and args.goal ~= "" and (", aiming for " .. args.goal) or "") .. ".\n" + .. "1. Read the current item with items_get and the build's needs with build_stats (resistances, attributes, warnings).\n" + .. "2. Find candidates with items_db_search (uniques and PoB's rare templates) and, if useful, items_craft; trade_query gives a weighted trade search the user can open.\n" + .. "3. Measure every candidate with simulate in that slot and rank them by the measured change, mentioning unmet requirements.\n" + .. "4. Only equip one with items_equip if the user asks." + end, + }, + { + name = "timeless_jewel", + title = "Find a timeless jewel", + description = "Use Path of Building's timeless jewel finder for a goal.", + arguments = { { name = "goal", description = "What the jewel should provide, for example 'Militant Faith with devotion near the Witch'.", required = true } }, + text = function(args) + return "Use Path of Building's timeless jewel finder for this goal: " .. tostring(args.goal) .. "\n" + .. "1. Call tree_timeless_jewel with action options to see the jewel types, sockets and node names it accepts.\n" + .. "2. Search with the weights that match the goal and present the best seeds with what they give.\n" + .. "3. Offer the trade search link it returns; nothing is bought or opened automatically." + end, + }, +} + +M.prompts = { + list = function() + return promptDefs + end, + get = function(name, args) + for _, def in ipairs(promptDefs) do + if def.name == name then + for _, arg in ipairs(def.arguments) do + if arg.required and (args[arg.name] == nil or args[arg.name] == "") then + return nil, "Missing required argument: " .. arg.name + end + end + return { + description = def.description, + messages = { { role = "user", content = { type = "text", text = def.text(args) } } }, + } + end + end + return nil, "Unknown prompt: " .. tostring(name) + end, +} + +M.instructions = table.concat({ + "This server drives the Path of Building window open on the user's computer (Path of Exile 1).", + "All numbers come from Path of Building's own calculations for the open build.", + "Start with app_status. Read before you change: build_stats, tree_get, items_get, skills_get, config_get.", + "Use simulate to measure a change (an item, passives, masteries, a flask) without touching the build.", + "Changes made here show in the window and mark the build as unsaved; only build_save writes files.", + "Never discard the user's unsaved work unless they agreed. Tools that need a dialog refuse while the user has one open.", +}, " ") + +-- Tool files, one per area of the UI. +for _, name in ipairs({ "Build", "Tree", "Items", "Skills", "Config", "Compare" }) do + LoadModule("Modules/McpTools/" .. name, T) +end + +M.T = T +return M diff --git a/src/Modules/McpTools/Build.lua b/src/Modules/McpTools/Build.lua new file mode 100644 index 00000000000..ad9a849dbc0 --- /dev/null +++ b/src/Modules/McpTools/Build.lua @@ -0,0 +1,750 @@ +-- Path of Building +-- +-- Module: MCP Tools - Build +-- Status, the builds folder, opening and saving builds, the side bar stats, +-- and what-if calculations. +-- +local T = ... + +local t_insert = table.insert +local t_concat = table.concat +local s_format = string.format + +local buildListHelpers = require("Modules.BuildListHelpers") + +-- Attributes PoB checks requirements against (CalcPerform, "Req"..attr). +local REQUIREMENT_ATTRIBUTES = { "Str", "Dex", "Int", "Omni" } + +-- Output fields build_stats and simulate report when no list is given. +local DEFAULT_FIELDS = { + "CombinedDPS", "TotalDPS", "FullDPS", "TotalDot", "AverageHit", "Speed", "CritChance", "CritMultiplier", "HitChance", + "Life", "LifeUnreserved", "EnergyShield", "Mana", "ManaUnreserved", "Ward", "Armour", "Evasion", + "FireResist", "ColdResist", "LightningResist", "ChaosResist", "EffectiveSpellSuppressionChance", "EffectiveBlockChance", + "EffectiveSpellBlockChance", "TotalEHP", "PhysicalMaximumHitTaken", "FireMaximumHitTaken", "ColdMaximumHitTaken", + "LightningMaximumHitTaken", "ChaosMaximumHitTaken", "LifeRegenRecovery", "EffectiveMovementSpeedMod", + "Str", "Dex", "Int", +} + +local function classInfo(spec) + local info = { + class = spec.curClassName, + ascendancy = spec.curAscendClassId ~= 0 and spec.curAscendClassName or nil, + } + if spec.curSecondaryAscendClassId and spec.curSecondaryAscendClassId ~= 0 then + info.secondaryAscendancy = spec.curSecondaryAscendClassName + end + return info +end + +-- The skill the side bar is calculated for. +local function mainSkillName(build) + local env = build.calcsTab.mainEnv + local skill = env and env.player and env.player.mainSkill + if not skill or not skill.activeEffect then + return nil + end + local name = skill.activeEffect.grantedEffect.name + if skill.skillPartName then + name = name .. " (" .. skill.skillPartName .. ")" + end + return name +end + +-- A short description of the open build. +function T.BuildSummary(build) + local used, ascUsed = build.spec:CountAllocNodes() + local summary = { + name = build.buildName, + file = build.dbFileName and (build.dbFileSubPath or "") .. build.buildName .. ".xml" or nil, + level = build.characterLevel, + mainSkill = mainSkillName(build), + tab = build.viewMode, + passivePointsUsed = used, + ascendancyPointsUsed = ascUsed, + unsaved = build:HasUnsavedChanges() and true or false, + } + for k, v in pairs(classInfo(build.spec)) do + summary[k] = v + end + if summary.unsaved then + summary.unsavedParts = T.UnsavedParts(build) + end + return summary +end + +-- Decode a build share code (url-safe base64 of the deflated XML), or pass XML through. +function T.DecodeBuildCode(code) + code = code:gsub("^%s+", ""):gsub("%s+$", "") + if code:sub(1, 1) == "<" then + return code + end + local xml = Inflate(common.base64.decode((code:gsub("-", "+"):gsub("_", "/")))) + if not xml or not xml:match("|%c]", "-") + if not name:match("%S") then + T.Fail("name must not be empty") + end + local folder = args.folder and buildFolderPath(args.folder, "folder") or (build.dbFileSubPath or "") + if folder ~= "" and not folder:match("/$") then + folder = folder .. "/" + end + if folder ~= "" and not NewFileSearch(main.buildPath .. folder:gsub("/$", ""), true) then + T.Fail("There is no folder '%s' in the builds folder.", folder) + end + local fileName = main.buildPath .. folder .. name .. ".xml" + local existing = io.open(fileName, "r") + if existing then + existing:close() + if fileName ~= build.dbFileName and not args.overwrite then + T.Fail("A build named '%s' already exists in that folder. Choose another name, or pass overwrite: true if the user wants to replace it.", name) + end + end + build.dbFileName = fileName + build.buildName = name + build.dbFileSubPath = folder + elseif not build.dbFileName then + T.Fail("This build has no file yet (it was opened from a code, a link or as new). Give a name to save it.") + end + if build:SaveDBFile() then + T.Fail("Path of Building could not write %s; check the folder exists and is writable.", build.dbFileName) + end + build.spec:SetWindowTitleWithBuildClass() + return { saved = (build.dbFileSubPath or "") .. build.buildName .. ".xml", build = T.BuildSummary(build) } + end, +} + +T.Tool { + name = "build_export", + title = "Export the build", + description = "Returns the open build as a Path of Building share code (what Import/Export's Generate button produces; other " + .. "PoB users can import it) or as the XML PoB saves. Includes unsaved changes. Nothing is uploaded.", + readOnly = true, + idempotent = true, + input = { + format = { type = "string", enum = { "code", "xml" }, description = "code (default) or xml." }, + }, + run = function(args) + local build = T.Build() + local xml = build:SaveDB("code") + if not xml then + T.Fail("Path of Building could not compose the build.") + end + if args.format == "xml" then + return { format = "xml", xml = xml } + end + return { format = "code", code = T.EncodeBuildCode(xml) } + end, +} + +-- Raw output values for a list of field names. +local function outputValues(output, fields) + local values, missing = { }, { } + for _, field in ipairs(fields) do + local value = output[field] + if type(value) == "number" then + values[field] = T.Round(value) + elseif type(value) == "boolean" or type(value) == "string" then + values[field] = value + else + t_insert(missing, field) + end + end + return T.Object(values), missing +end + +-- The side bar as PoB shows it (Build:RefreshStatList fills controls.statBox). +local function sidebarLines(build) + local lines = { } + for _, row in ipairs(build.controls.statBox.list) do + if row[1] then + local label = T.Clean(row[1]):gsub(":$", "") + if row[2] then + t_insert(lines, { label = label, value = T.Clean(row[2]) }) + elseif label:match("%S") then + t_insert(lines, { label = label }) + end + end + end + return lines +end + +local function warnings(build) + local list = { } + for _, line in ipairs(build.controls.warnings.lines or { }) do + t_insert(list, T.Clean(line)) + end + return list +end + +T.Tool { + name = "build_stats", + title = "Build stats", + description = "Returns the open build's stats as Path of Building calculates them: the side bar exactly as PoB shows it (labels " + .. "and formatted values, including the minion section), PoB's warnings (unmet requirements, not enough mana, too many " + .. "jewels, ...), the main skill, and raw numbers for a set of key output fields. Pass 'fields' to get other raw output values by " + .. "their PoB name (for example 'BleedDPS', 'IgniteDPS', 'ManaCost', 'LifeLeechGainRate'); fields PoB did not calculate for " + .. "this build are listed under 'missing'. The numbers depend on the Config tab (enemy, buffs, conditions): see config_get.", + readOnly = true, + idempotent = true, + input = { + fields = { type = "array", items = { type = "string" }, maxItems = 100, description = "Output field names to return raw values for (default: a set of key offence and defence fields)." }, + sidebar = { type = "boolean", description = "Include the formatted side bar (default true)." }, + minion = { type = "boolean", description = "Return the raw fields from the minion's output instead of the player's." }, + }, + run = function(args) + local build = T.Build() + build:ProcessBuildFlag() + local output = build.calcsTab.mainOutput + if args.minion then + output = output.Minion + if not output then + T.Fail("The main skill has no minion.") + end + end + local values, missing = outputValues(output, args.fields or DEFAULT_FIELDS) + local result = { + build = T.BuildSummary(build), + values = values, + warnings = T.Array(warnings(build)), + } + if args.fields and missing[1] then + result.missing = missing + end + if args.sidebar ~= false then + result.sidebar = T.Array(sidebarLines(build)) + end + return result + end, +} + +T.Tool { + name = "build_edit", + title = "Edit level and notes", + description = "Changes the character level (as the level box in the top bar does, which switches level mode to Manual) or " + .. "the build's notes (Notes tab). The change shows in the window and marks the build unsaved. Class and ascendancy are " + .. "changed with tree_edit; bandit and pantheon are Config options (config_set).", + idempotent = true, + modifies = true, + input = { + level = { type = "integer", minimum = 1, maximum = 100, description = "Character level." }, + auto_level = { type = "boolean", description = "true: let PoB estimate the level from passive points (Auto mode)." }, + notes = { type = "string", maxLength = 100000, description = "Replace the notes with this text. PoB colour codes (^1-^9, ^xRRGGBB) work." }, + append_notes = { type = "string", maxLength = 100000, description = "Add this text at the end of the notes." }, + }, + run = function(args, ctx) + local build = T.Build() + local result = { } + if args.level then + build.controls.characterLevel:SetText(tostring(args.level), true) + ctx:Changed() + end + if args.auto_level ~= nil and args.auto_level ~= build.characterLevelAutoMode then + build.controls.levelScalingButton.onClick() + ctx:Changed() + end + if args.notes or args.append_notes then + local edit = build.notesTab.controls.edit + build.notesTab:SetShowColorCodes(false) + local text = args.notes or edit.buf + if args.append_notes then + text = text .. (text ~= "" and "\n" or "") .. args.append_notes + end + local clean, changed = T.Sanitise(text) + edit:SetText(clean) + if changed then + result.note = "Characters Path of Building cannot display were replaced." + end + ctx:Changed() + end + build:ProcessBuildFlag() + result.level = build.characterLevel + result.levelMode = build.characterLevelAutoMode and "auto" or "manual" + if args.notes or args.append_notes then + result.notesLength = #build.notesTab.controls.edit.buf + end + return result + end, +} + +------------------------------------------------------------------------------ +-- What-if calculations +------------------------------------------------------------------------------ + +-- Look up a passive node by id or name (names must be unique on the tree). +function T.FindNode(spec, ref) + local id = tonumber(ref) + if id then + local node = spec.nodes[id] + if not node then + T.Fail("There is no passive node with id %d on this tree.", id) + end + return node + end + local wanted = tostring(ref):lower() + local matches = { } + for _, node in pairs(spec.nodes) do + if node.dn and node.dn:lower() == wanted and node.type ~= "ClassStart" and node.type ~= "AscendClassStart" then + t_insert(matches, node) + end + end + if #matches == 0 then + T.Fail("No passive node is named '%s'; find it with tree_search.", tostring(ref)) + elseif #matches > 1 then + -- Prefer the one this build can reach, as the tree's hover would. + local reachable = { } + for _, node in ipairs(matches) do + if node.alloc or node.path then + t_insert(reachable, node) + end + end + if #reachable == 1 then + return reachable[1] + end + local ids = { } + for _, node in ipairs(matches) do + t_insert(ids, tostring(node.id)) + end + T.Fail("Several passive nodes are named '%s' (ids %s); pass the id instead.", tostring(ref), t_concat(ids, ", ")) + end + return matches[1] +end + +-- Requirements the calculated build does not meet (CalcPerform's Req* outputs). +function T.UnmetRequirements(output) + local unmet = { } + for _, attr in ipairs(REQUIREMENT_ATTRIBUTES) do + local required = output["Req" .. attr] + if type(required) == "number" and required > (output[attr] or 0) then + local source = output["Req" .. attr .. "Item"] + local from + if type(source) == "table" then + from = source.source == "Item" and source.sourceItem and source.sourceItem.name + or source.source == "Gem" and source.sourceGem and source.sourceGem.nameSpec or nil + end + t_insert(unmet, { attribute = attr, required = required, have = output[attr] or 0, from = from }) + end + end + return unmet +end + +-- Before/after/delta for a list of fields. +function T.CompareValues(before, after, fields) + local values = { } + for _, field in ipairs(fields) do + local a, b = T.Number(before[field]), T.Number(after[field]) + if a or b then + values[field] = { before = T.Round(a or 0), after = T.Round(b or 0), change = T.Round((b or 0) - (a or 0)) } + end + end + return T.Object(values) +end + +-- An item from its text, prepared as the Items tab prepares a pasted item +-- (ItemsTab:CreateDisplayItemFromRaw with normalise). +-- slotName: the slot the item is meant for, whose anoint and eldritch implicits are copied (as the Items tab does). +function T.ParseItem(build, text, slotName) + if type(text) ~= "string" or not text:match("%S") then + T.Fail("item text is empty") + end + local item = new("Item"):Item((T.Sanitise((text:gsub("\r\n", "\n"))))) + if not item.base then + T.Fail("Path of Building could not read that item (unknown base type). Use the item text as copied from the game or from PoB.") + end + build.itemsTab:CopyAnointsAndEldritchImplicits(item, main.migrateEldritchImplicits, false, slotName) + item:NormaliseQuality() + item:BuildModList() + return item +end + +-- The item slot control for a slot name ("Helmet", "Ring 1", "Flask 2", a jewel socket label ...). +function T.FindSlot(build, slotName) + local itemsTab = build.itemsTab + local slot = itemsTab.slots[slotName] + if slot then + return slot + end + return T.Find(itemsTab.orderedSlots, slotName, function(candidate) + if candidate.inactive or (candidate.shown and not candidate.shown()) then + return nil + end + return candidate.label or candidate.slotName + end, "item slot") +end + +T.Tool { + name = "simulate", + title = "Simulate a change", + description = "Calculates what a change would do to the open build, without changing it: equipping an item (its text, as " + .. "copied from the game or PoB) in a slot or removing one, allocating or removing passive nodes, and switching a flask on " + .. "or off; any of these can be combined in one call (one item per call). It uses PoB's own what-if calculator, the same " + .. "one behind its hover tooltips: 'changes' lists the side-bar stats that change, as PoB words them in tooltips, 'values' gives " + .. "raw before/after numbers, and 'unmetRequirements' lists attribute requirements the result would not meet. Adding a node " + .. "also adds the path to it, as clicking it on the tree would. Use it to rank items or passives before recommending them.", + readOnly = true, + idempotent = true, + input = { + slot = { type = "string", description = "Equipment slot for 'item' or 'remove_item', for example 'Body Armour', 'Ring 2', 'Weapon 1', 'Flask 3'." }, + item = { type = "string", maxLength = 20000, description = "Item text to put in 'slot'." }, + remove_item = { type = "boolean", description = "Simulate removing the item in 'slot'." }, + add_nodes = { type = "array", items = { type = { "string", "integer" } }, maxItems = 50, description = "Passive nodes to allocate (names or ids)." }, + remove_nodes = { type = "array", items = { type = { "string", "integer" } }, maxItems = 50, description = "Allocated passive nodes to remove (with the nodes that depend on them)." }, + toggle_flask = { type = "integer", minimum = 1, maximum = 5, description = "Flask slot number to switch on or off." }, + fields = { type = "array", items = { type = "string" }, maxItems = 100, description = "Output fields to report before/after (default: key offence and defence fields)." }, + }, + run = function(args) + local build = T.Build() + build:ProcessBuildFlag() + local itemsTab = build.itemsTab + local spec = build.spec + local calcFunc, calcBase = build.calcsTab:GetMiscCalculator() + local override = { } + local described = { } + if args.item or args.remove_item then + if not args.slot then + T.Fail("slot is required with item or remove_item") + end + local slot = T.FindSlot(build, args.slot) + local item + if args.remove_item then + item = itemsTab.items[slot.selItemId] + if not item then + T.Fail("Nothing is equipped in %s.", slot.label or slot.slotName) + end + t_insert(described, "remove " .. item.name .. " from " .. (slot.label or slot.slotName)) + else + item = T.ParseItem(build, args.item, slot.slotName) + if not itemsTab:IsItemValidForSlot(item, slot.slotName) then + T.Fail("%s cannot be equipped in %s.", item.name, slot.label or slot.slotName) + end + local replaced = itemsTab.items[slot.selItemId] + t_insert(described, "equip " .. item.name .. " in " .. (slot.label or slot.slotName) .. (replaced and (" replacing " .. replaced.name) or "")) + end + local slotOverride = itemsTab:GetSlotReplacementOverride(slot, item) + for k, v in pairs(slotOverride) do + override[k] = v + end + end + if args.add_nodes and args.add_nodes[1] then + override.addNodes = { } + for _, ref in ipairs(args.add_nodes) do + local node = T.FindNode(spec, ref) + if node.alloc then + T.Fail("%s is already allocated.", node.dn) + end + if not node.path then + T.Fail("%s cannot be reached from this build's tree.", node.dn) + end + for _, pathNode in ipairs(node.path) do + override.addNodes[pathNode] = true + end + t_insert(described, s_format("allocate %s (%d point%s)", node.dn, #node.path, #node.path == 1 and "" or "s")) + end + end + if args.remove_nodes and args.remove_nodes[1] then + override.removeNodes = { } + for _, ref in ipairs(args.remove_nodes) do + local node = T.FindNode(spec, ref) + if not node.alloc then + T.Fail("%s is not allocated.", node.dn) + end + for _, depNode in ipairs(node.depends) do + override.removeNodes[depNode] = true + end + t_insert(described, s_format("remove %s (%d point%s)", node.dn, #node.depends, #node.depends == 1 and "" or "s")) + end + end + if args.toggle_flask then + local slot = itemsTab.slots["Flask " .. args.toggle_flask] + local flask = slot and itemsTab.items[slot.selItemId] + if not flask then + T.Fail("No flask is equipped in Flask %d.", args.toggle_flask) + end + override.toggleFlask = flask + t_insert(described, (build.calcsTab.mainEnv.flasks[flask] and "switch off " or "switch on ") .. flask.name) + end + if not described[1] then + T.Fail("Nothing to simulate: give item/remove_item with slot, add_nodes, remove_nodes or toggle_flask.") + end + local output = calcFunc(override) + local collector = T.LineCollector() + build:AddStatComparesToTooltip(collector, calcBase, output, "Changes:") + local changes = { } + for _, line in ipairs(collector.lines) do + if line ~= "Changes:" then + t_insert(changes, line) + end + end + return { + simulated = described, + changes = T.Array(changes), + values = T.CompareValues(calcBase, output, args.fields or DEFAULT_FIELDS), + unmetRequirements = T.Array(T.UnmetRequirements(output)), + unmetRequirementsNow = T.Array(T.UnmetRequirements(calcBase)), + } + end, +} + +T.DEFAULT_FIELDS = DEFAULT_FIELDS diff --git a/src/Modules/McpTools/Compare.lua b/src/Modules/McpTools/Compare.lua new file mode 100644 index 00000000000..0ce233596db --- /dev/null +++ b/src/Modules/McpTools/Compare.lua @@ -0,0 +1,6 @@ +-- Path of Building +-- +-- Module: MCP Tools - Compare +-- +local T = ... + diff --git a/src/Modules/McpTools/Config.lua b/src/Modules/McpTools/Config.lua new file mode 100644 index 00000000000..7359c9b3e2c --- /dev/null +++ b/src/Modules/McpTools/Config.lua @@ -0,0 +1,6 @@ +-- Path of Building +-- +-- Module: MCP Tools - Config +-- +local T = ... + diff --git a/src/Modules/McpTools/Items.lua b/src/Modules/McpTools/Items.lua new file mode 100644 index 00000000000..cd6ad92934f --- /dev/null +++ b/src/Modules/McpTools/Items.lua @@ -0,0 +1,6 @@ +-- Path of Building +-- +-- Module: MCP Tools - Items +-- +local T = ... + diff --git a/src/Modules/McpTools/Skills.lua b/src/Modules/McpTools/Skills.lua new file mode 100644 index 00000000000..c3f1f30bfa6 --- /dev/null +++ b/src/Modules/McpTools/Skills.lua @@ -0,0 +1,6 @@ +-- Path of Building +-- +-- Module: MCP Tools - Skills +-- +local T = ... + diff --git a/src/Modules/McpTools/Tree.lua b/src/Modules/McpTools/Tree.lua new file mode 100644 index 00000000000..9bd90fa8d15 --- /dev/null +++ b/src/Modules/McpTools/Tree.lua @@ -0,0 +1,6 @@ +-- Path of Building +-- +-- Module: MCP Tools - Tree +-- +local T = ... + From ca69380ad1968211701598ddbbf1c88891fdbb05 Mon Sep 17 00:00:00 2001 From: Filipe Cavalcante Date: Mon, 16 Nov 2026 14:02:56 -0300 Subject: [PATCH 2/7] MCP server: chunked responses, lighter idle frames, robust tool loading - Send HTTP/1.1 responses chunked. Security software that inspects MCP traffic was seen rewriting Content-Length responses on /mcp to chunked framing without re-encoding the body, which corrupted every reply; responses that are already chunked pass through intact. - Only count cursor movement as use of the window shortly after a key or click in it, and wait longer between idle frames the longer the window stays idle (up to 1 s; a request still wakes it at once). - Report a tool file that fails to load instead of failing startup. --- spec/System/TestMcpServer_spec.lua | 11 +++++++ src/Modules/McpHttp.lua | 29 ++++++++++++++++-- src/Modules/McpServer.lua | 47 +++++++++++++++++++++++------- src/Modules/McpTools.lua | 8 +++-- src/Modules/McpTools/Calcs.lua | 6 ++++ 5 files changed, 85 insertions(+), 16 deletions(-) create mode 100644 src/Modules/McpTools/Calcs.lua diff --git a/spec/System/TestMcpServer_spec.lua b/spec/System/TestMcpServer_spec.lua index 577ba70c6ec..cb48c2264b2 100644 --- a/spec/System/TestMcpServer_spec.lua +++ b/spec/System/TestMcpServer_spec.lua @@ -102,6 +102,17 @@ describe("MCP server", function() local req = McpHttp.ParseRequest("POST /mcp HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\n\r\n") assert.are.equals("{}", req.body) end) + it("sends HTTP/1.1 responses chunked and HTTP/1.0 responses with a length", function() + local response = McpHttp.FormatResponse(200, { ["Content-Type"] = "application/json" }, "{}", true, "1.1") + assert.is_truthy(response:find("Transfer-Encoding: chunked\r\n", 1, true)) + assert.is_nil(response:find("Content-Length", 1, true)) + local body = McpHttp.DecodeChunked(response:match("\r\n\r\n(.*)$")) + assert.are.equals("{}", body) + assert.is_truthy(McpHttp.FormatResponse(202, nil, "", true, "1.1"):find("\r\n\r\n0\r\n\r\n$")) + response = McpHttp.FormatResponse(200, nil, "{}", false, "1.0") + assert.is_truthy(response:find("Content-Length: 2\r\n", 1, true)) + assert.are.equals("{}", response:match("\r\n\r\n(.*)$")) + end) it("refuses a POST without a length and oversized bodies", function() local _, status = McpHttp.ParseRequest("POST /mcp HTTP/1.1\r\nHost: x\r\n\r\n") assert.are.equals(411, status) diff --git a/src/Modules/McpHttp.lua b/src/Modules/McpHttp.lua index 7a825c9bf6f..71475d4b929 100644 --- a/src/Modules/McpHttp.lua +++ b/src/Modules/McpHttp.lua @@ -162,12 +162,18 @@ function M.KeepAlive(request) end --- Compose an HTTP response. +--- HTTP/1.1 responses are sent chunked: some security software that inspects +--- MCP traffic on this machine rewrites responses to chunked framing but +--- passes a Content-Length body through unchanged, which corrupts it, while +--- it forwards responses that are already chunked intact. --- @param status number --- @param headers table|nil Extra headers, { name = value } --- @param body string|nil --- @param keepAlive boolean -function M.FormatResponse(status, headers, body, keepAlive) +--- @param httpVersion string|nil The request's HTTP version ("1.0" gets Content-Length) +function M.FormatResponse(status, headers, body, keepAlive, httpVersion) body = body or "" + local chunked = httpVersion ~= "1.0" local lines = { s_format("HTTP/1.1 %d %s", status, reasonPhrases[status] or "Unknown") } local names = { } for name in pairs(headers or { }) do @@ -177,10 +183,27 @@ function M.FormatResponse(status, headers, body, keepAlive) for _, name in ipairs(names) do t_insert(lines, name .. ": " .. headers[name]) end - t_insert(lines, "Content-Length: " .. #body) + if chunked then + t_insert(lines, "Transfer-Encoding: chunked") + else + t_insert(lines, "Content-Length: " .. #body) + end t_insert(lines, "Cache-Control: no-store") t_insert(lines, "Connection: " .. (keepAlive and "keep-alive" or "close")) - return t_concat(lines, "\r\n") .. "\r\n\r\n" .. body + local head = t_concat(lines, "\r\n") .. "\r\n\r\n" + if not chunked then + return head .. body + end + if body == "" then + return head .. "0\r\n\r\n" + end + return head .. s_format("%x\r\n", #body) .. body .. "\r\n0\r\n\r\n" +end + +--- Decode a chunked response body (for tests and tools that read responses). +function M.DecodeChunked(data) + local body, rest = decodeChunked(data) + return body, rest end return M diff --git a/src/Modules/McpServer.lua b/src/Modules/McpServer.lua index 863d8592375..c46fedd9a0f 100644 --- a/src/Modules/McpServer.lua +++ b/src/Modules/McpServer.lua @@ -24,10 +24,13 @@ local MAX_CONNECTIONS = 8 local RECEIVE_BYTES = 64 * 1024 -- A connection with no request in flight is closed after this long. local IDLE_CONNECTION_S = 120 --- While nobody uses the window, Poll waits this long for network activity --- instead of returning at once (see Poll). -local IDLE_WAIT_S = 0.1 +-- While nobody uses the window, Poll waits for network activity instead of +-- returning at once, longer the longer the window has been idle (see Poll). local USER_IDLE_MS = 2000 +-- Cursor movement only counts as use this soon after a key or click in the +-- window: the cursor also moves over the window's area while another window +-- covers it (a game, for example), which must not keep frames at full rate. +local CURSOR_ENGAGED_MS = 20000 local LOG_SIZE = 50 local server = { @@ -147,8 +150,15 @@ function server:Start() return false end listener:settimeout(0) + local protocolOk, protocol = pcall(self.NewProtocol, self, self.port) + if not protocolOk then + listener:close() + self.error = "could not load the MCP tools: " .. tostring(protocol) + ConPrintf("MCP server: %s", self.error) + return false + end self.listener = listener - self.protocol = self:NewProtocol(self.port) + self.protocol = protocol -- SimpleGraphic skips OnFrame for a window that is unfocused, not under the -- cursor and has no suspended coroutine (ui_main.cpp, ui_main_c::Frame), so -- requests would wait until someone touches the window. A coroutine kept @@ -205,16 +215,18 @@ function server:StatusText() return "^8Off" end --- Whether someone used the window recently: an input event, or the cursor --- moving inside the window. +-- Whether someone used the window recently: an input event (key, click, +-- wheel), or the cursor moving inside the window soon after one. function server:UserActive(inputEvents) local now = GetTime() if inputEvents and inputEvents[1] then self.lastInput = now + self.lastInputEvent = now end local x, y = GetCursorPos() if x ~= self.lastCursorX or y ~= self.lastCursorY then - if x and y and main.screenW and x >= 0 and y >= 0 and x < main.screenW and y < main.screenH then + local inside = x and y and main.screenW and x >= 0 and y >= 0 and x < main.screenW and y < main.screenH + if inside and now - (self.lastInputEvent or -CURSOR_ENGAGED_MS) < CURSOR_ENGAGED_MS then self.lastInput = now end self.lastCursorX, self.lastCursorY = x, y @@ -222,6 +234,20 @@ function server:UserActive(inputEvents) return now - (self.lastInput or 0) < USER_IDLE_MS end +-- How long Poll may wait for a request: frames of an idle window cost as much +-- as any other, so their rate drops the longer it stays idle. A request still +-- wakes the wait at once; only the first input after a long idle can take up +-- to a second to show. +function server:IdleWait() + local idleMs = GetTime() - (self.lastInput or 0) + if idleMs < 10000 then + return 0.1 + elseif idleMs < 60000 then + return 0.5 + end + return 1 +end + -- Long jobs PoB runs as coroutines (item database load, power report, trade -- generator) want full frame rate. function server:OtherWorkRunning() @@ -267,7 +293,7 @@ function server:HandleRequest(connection, request) if connection.closed then return end - connection.out = connection.out .. McpHttp.FormatResponse(response.status, response.headers, response.body, keepAlive) + connection.out = connection.out .. McpHttp.FormatResponse(response.status, response.headers, response.body, keepAlive, request.version) if not keepAlive then connection.closeAfterFlush = true end @@ -283,14 +309,13 @@ function server:Poll(inputEvents) local socket = self.socket -- With nobody using the window and nothing else to do, wait for a -- request here instead of rendering another idle frame at once. select - -- returns as soon as a connection or request arrives; the wait matches - -- the 100 ms SimpleGraphic sleeps between frames of an inactive window. + -- returns as soon as a connection or request arrives. if not self:UserActive(inputEvents) and not self:OtherWorkRunning() then local watch = { self.listener } for _, connection in ipairs(self.connections) do t_insert(watch, connection.sock) end - socket.select(watch, nil, IDLE_WAIT_S) + socket.select(watch, nil, self:IdleWait()) end while true do local sock = self.listener:accept() diff --git a/src/Modules/McpTools.lua b/src/Modules/McpTools.lua index 6c3ac094b7d..a6b240e69ca 100644 --- a/src/Modules/McpTools.lua +++ b/src/Modules/McpTools.lua @@ -511,8 +511,12 @@ M.instructions = table.concat({ }, " ") -- Tool files, one per area of the UI. -for _, name in ipairs({ "Build", "Tree", "Items", "Skills", "Config", "Compare" }) do - LoadModule("Modules/McpTools/" .. name, T) +-- One failing file must not take the others down. +for _, name in ipairs({ "Build", "Tree", "Items", "Skills", "Config", "Calcs", "Compare" }) do + local ok, err = pcall(LoadModule, "Modules/McpTools/" .. name, T) + if not ok then + ConPrintf("MCP server: could not load the %s tools: %s", name, tostring(err)) + end end M.T = T diff --git a/src/Modules/McpTools/Calcs.lua b/src/Modules/McpTools/Calcs.lua new file mode 100644 index 00000000000..f0ab46e9e89 --- /dev/null +++ b/src/Modules/McpTools/Calcs.lua @@ -0,0 +1,6 @@ +-- Path of Building +-- +-- Module: MCP Tools - Calcs +-- +local T = ... + From 05572e5c0a70a62705aba21ba959b4bd5059b507 Mon Sep 17 00:00:00 2001 From: Filipe Cavalcante Date: Mon, 16 Nov 2026 14:18:29 -0300 Subject: [PATCH 3/7] MCP server: tools for every tab, docs Adds the remaining tools, grouped by the part of the window they use: - Tree: tree_get, tree_search, tree_edit, tree_specs, tree_node_power, tree_timeless_jewel, tree_tattoos - Items: items_get, items_equip, items_sets, items_db_search, items_craft, trade_query - Skills and Config: skills_get, skills_edit, skills_rank_supports, config_get, config_set - Calcs: calcs_breakdown - Compare, Party and import: compare_builds, compare_copy, party, import_character Each drives the same functions the tab's controls use and restores any dialog or selection it borrows. PoB changes: - SkillsTab:PasteSocketGroup(text) now uses its argument before the clipboard (Ctrl+V passes none, so it is unchanged). - CompareTab and CompareBuySimilar export the helpers the comparison report shares with the tab. - build_open defers link downloads through T.Settle so failures reach the client instead of the download callback. Adds docs/mcp.md and specs for every tool. --- docs/mcp.md | 127 ++ spec/System/TestMcpCompare_spec.lua | 384 +++++ spec/System/TestMcpItems_spec.lua | 301 ++++ spec/System/TestMcpServer_spec.lua | 5 + spec/System/TestMcpSkillsConfig_spec.lua | 319 ++++ spec/System/TestMcpTree_spec.lua | 402 +++++ src/Classes/CompareBuySimilar.lua | 3 + src/Classes/CompareTab.lua | 6 + src/Classes/SkillsTab.lua | 2 +- src/Modules/McpTools.lua | 11 + src/Modules/McpTools/Build.lua | 17 +- src/Modules/McpTools/Calcs.lua | 456 ++++++ src/Modules/McpTools/Compare.lua | 1777 ++++++++++++++++++++++ src/Modules/McpTools/Config.lua | 460 ++++++ src/Modules/McpTools/Items.lua | 1717 +++++++++++++++++++++ src/Modules/McpTools/Skills.lua | 1006 ++++++++++++ src/Modules/McpTools/Tree.lua | 1448 ++++++++++++++++++ 17 files changed, 8432 insertions(+), 9 deletions(-) create mode 100644 docs/mcp.md create mode 100644 spec/System/TestMcpCompare_spec.lua create mode 100644 spec/System/TestMcpItems_spec.lua create mode 100644 spec/System/TestMcpSkillsConfig_spec.lua create mode 100644 spec/System/TestMcpTree_spec.lua diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 00000000000..8b0807289cd --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,127 @@ +# Local MCP server + +Path of Building can run a small [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server, so MCP clients on +the same computer can read and change the build open in the window: look at its stats, simulate an item or passive before +buying or allocating it, compare it with a guide build, use the timeless jewel finder, and so on. Every number comes from +Path of Building's own calculations, and every change shows in the window as if it had been made by hand. + +The server is **off by default**. + +## Turning it on + +1. Open **Options** (bottom left) and, under *Application options*, click **Configure...** next to *Local MCP server*. +2. Tick **Enable MCP server**, keep the port (49290) or choose another, and click **Save**. The status line shows + `Listening on http://127.0.0.1:49290/mcp`. +3. Click **Copy client configuration** and add it to your MCP client. It looks like this: + +```json +{ + "mcpServers": { + "path-of-building": { + "type": "http", + "url": "http://127.0.0.1:49290/mcp", + "headers": { "Authorization": "Bearer " } + } + } +} +``` + +Any client that supports the *Streamable HTTP* transport and custom headers works. Path of Building must be running +for the client to reach it; the server stops when Path of Building closes. The same dialog lists the most recent requests, +so you can see what a client did. + +## Safety + +- The server listens on `127.0.0.1` only, so other computers cannot reach it. +- Every request must carry the token shown in the dialog (stored in `Settings.xml`, like the Path of Exile login). + **New token** invalidates the old one. Requests with another `Host` or a foreign `Origin` header are refused, so web pages + cannot use the server. +- Nothing replaces the open build while it has unsaved changes, unless the client explicitly asks to discard them; clients + are told to do that only when you agree. +- Tools that change the build are refused while you have a dialog open in Path of Building, and changes mark the build as + unsaved, so Path of Building asks before closing it. Only `build_save` writes build files, and it never replaces another + existing file unless told to. +- Tools that use one of Path of Building's dialogs to do their work (timeless jewel finder, tattoos, crafting) close it and + put back what they changed in it. +- `import_character` uses the Path of Exile login you set up in *Import/Export*; the token never leaves Path of Building. + Build links are downloaded by Path of Building itself. Nothing is uploaded. + +## Tools + +Tools are grouped by the part of the window they work on. Read-only tools are marked as such to clients. + +| Area | Tool | What it does | +|---|---|---| +| App | `app_status` | Version, what is open, unsaved changes, dialogs, Path of Exile login | +| Builds | `builds_list` | Saved builds and folders, with PoB's search and sort | +| | `build_open` | Open a saved build, a code, a build link or a new build | +| | `build_save` | Save, or save as a new name | +| | `build_export` | Build share code or XML | +| Side bar | `build_stats` | The side bar as shown, warnings, raw output values | +| | `build_edit` | Character level and notes | +| Calcs | `simulate` | What an item, passives or a flask would change, without changing the build | +| | `calcs_breakdown` | Calcs tab cells and the breakdown of a stat | +| Tree | `tree_get` | Class, ascendancy, points, keystones, notables, masteries, jewels, specs | +| | `tree_search` | PoB's tree search, with the points needed to reach each node | +| | `tree_edit` | Allocate or remove passives, masteries, class and ascendancy | +| | `tree_specs` | Passive tree sets: list, select, new, copy, rename, delete | +| | `tree_node_power` | The node power report for a stat | +| | `tree_timeless_jewel` | The timeless jewel finder | +| | `tree_tattoos` | Tattoos for a node: list, apply, remove | +| Items | `items_get` | Equipped items, item sets, other items in the build | +| | `items_equip` | Add an item from its text, equip, unequip, flasks | +| | `items_sets` | Item sets: list, select, new, copy, rename, delete | +| | `items_db_search` | PoB's unique and rare databases, sortable by a stat | +| | `items_craft` | Build an item with PoB's crafting and return its text | +| | `trade_query` | The weighted trade search PoB generates for a slot | +| Skills | `skills_get` | Socket groups, gems, main skill, skill sets | +| | `skills_edit` | Add or change gems and groups, main skill, skill sets | +| | `skills_rank_supports` | Support gems ranked by damage for a group | +| Config | `config_get` | Configuration options that differ from defaults, or a search | +| | `config_set` | Change options, configuration sets and custom modifiers | +| Compare | `compare_builds` | Builds in the Compare tab and their differences | +| | `compare_copy` | Copy tree, items, skills or config from a compared build | +| Party | `party` | Party members and their effects | +| Import | `import_character` | Import a character through the Path of Exile login | + +The server also offers four prompts (`analyze_build`, `compare_with_guide`, `best_upgrade`, `timeless_jewel`) and the +open build's XML as the resource `pob://build/current.xml`. + +## Troubleshooting + +- **The status shows an error about the port:** another program uses it. Choose another port and update the client. +- **The client gets 401:** the token in the client does not match; copy the configuration again. +- **Requests are slow while the window is idle:** Path of Building redraws an idle window less often to save power; a + request still wakes it at once. Long tools (node power, timeless jewel search) run while the window waits. +- **Responses arrive broken or truncated:** security software that inspects local web traffic can interfere. The server + answers in the HTTP framing such software was seen to pass through intact; if a client still fails, allow local + connections to Path of Building in that software. + +## For developers + +| File | Purpose | +|---|---| +| `src/Modules/McpHttp.lua` | Parses HTTP/1.1 requests and composes responses. No sockets. | +| `src/Modules/McpProtocol.lua` | MCP over Streamable HTTP: JSON-RPC, protocol versions, Host/Origin/token checks, argument validation. No sockets. | +| `src/Modules/McpServer.lua` | LuaSocket listener polled from `main:OnFrame`, settings and the settings dialog. | +| `src/Modules/McpTools.lua` | The tool framework, prompts and resources. | +| `src/Modules/McpTools/*.lua` | The tools, one file per area of the window. | + +**Protocol.** One endpoint, `POST /mcp`, answered with `application/json` (no SSE stream). It serves protocol version +2026-07-28 (stateless: version and client capabilities in every request's `_meta` and headers, `server/discover`) and the +earlier `initialize`-based versions 2025-11-25, 2025-06-18 and 2025-03-26 on the same endpoint, as the specification allows +for dual-era servers. No session ids are issued. `GET` and `DELETE` get 405. + +**Threading.** Everything runs on the main thread between frames, on the same objects the UI uses. SimpleGraphic skips +`OnFrame` for an unfocused window unless a coroutine is suspended (`ui_main_c::Frame`), so while the server runs it keeps +one suspended; `McpServer:Poll` then waits in `socket.select` while nobody uses the window, so idle frames are rare. + +**Adding a tool.** Register it in the matching `McpTools/*.lua` with `T.Tool { name, title, description, input, required, +readOnly/destructive/idempotent/openWorld, modifies/usesDialog/replacesBuild, run }`. Prefer calling the same functions the +UI's controls call, so behaviour stays identical. Fail with `T.Fail(message)` and say what to do instead. Call +`ctx:Changed()` after changing the build: the framework then marks it unsaved, recalculates it, and reports the changed +side-bar stats. Return names people understand, with ids only where a follow-up call needs them, and page long lists. + +**Tests.** `spec/System/TestMcp*_spec.lua` drive the protocol and the tools headless (`docker-compose up`, or +`busted --lua=luajit -p TestMcp`). The socket layer and anything using `Deflate`/`Inflate` (build codes) need the real +application. diff --git a/spec/System/TestMcpCompare_spec.lua b/spec/System/TestMcpCompare_spec.lua new file mode 100644 index 00000000000..4d1a56711fc --- /dev/null +++ b/spec/System/TestMcpCompare_spec.lua @@ -0,0 +1,384 @@ +local McpProtocol = LoadModule("Modules/McpProtocol") + +local PORT = 49290 +local TOKEN = "0123456789abcdef0123456789abcdef" + +local protocol + +local function request(method, params) + local message = { jsonrpc = "2.0", id = 1, method = method, params = params } + local response + protocol:HandleHttp({ + method = "POST", + path = "/mcp", + version = "1.1", + headers = { + host = "127.0.0.1:" .. PORT, + authorization = "Bearer " .. TOKEN, + ["content-type"] = "application/json", + }, + body = McpProtocol.Encode(message), + }, function(r) + response = r + end) + assert.is_truthy(response, "no response") + local body = response.body ~= "" and McpProtocol.Decode(response.body) or nil + return response.status, body, response +end + +local function callTool(name, args, allowError) + local status, body = request("tools/call", { name = name, arguments = args or McpProtocol.Object() }) + assert.are.equals(200, status) + assert.is_nil(body.error) + if body.result.isError and not allowError then + error(name .. " failed: " .. tostring(body.result.content[1].text), 2) + end + return body.result.structuredContent, body.result +end + +local function toolError(name, args) + local _, result = callTool(name, args, true) + assert.is_true(result.isError, "expected an error from " .. name) + return result.content[1].text +end + +-- A node next to the class start that the open build has not allocated. +local function nearbyNode() + for _, node in pairs(build.spec.nodes) do + if node.path and #node.path == 1 and node.type == "Normal" and not node.alloc then + return node + end + end +end + +local HELMET = "Rarity: RARE\nTest Hat\nIron Hat\nQuality: 0\n+80 to maximum Life\n+40% to Fire Resistance\n" + +-- XML of a build different from a new one: level 90, one more passive, a helmet and a skill. +local function otherBuildXML() + newBuild() + build.controls.characterLevel:SetText("90", true) + local node = nearbyNode() + build.spec:AllocNode(node) + build.spec:AddUndoState() + build.itemsTab:CreateDisplayItemFromRaw(HELMET, true) + build.itemsTab:AddDisplayItem() + build.skillsTab:PasteSocketGroup("Label: Test group\nFireball 20/0 1\nAdded Fire Damage 20/0 1\n") + build.buildFlag = true + runCallback("OnFrame") + local xml = build:SaveDB("code") + build.abortSave = true + return xml, node.id +end + +local function readSampleCharacter() + local dkjson = require "dkjson" + local file = io.open("../spec/System/SampleCharacter.json", "r") + local body = dkjson.decode(file:read("*a")) + file:close() + return body +end + +describe("MCP compare, party and character import tools", function() + before_each(function() + main.mcpServer.token = TOKEN + protocol = main.mcpServer:NewProtocol(PORT) + -- A build an earlier spec changed would be autosaved by Dev Mode when replaced; there is nowhere to save it here. + build.abortSave = true + while main.popups[1] do + main:ClosePopup() + end + newBuild() + end) + + after_each(function() + build.abortSave = true + local popup = main.popups[1] + while main.popups[1] do + main:ClosePopup() + end + assert.is_nil(popup, popup and ("dialog left open: " .. tostring(popup.title))) + end) + + describe("compare_builds", function() + it("adds a copy of the open build, lists it and reports no differences", function() + build:ResetModFlags() + local added = callTool("compare_builds", { action = "add", current = true }) + assert.are.equals(1, added.added.index) + assert.are.equals(1, #build.compareTab.compareEntries) + local list = callTool("compare_builds", { action = "list" }) + assert.are.equals(1, #list.comparisons) + assert.are.equals("Scion", list.comparisons[1].class) + assert.is_true(list.comparisons[1].active) + local report = callTool("compare_builds", { action = "report" }) + assert.are.equals(0, #report.stats.rows) + assert.are.equals(0, report.tree.compareOnlyCount) + assert.are.equals(0, report.config.differences) + -- Comparisons are not part of the build. + assert.is_false(build:HasUnsavedChanges()) + end) + + it("adds a build from XML and reports what PoB shows as different", function() + local xml, nodeId = otherBuildXML() + newBuild() + callTool("compare_builds", { action = "add", code = xml, name = "Guide" }) + local entry = build.compareTab.compareEntries[1] + assert.are.equals("Guide", entry.label) + local report = callTool("compare_builds", { action = "report", item_mods = true, item_stat_changes = true }) + assert.are.equals(90, report.compareLevel) + local life + for _, row in ipairs(report.stats.rows) do + if row.stat == "Life" then + life = row + end + end + assert.is_truthy(life, "Life should differ") + assert.is_true(life.compareIsBetter) + local found = false + for _, node in ipairs(report.tree.compareOnly) do + found = found or node.id == nodeId + end + assert.is_true(found) + local helmet + for _, row in ipairs(report.items.slots) do + if row.slot == "Helmet" then + helmet = row + end + end + assert.are.equals("missing", helmet.status) + assert.is_truthy(helmet.compare.name:find("Test Hat", 1, true)) + assert.is_truthy(#helmet.compareMods > 0) + assert.is_truthy(#helmet.equipStatChanges > 0) + assert.are.equals(1, #report.skills.groups) + assert.is_nil(report.skills.groups[1].primaryGroup) + -- Only differences: the open build's own passives are all shared. + local all = callTool("compare_builds", { action = "report", sections = { "stats" }, only_differences = false }) + assert.is_truthy(#all.stats.rows > #report.stats.rows) + end) + + it("runs the power report without changing the open build", function() + local xml, nodeId = otherBuildXML() + newBuild() + build:ResetModFlags() + callTool("compare_builds", { action = "add", code = xml }) + local allocated = build.spec:CountAllocNodes() + local lifeBefore = build.calcsTab.mainOutput.Life + local report = callTool("compare_builds", { action = "power_report", metric = "Life" }) + assert.are.equals("Life", report.metric.stat) + local item + for _, row in ipairs(report.rows) do + if row.category == "Item" then + item = row + end + end + assert.is_truthy(item, "the helmet adds life") + assert.is_truthy(item.impact > 0) + assert.are.equals(allocated, build.spec:CountAllocNodes()) + assert.are.equals(lifeBefore, build.calcsTab.mainOutput.Life) + assert.is_false(build:HasUnsavedChanges()) + -- The tab shows the same report. + assert.are.equals("Life", build.compareTab.comparePowerStat.stat) + local message = toolError("compare_builds", { action = "power_report", metric = "Nope" }) + assert.is_truthy(message:find("Unknown metric", 1, true)) + end) + + it("composes a buy-similar URL for a compared item without opening anything", function() + local xml = otherBuildXML() + newBuild() + callTool("compare_builds", { action = "add", code = xml }) + local result = callTool("compare_builds", { action = "buy_similar", slot = "Helmet", mods = "all" }) + assert.is_truthy(result.url:find("^https://www%.pathofexile%.com/trade/search/Standard/")) + assert.is_truthy(#result.mods > 0) + assert.is_nil(main.popups[1]) + end) + + it("selects and removes comparisons", function() + callTool("compare_builds", { action = "add", current = true, name = "One" }) + callTool("compare_builds", { action = "add", current = true, name = "Two" }) + assert.are.equals(2, build.compareTab.activeCompareIndex) + local selected = callTool("compare_builds", { action = "select", index = 1, tree_set = 1 }) + assert.are.equals("One", selected.selected.label) + assert.are.equals(1, build.compareTab.activeCompareIndex) + local message = toolError("compare_builds", { action = "select", index = 1, item_set = "Nope" }) + assert.is_truthy(message:find("item set", 1, true)) + local removed = callTool("compare_builds", { action = "remove", index = 1 }) + assert.are.equals("One", removed.removed) + assert.are.equals(1, removed.remaining) + callTool("compare_builds", { action = "remove" }) + message = toolError("compare_builds", { action = "report" }) + assert.is_truthy(message:find("No comparison build", 1, true)) + end) + end) + + describe("compare_copy", function() + it("copies the tree so the allocations match", function() + local xml = otherBuildXML() + newBuild() + callTool("compare_builds", { action = "add", code = xml }) + local entry = build.compareTab.compareEntries[1] + local result = callTool("compare_copy", { what = "tree", use = true }) + assert.is_true(result.treeSet.active) + assert.are.equals(2, #build.treeTab.specList) + for nodeId in pairs(entry.spec.allocNodes) do + assert.is_truthy(build.spec.allocNodes[nodeId], "node " .. nodeId .. " not copied") + end + for nodeId in pairs(build.spec.allocNodes) do + assert.is_truthy(entry.spec.allocNodes[nodeId], "node " .. nodeId .. " extra") + end + assert.is_true(build:HasUnsavedChanges()) + end) + + it("copies and equips an item and copies socket groups", function() + local xml = otherBuildXML() + newBuild() + callTool("compare_builds", { action = "add", code = xml }) + local lifeBefore = build.calcsTab.mainOutput.Life + local result = callTool("compare_copy", { what = "item", slot = "Helmet", use = true }) + assert.is_true(result.equipped) + local slot = build.itemsTab.slots["Helmet"] + assert.is_truthy(build.itemsTab.items[slot.selItemId].name:find("Test Hat", 1, true)) + assert.is_truthy(build.calcsTab.mainOutput.Life > lifeBefore) + assert.is_truthy(#result.statChanges > 0) + result = callTool("compare_copy", { what = "skills", socket_groups = { 1 } }) + assert.are.equals(1, #build.skillsTab.socketGroupList) + assert.are.equals("Fireball", build.skillsTab.socketGroupList[1].gemList[1].nameSpec) + assert.are.equals("Test group", build.skillsTab.socketGroupList[1].label) + local message = toolError("compare_copy", { what = "skills", socket_groups = { 9 } }) + assert.is_truthy(message:find("no socket group 9", 1, true)) + end) + end) + + describe("party", function() + it("imports a party member's aura, changing the calculation, and clears it", function() + -- A support build exporting Clarity. + callTool("party", { action = "export_support", enabled = true }) + assert.is_true(build.importTab.controls.enablePartyExportBuffs.state) + build.skillsTab:PasteSocketGroup("Clarity 20/0 1\n") + build.buildFlag = true + runCallback("OnFrame") + local exported = callTool("party", { action = "export_support", enabled = true }) + assert.is_truthy(exported.exports.Aura) + local xml = build:SaveDB("code") + assert.is_truthy(xml:find("ExportedBuffs", 1, true)) + build.abortSave = true + + newBuild() + local regenBefore = build.calcsTab.mainOutput.ManaRegenRecovery + local destination = build.partyTab.controls.importCodeDestination.selIndex + -- Build files saved on Windows have CRLF line ends. + local result = callTool("party", { action = "import", code = xml:gsub("\n", "\r\n") }) + assert.are.equals("Clarity", result.auras[1].name) + assert.is_truthy(build.partyTab.actor.Aura.Aura.Clarity) + assert.is_truthy(build.calcsTab.mainOutput.ManaRegenRecovery > regenBefore) + assert.is_truthy(#result.statChanges > 0) + assert.are.equals(destination, build.partyTab.controls.importCodeDestination.selIndex) + assert.is_true(build:HasUnsavedChanges()) + + local got = callTool("party", { action = "get", include_text = true }) + assert.is_truthy(got.importedText.auras:find("Clarity", 1, true)) + callTool("party", { action = "disable_effects" }) + assert.are.equals(regenBefore, build.calcsTab.mainOutput.ManaRegenRecovery) + callTool("party", { action = "rebuild" }) + assert.is_truthy(build.calcsTab.mainOutput.ManaRegenRecovery > regenBefore) + result = callTool("party", { action = "clear" }) + assert.are.equals(0, #result.auras) + assert.are.equals("", build.partyTab.controls.editAuras.buf) + assert.are.equals(regenBefore, build.calcsTab.mainOutput.ManaRegenRecovery) + end) + + it("refuses a build without a party export", function() + local message = toolError("party", { action = "import", code = build:SaveDB("code") }) + assert.is_truthy(message:find("Export Support", 1, true)) + end) + end) + + describe("import_character", function() + local api, savedToken + + before_each(function() + api = main.api + savedToken = api.authToken + end) + + after_each(function() + api.authToken = savedToken + api.DownloadCharacter = nil + api.DownloadCharacterList = nil + end) + + it("fails when Path of Building is not logged in, and checks the name", function() + api.authToken = nil + local message = toolError("import_character", { action = "import", name = "testCharacter" }) + assert.is_truthy(message:find("Authorize with Path of Exile", 1, true)) + message = toolError("import_character", { action = "list" }) + assert.is_truthy(message:find("Authorize with Path of Exile", 1, true)) + api.authToken = "test" + message = toolError("import_character", { action = "import", name = "../league/x" }) + assert.is_truthy(message:find("character name", 1, true)) + end) + + it("imports a character into a new build", function() + local sample = readSampleCharacter() + api.authToken = "test" + local asked + api.DownloadCharacter = function(_, realm, name, callback) + asked = realm .. "/" .. name + callback(copyTable(sample)) + end + build.controls.characterLevel:SetText("50", true) + assert.is_truthy(toolError("import_character", { action = "import", name = "testCharacter" }):find("unsaved changes", 1, true)) + local result = callTool("import_character", { action = "import", name = "testCharacter", realm = "pc", discard_unsaved = true }) + assert.are.equals("pc/testCharacter", asked) + assert.are.equals("testCharacter", result.build.name) + assert.are.equals("Templar", build.spec.curClassName) + assert.are.equals("Hierophant", build.spec.curAscendClassName) + assert.are.equals(99, build.characterLevel) + assert.are.equals(2, build.spec.allocatedKeystoneCount) + assert.is_truthy(result.equippedItems > 5) + assert.is_truthy(#build.skillsTab.socketGroupList > 0) + assert.is_truthy(result.audit.itemsNotImported) + end) + + it("updates only the tree of the open build", function() + local sample = readSampleCharacter() + api.authToken = "test" + api.DownloadCharacter = function(_, _, _, callback) + callback(copyTable(sample)) + end + local result = callTool("import_character", { action = "import", name = "testCharacter", mode = "update", parts = "tree" }) + assert.are.equals("tree and jewels", result.imported) + assert.are.equals("Templar", build.spec.curClassName) + -- Only skills granted by the imported jewels, no gem groups. + for _, group in ipairs(build.skillsTab.socketGroupList) do + assert.is_truthy(group.source, "unexpected socket group " .. tostring(group.displayLabel)) + end + assert.is_nil(build.itemsTab.items[build.itemsTab.slots["Helmet"].selItemId]) + assert.is_true(build:HasUnsavedChanges()) + end) + + it("lists characters and explains API errors", function() + api.authToken = "test" + api.DownloadCharacterList = function(_, realm, callback) + callback({ characters = { + { name = "Zed", realm = "pc", class = "Witch", league = "Standard", level = 90 }, + { name = "amy", realm = "pc", class = "Slayer", league = "Mirage", level = 80 }, + } }) + end + local list = callTool("import_character", { action = "list" }) + assert.are.equals(2, #list.characters) + assert.are.equals("amy", list.characters[1].name) + list = callTool("import_character", { action = "list", league = "Standard" }) + assert.are.equals(1, #list.characters) + assert.are.equals("Zed", list.characters[1].name) + api.DownloadCharacter = function(_, _, _, callback) + callback(nil, "Response code: 404") + end + local message = toolError("import_character", { action = "import", name = "Nobody", mode = "update" }) + assert.is_truthy(message:find("no character 'Nobody'", 1, true)) + api.DownloadCharacter = function(_, _, _, callback) + callback(nil, "Response code: 429", os.time() + 30) + end + message = toolError("import_character", { action = "import", name = "Nobody", mode = "update" }) + assert.is_truthy(message:find("rate limiting", 1, true)) + end) + end) +end) diff --git a/spec/System/TestMcpItems_spec.lua b/spec/System/TestMcpItems_spec.lua new file mode 100644 index 00000000000..fac762b2b5d --- /dev/null +++ b/spec/System/TestMcpItems_spec.lua @@ -0,0 +1,301 @@ +local McpProtocol = LoadModule("Modules/McpProtocol") + +local PORT = 49290 +local TOKEN = "0123456789abcdef0123456789abcdef" + +local protocol + +local function request(method, params, opts) + opts = opts or { } + local message = { jsonrpc = "2.0", id = opts.id == nil and 1 or opts.id, method = method, params = params } + local headers = { + host = "127.0.0.1:" .. PORT, + authorization = "Bearer " .. TOKEN, + ["content-type"] = "application/json", + } + local response + protocol:HandleHttp({ + method = "POST", + path = "/mcp", + version = "1.1", + headers = headers, + body = McpProtocol.Encode(message), + }, function(r) + response = r + end) + assert.is_truthy(response, "no response") + local body = response.body ~= "" and McpProtocol.Decode(response.body) or nil + return response.status, body, response +end + +local function callTool(name, args, allowError) + local status, body = request("tools/call", { name = name, arguments = args or McpProtocol.Object() }) + assert.are.equals(200, status) + assert.is_nil(body.error) + if body.result.isError and not allowError then + error(name .. " failed: " .. tostring(body.result.content[1].text), 2) + end + return body.result.structuredContent, body.result +end + +local function toolError(name, args) + local _, result = callTool(name, args, true) + assert.is_true(result.isError, "expected an error from " .. name) + return result.content[1].text +end + +local HELMET = "Rarity: RARE\nTest Hat\nIron Hat\nQuality: 0\n+80 to maximum Life\n+40% to Fire Resistance\n" +local GLOVES = "Rarity: RARE\nTest Mitts\nRawhide Gloves\nQuality: 0\n+30 to maximum Life\n" +local FLASK = "Rarity: MAGIC\nSeething Divine Life Flask of Staunching\n" + +local function addItem(text) + build.itemsTab:CreateDisplayItemFromRaw(text, true) + build.itemsTab:AddDisplayItem() + runCallback("OnFrame") +end + +local function entryFor(list, slotName) + for _, entry in ipairs(list) do + if entry.slot == slotName then + return entry + end + end +end + +describe("MCP items tools", function() + before_each(function() + main.mcpServer.token = TOKEN + protocol = main.mcpServer:NewProtocol(PORT) + -- A build an earlier spec changed would be autosaved by Dev Mode when replaced; there is nowhere to save it here. + build.abortSave = true + while main.popups[1] do + main:ClosePopup() + end + newBuild() + end) + + after_each(function() + -- Dev Mode saves a changed build when the next test replaces it; there is nowhere to save it here. + build.abortSave = true + -- No test may leave one of PoB's dialogs open. + local popup = main.popups[1] + while main.popups[1] do + main:ClosePopup() + end + assert.is_nil(popup, popup and ("dialog left open: " .. tostring(popup.title))) + end) + + describe("items_get", function() + it("reports the equipped items as the Items tab holds them, and changes nothing", function() + addItem(HELMET) + addItem(FLASK) + build:ResetModFlags() + local itemsTab = build.itemsTab + local result = callTool("items_get") + local helmet = entryFor(result.equipped, "Helmet") + assert.are.equals(itemsTab.items[itemsTab.slots["Helmet"].selItemId].name, helmet.name) + assert.are.equals(itemsTab.slots["Helmet"].selItemId, helmet.id) + assert.is_truthy(table.concat(helmet.mods, "\n"):find("+80 to maximum Life", 1, true)) + local flask = entryFor(result.equipped, "Flask 1") + assert.are.equals(itemsTab.slots["Flask 1"].active and true or false, flask.active) + assert.is_truthy(isValueInArray(result.emptySlots, "Gloves")) + assert.are.equals(1, #result.itemSets) + assert.is_true(result.itemSets[1].active) + assert.are.equals(0, result.otherItemsPage.total) + + local detail = callTool("items_get", { detail = true, slot = "Helmet" }) + assert.are.equals(itemsTab.items[itemsTab.slots["Helmet"].selItemId]:BuildRaw(), detail.equipped[1].text) + assert.is_false(build:HasUnsavedChanges()) + end) + end) + + describe("items_equip", function() + it("equips pasted item text exactly as simulate predicted", function() + local simulated = callTool("simulate", { slot = "Helmet", item = HELMET, fields = { "Life", "FireResist" } }) + local equipped = callTool("items_equip", { action = "equip", slot = "Helmet", item = HELMET }) + assert.are.equals("Helmet", equipped.equippedIn) + assert.is_true(equipped.added) + assert.is_truthy(#equipped.statChanges > 0) + assert.are.equals(simulated.values.Life.after, build.calcsTab.mainOutput.Life) + assert.are.equals(simulated.values.FireResist.after, build.calcsTab.mainOutput.FireResist) + assert.is_true(build:HasUnsavedChanges()) + local shown = callTool("items_get", { slot = "Helmet" }) + assert.are.equals("Test Hat, Iron Hat", shown.equipped[1].name) + end) + + it("replaces, unequips, re-equips and removes items", function() + callTool("items_equip", { action = "equip", slot = "Gloves", item = GLOVES }) + local itemsTab = build.itemsTab + local id = itemsTab.slots["Gloves"].selItemId + local lifeWith = build.calcsTab.mainOutput.Life + local unequipped = callTool("items_equip", { action = "unequip", slot = "Gloves" }) + assert.are.equals("Test Mitts, Rawhide Gloves", unequipped.unequipped) + assert.are.equals(0, itemsTab.slots["Gloves"].selItemId) + assert.is_truthy(itemsTab.items[id]) + assert.is_true(build.calcsTab.mainOutput.Life < lifeWith) + local others = callTool("items_get") + assert.are.equals(1, others.otherItemsPage.total) + assert.are.equals(id, others.otherItems[1].id) + + -- By name, into its usual slot, as Ctrl+click does. + local again = callTool("items_equip", { action = "equip", item_ref = "Test Mitts" }) + assert.are.equals("Gloves", again.equippedIn) + assert.are.equals(id, itemsTab.slots["Gloves"].selItemId) + assert.are.equals(lifeWith, build.calcsTab.mainOutput.Life) + + local message = toolError("items_equip", { action = "equip", slot = "Helmet", item_ref = id }) + assert.is_truthy(message:find("cannot be equipped in Helmet", 1, true)) + + local removed = callTool("items_equip", { action = "remove", item_ref = id }) + assert.are.equals("Gloves", removed.wasEquippedIn) + assert.is_nil(itemsTab.items[id]) + assert.are.equals(0, itemsTab.slots["Gloves"].selItemId) + end) + + it("switches a flask on and off like its check box", function() + callTool("items_equip", { action = "equip", slot = "Flask 1", item = FLASK }) + local itemsTab = build.itemsTab + local flask = itemsTab.items[itemsTab.slots["Flask 1"].selItemId] + callTool("items_equip", { action = "set_active", slot = "Flask 1", active = false }) + assert.is_falsy(build.calcsTab.mainEnv.flasks[flask]) + local on = callTool("items_equip", { action = "set_active", slot = "Flask 1", active = true }) + assert.is_true(on.active) + assert.is_true(itemsTab.slots["Flask 1"].controls.activate.state) + assert.is_truthy(build.calcsTab.mainEnv.flasks[flask]) + callTool("items_equip", { action = "set_active", slot = "Flask 1", active = false }) + assert.is_falsy(build.calcsTab.mainEnv.flasks[flask]) + end) + end) + + describe("items_sets", function() + it("creates, renames, selects and deletes item sets", function() + local itemsTab = build.itemsTab + callTool("items_equip", { action = "equip", slot = "Helmet", item = HELMET }) + local created = callTool("items_sets", { action = "new", title = "Bossing" }) + assert.are.equals(2, #created.itemSets) + assert.are.equals("Bossing", created.itemSets[2].title) + callTool("items_sets", { action = "rename", set = "Bossing", title = "Mapping" }) + assert.are.equals("Mapping", itemsTab.itemSets[itemsTab.itemSetOrderList[2]].title) + local copied = callTool("items_sets", { action = "copy", set = 1, title = "Copy" }) + assert.are.equals(3, #copied.itemSets) + assert.are.equals(itemsTab.slots["Helmet"].selItemId, itemsTab.itemSets[itemsTab.itemSetOrderList[3]]["Helmet"].selItemId) + + local selected = callTool("items_sets", { action = "select", set = "Mapping" }) + assert.is_true(selected.itemSets[2].active) + assert.are.equals(itemsTab.itemSetOrderList[2], itemsTab.activeItemSetId) + -- The new set is empty. + assert.are.equals(0, itemsTab.slots["Helmet"].selItemId) + + local deleted = callTool("items_sets", { action = "delete", set = "Mapping" }) + assert.are.equals("Mapping", deleted.deleted) + assert.are.equals(2, #itemsTab.itemSetOrderList) + assert.are.equals(itemsTab.itemSetOrderList[1], itemsTab.activeItemSetId) + assert.is_truthy(itemsTab.slots["Helmet"].selItemId > 0) + local message = toolError("items_sets", { action = "new" }) + assert.is_truthy(message:find("title is required", 1, true)) + end) + end) + + describe("items_db_search", function() + it("finds uniques once the databases are loaded", function() + local frames = 0 + while (main.uniqueDB.loading or main.rareDB.loading) and frames < 1000 do + runCallback("OnFrame") + frames = frames + 1 + end + assert.is_nil(main.uniqueDB.loading) + local result = callTool("items_db_search", { search = "Tabula Rasa", include_text = true }) + assert.are.equals("Tabula Rasa, Simple Robe", result.items[1].name) + assert.is_truthy(result.items[1].text:find("Tabula Rasa", 1, true)) + local item = new("Item"):Item(result.items[1].text) + assert.are.equals("Simple Robe", item.baseName) + + local helmets = callTool("items_db_search", { slot = "Helmet", limit = 5, list_filters = true }) + assert.are.equals(5, #helmets.items) + assert.is_truthy(helmets.page.total > 5) + for _, entry in ipairs(helmets.items) do + assert.are.equals("Helmet", entry.type) + end + assert.is_truthy(isValueInArray(helmets.filters.slot, "Helmet")) + + local rares = callTool("items_db_search", { db = "rare", slot = "Ring", limit = 3 }) + assert.is_truthy(#rares.items > 0) + local message = toolError("items_db_search", { slot = "Nowhere" }) + assert.is_truthy(message:find("No slot matches", 1, true)) + end) + end) + + describe("items_craft", function() + it("crafts with the Items tab's controls and leaves the tab as it was", function() + local itemsTab = build.itemsTab + itemsTab:CreateDisplayItemFromRaw(GLOVES, true) + local shown = itemsTab.displayItem + -- What the user last picked in "Craft item..." and the affix sorting stay theirs. + itemsTab.lastCraftRaritySel = 2 + itemsTab.controls.craftingSorting.selIndex = 3 + + local bases = callTool("items_craft", { action = "bases", search = "Hubris" }) + assert.are.equals("Hubris Circlet", bases.bases[1].name) + + local created = callTool("items_craft", { action = "create", base = "Hubris Circlet", name = "Crafted Crown" }) + assert.is_truthy(created.item:find("Crafted: true", 1, true)) + assert.are.equals("RARE", created.rarity) + + local options = callTool("items_craft", { action = "affix", item = created.item, affix_type = "prefix" }) + assert.is_truthy(#options.options > 0) + local lifeLabel + for _, option in ipairs(options.options) do + if option.label:find("to maximum Life$") then + lifeLabel = option.label + end + end + assert.is_truthy(lifeLabel) + local withLife = callTool("items_craft", { action = "affix", item = created.item, affix_type = "prefix", modifier = lifeLabel, tier = 1, roll = 1 }) + assert.are.equals(1, withLife.affixes[1].tier) + assert.is_truthy(table.concat(withLife.mods, "\n"):find("to maximum Life", 1, true)) + + local bench = callTool("items_craft", { action = "modifier", item = withLife.item, source = "Crafting Bench" }) + assert.is_truthy(#bench.options > 0) + local custom = callTool("items_craft", { action = "modifier", item = withLife.item, custom = "+10% to Cold Resistance" }) + assert.is_truthy(table.concat(custom.mods, "\n"):find("+10% to Cold Resistance", 1, true)) + + local quality = callTool("items_craft", { action = "properties", item = custom.item, quality = 20, influences = { "Shaper" } }) + assert.is_truthy(quality.item:find("Shaper Item", 1, true)) + assert.is_truthy(quality.item:find("Quality: 20", 1, true)) + + local corrupted = callTool("items_craft", { action = "corrupt", item = quality.item, implicits = { } }) + assert.is_truthy(corrupted.item:find("Corrupted", 1, true)) + + local item = main.mcpServer:GetTools().T.ParseItem(build, corrupted.item, "Helmet") + assert.are.equals("Crafted Crown, Hubris Circlet", item.name) + -- Nothing was added to the build and the tab still shows its own item. + assert.are.equals(shown, itemsTab.displayItem) + assert.are.equals(2, itemsTab.lastCraftRaritySel) + assert.are.equals(3, itemsTab.controls.craftingSorting.selIndex) + assert.are.equals(0, #itemsTab.itemOrderList) + local message = toolError("items_craft", { action = "affix", item = corrupted.item, modifier = "no such modifier at all" }) + assert.is_truthy(message:find("modifier", 1, true)) + assert.are.equals(shown, itemsTab.displayItem) + assert.is_nil(main.popups[1]) + end) + end) + + describe("trade_query", function() + it("generates a weighted search without contacting the trade site", function() + callTool("items_equip", { action = "equip", slot = "Helmet", item = HELMET }) + local tradeQuery = build.itemsTab.tradeQuery + local generatorBefore = tradeQuery.tradeQueryGenerator + local weightsBefore = tradeQuery.statSortSelectionList and copyTable(tradeQuery.statSortSelectionList) + local result = callTool("trade_query", { slot = "Helmet", weights = { { stat = "Life", weight = 1 } }, league = "Standard" }) + assert.are.equals("armour.helmet", result.category) + assert.is_truthy(#result.weightedStats > 0) + assert.are.equals(result.query.stats[1].filters[1].id, result.weightedStats[1].id) + assert.are.equals("securable", result.query.status.option) + assert.are.equals(generatorBefore, tradeQuery.tradeQueryGenerator) + assert.are.same(weightsBefore, tradeQuery.statSortSelectionList) + assert.is_nil(main.popups[1]) + local message = toolError("trade_query", { slot = "Helmet", weights = { { stat = "Nonsense", weight = 1 } } }) + assert.is_truthy(message:find("Unknown weight stat", 1, true)) + end) + end) +end) diff --git a/spec/System/TestMcpServer_spec.lua b/spec/System/TestMcpServer_spec.lua index cb48c2264b2..6e4eb9c2263 100644 --- a/spec/System/TestMcpServer_spec.lua +++ b/spec/System/TestMcpServer_spec.lua @@ -71,6 +71,11 @@ describe("MCP server", function() before_each(function() main.mcpServer.token = TOKEN protocol = main.mcpServer:NewProtocol(PORT) + -- A build an earlier spec changed would be autosaved by Dev Mode when replaced; there is nowhere to save it here. + build.abortSave = true + while main.popups[1] do + main:ClosePopup() + end newBuild() end) diff --git a/spec/System/TestMcpSkillsConfig_spec.lua b/spec/System/TestMcpSkillsConfig_spec.lua new file mode 100644 index 00000000000..0f3964cb023 --- /dev/null +++ b/spec/System/TestMcpSkillsConfig_spec.lua @@ -0,0 +1,319 @@ +local McpProtocol = LoadModule("Modules/McpProtocol") + +local PORT = 49290 +local TOKEN = "0123456789abcdef0123456789abcdef" + +local protocol + +local function request(method, params) + local message = { jsonrpc = "2.0", id = 1, method = method, params = params } + local response + protocol:HandleHttp({ + method = "POST", + path = "/mcp", + version = "1.1", + headers = { + host = "127.0.0.1:" .. PORT, + authorization = "Bearer " .. TOKEN, + ["content-type"] = "application/json", + }, + body = McpProtocol.Encode(message), + }, function(r) + response = r + end) + assert.is_truthy(response, "no response") + local body = response.body ~= "" and McpProtocol.Decode(response.body) or nil + return response.status, body, response +end + +local function callTool(name, args, allowError) + local status, body = request("tools/call", { name = name, arguments = args or McpProtocol.Object() }) + assert.are.equals(200, status) + assert.is_nil(body.error) + if body.result.isError and not allowError then + error(name .. " failed: " .. tostring(body.result.content[1].text), 2) + end + return body.result.structuredContent, body.result +end + +local function toolError(name, args) + local _, result = callTool(name, args, true) + assert.is_true(result.isError, "expected an error from " .. name) + return result.content[1].text +end + +local function findBy(list, key, value) + for _, entry in ipairs(list) do + if entry[key] == value then + return entry + end + end +end + +describe("MCP skills, config and calcs tools", function() + before_each(function() + main.mcpServer.token = TOKEN + protocol = main.mcpServer:NewProtocol(PORT) + -- A build an earlier spec changed would be autosaved by Dev Mode when replaced; there is nowhere to save it here. + build.abortSave = true + while main.popups[1] do + main:ClosePopup() + end + newBuild() + end) + + after_each(function() + -- Dev Mode saves a changed build when the next test replaces it; there is nowhere to save it here. + build.abortSave = true + -- No test may leave one of PoB's dialogs open. + local popup = main.popups[1] + while main.popups[1] do + main:ClosePopup() + end + assert.is_nil(popup, popup and ("dialog left open: " .. tostring(popup.title))) + end) + + describe("skills", function() + it("reports the socket groups and gems as the Skills tab holds them", function() + build.skillsTab:PasteSocketGroup("Slot: Body Armour\nFireball 20/3 1\nControlled Destruction 18/0 DISABLED 1\n") + build.skillsTab:PasteSocketGroup("Label: Second\nArc 20/0 1\n") + runCallback("OnFrame") + local skills = callTool("skills_get") + assert.are.equals(#build.skillsTab.socketGroupList, #skills.groups) + for index, group in ipairs(build.skillsTab.socketGroupList) do + local reported = skills.groups[index] + assert.are.equals(group.displayLabel, reported.label) + assert.are.equals(#group.gemList, #reported.gems) + for gemIndex, gem in ipairs(group.gemList) do + assert.are.equals(gem.gemData.name, reported.gems[gemIndex].name) + assert.are.equals(gem.level, reported.gems[gemIndex].level) + assert.are.equals(gem.quality, reported.gems[gemIndex].quality) + assert.are.equals(gem.enabled, reported.gems[gemIndex].enabled) + end + end + assert.are.equals("Body Armour", skills.groups[1].slot) + assert.are.equals("support", skills.groups[1].gems[2].type) + assert.are.equals("active", skills.groups[1].gems[1].type) + assert.are.equals("Second", skills.groups[2].label) + assert.are.equals(build.mainSocketGroup, skills.mainSkill.group) + assert.are.equals("Fireball", skills.mainSkill.activeSkill) + assert.are.equals(1, #skills.skillSets) + -- One group with PoB's own details. + local one = callTool("skills_get", { group = "Second" }) + assert.are.equals(1, #one.groups) + assert.are.equals(2, one.groups[1].index) + assert.is_truthy(#one.groups[1].details > 0) + end) + + it("adds a pasted group and changes gem level and quality as the gem controls do", function() + local added = callTool("skills_edit", { action = "add_group", text = "Slot: Body Armour\nFireball 1/0 1\n" }) + assert.are.equals(1, #build.skillsTab.socketGroupList) + assert.are.equals("Fireball", added.group.gems[1].name) + local hitBefore = build.calcsTab.mainOutput.AverageHit + assert.is_truthy(hitBefore > 0) + local edited = callTool("skills_edit", { action = "edit_gem", group = 1, gem = "Fireball", level = 20, quality = 20 }) + local gem = build.skillsTab.socketGroupList[1].gemList[1] + assert.are.equals(20, gem.level) + assert.are.equals(20, gem.quality) + assert.are.equals(20, edited.group.gems[1].level) + assert.is_truthy(build.calcsTab.mainOutput.AverageHit > hitBefore) + assert.is_truthy(#edited.statChanges > 0) + assert.is_true(build:HasUnsavedChanges()) + -- PoB matches gem names as it does for pasted gems. + local message = toolError("skills_edit", { action = "add_group", text = "Fireball twenty\n" }) + assert.is_truthy(message:find("copy/paste format", 1, true)) + end) + + it("adds, disables and removes gems and groups", function() + callTool("skills_edit", { action = "add_group", text = "Fireball 20/0 1\n" }) + local result = callTool("skills_edit", { action = "add_gem", group = 1, gem = "Spell Echo Support", quality = 10 }) + local group = build.skillsTab.socketGroupList[1] + assert.are.equals(2, #group.gemList) + assert.are.equals("Spell Echo", group.gemList[2].gemData.name) + assert.are.equals(10, group.gemList[2].quality) + assert.are.equals(2, result.group.gems[2].index) + callTool("skills_edit", { action = "edit_gem", group = "Fireball", gem = 2, enabled = false }) + assert.is_false(group.gemList[2].enabled) + callTool("skills_edit", { action = "remove_gem", group = 1, gem = "Spell Echo" }) + assert.are.equals(1, #group.gemList) + callTool("skills_edit", { action = "edit_group", group = 1, enabled = false, label = "Main", include_in_full_dps = true }) + assert.is_false(group.enabled) + assert.is_true(group.includeInFullDPS) + assert.are.equals("Main", group.label) + callTool("skills_edit", { action = "edit_group", group = 1, slot = "Helmet" }) + assert.are.equals("Helmet", group.slot) + assert.is_truthy(toolError("skills_edit", { action = "edit_group", group = 1, slot = "Pocket" }):find("Body Armour", 1, true)) + assert.is_truthy(toolError("skills_edit", { action = "add_gem", group = 1, gem = "No Such Gem At All" }):find("Unrecognised", 1, true)) + callTool("skills_edit", { action = "remove_group", group = "Main" }) + assert.are.equals(0, #build.skillsTab.socketGroupList) + end) + + it("selects the main skill through the side bar's controls", function() + build.skillsTab:PasteSocketGroup("Fireball 20/0 1\n") + build.skillsTab:PasteSocketGroup("Arc 20/0 1\n") + runCallback("OnFrame") + assert.are.equals(1, build.mainSocketGroup) + local result = callTool("skills_edit", { action = "set_main", group = "Arc" }) + assert.are.equals(2, build.mainSocketGroup) + assert.are.equals("Arc", result.mainSkill.activeSkill) + assert.are.equals("Arc", build.calcsTab.mainEnv.player.mainSkill.activeEffect.grantedEffect.name) + assert.is_truthy(toolError("skills_edit", { action = "set_main", skill_part = 2 }):find("no skill part", 1, true)) + end) + + it("manages skill sets with the skill set list and its dialogs", function() + build.skillsTab:PasteSocketGroup("Fireball 20/0 1\n") + runCallback("OnFrame") + local created = callTool("skills_edit", { action = "copy_set", set = "Default", title = "Copy" }) + assert.are.equals(2, #build.skillsTab.skillSetOrderList) + assert.are.equals("Copy", build.skillsTab.skillSets[created.skillSet.id].title) + callTool("skills_edit", { action = "select_set", set = "Copy" }) + assert.are.equals(created.skillSet.id, build.skillsTab.activeSkillSetId) + assert.are.equals(1, #build.skillsTab.socketGroupList) + callTool("skills_edit", { action = "new_set", title = "Empty" }) + assert.are.equals(3, #build.skillsTab.skillSetOrderList) + callTool("skills_edit", { action = "delete_set", set = "Copy" }) + assert.are.equals(2, #build.skillsTab.skillSetOrderList) + assert.is_nil(build.skillsTab.skillSets[created.skillSet.id]) + end) + + it("sets the spectres as the spectre library does", function() + local skills = callTool("skills_get", { spectre_search = "a" }) + assert.is_truthy(skills.spectreLibrary.total > 0) + local spectre = skills.spectreLibrary.results[1] + local result = callTool("skills_edit", { action = "set_spectres", add_spectres = { spectre.id } }) + assert.are.same({ spectre.id }, build.spectreList) + assert.are.equals(spectre.id, result.spectres[1].id) + callTool("skills_edit", { action = "set_spectres", remove_spectres = { spectre.id } }) + assert.are.equals(0, #build.spectreList) + end) + + it("ranks supports as the gem selector's DPS sort and leaves the build unchanged", function() + build.skillsTab:PasteSocketGroup("Slot: Body Armour\nFireball 20/0 1\n") + runCallback("OnFrame") + build:ResetModFlags() + local xmlBefore = build:SaveDB("code") + local dpsBefore = build.calcsTab.mainOutput.CombinedDPS + local ranked = callTool("skills_rank_supports", { group = 1, search = "fire", limit = 50 }) + assert.are.equals("CombinedDPS", ranked.stat.field) + assert.is_truthy(#ranked.gems > 1) + for i = 2, #ranked.gems do + if ranked.gems[i - 1].canSupport == ranked.gems[i].canSupport then + assert.is_truthy(ranked.gems[i - 1].value >= ranked.gems[i].value) + end + end + assert.is_truthy(ranked.gems[1].change > 0) + assert.are.equals(xmlBefore, build:SaveDB("code")) + assert.are.equals(1, #build.skillsTab.socketGroupList[1].gemList) + build:ProcessBuildFlag() + assert.are.equals(dpsBefore, build.calcsTab.mainOutput.CombinedDPS) + assert.is_false(build:HasUnsavedChanges()) + end) + end) + + describe("config", function() + it("lists the options that differ from their defaults, and changes them", function() + local before = callTool("config_get") + assert.is_nil(findBy(before.options, "var", "usePowerCharges")) + local result = callTool("config_set", { options = { usePowerCharges = true, ["Is the enemy a Boss?"] = "Standard Boss", enemyFireResist = 30 } }) + assert.are.equals(3, #result.applied) + assert.are.equals(0, #result.rejected) + assert.is_true(build.configTab.input.usePowerCharges) + assert.are.equals("Boss", build.configTab.input.enemyIsBoss) + assert.are.equals(30, build.configTab.input.enemyFireResist) + local after = callTool("config_get") + assert.is_true(findBy(after.options, "var", "usePowerCharges").value) + assert.are.equals("Standard Boss", findBy(after.options, "var", "enemyIsBoss").value) + assert.are.equals(#before.options + 3, #after.options) + local searched = callTool("config_get", { search = "bandit" }) + local bandit = findBy(searched.options, "var", "bandit") + assert.are.equals("Kill all", bandit.value) + assert.is_truthy(#bandit.choices >= 4) + callTool("config_set", { reset = { "usePowerCharges", "enemyIsBoss" } }) + assert.is_false(build.configTab.input.usePowerCharges) + assert.are.equals("Pinnacle", build.configTab.input.enemyIsBoss) + end) + + it("rejects unknown options and invalid values with the valid choices", function() + local result = callTool("config_set", { options = { enemyIsBoss = "Nope", usePowerCharges = true, noSuchOption = 1, enemyLevel = "high" } }) + assert.are.equals(1, #result.applied) + assert.are.equals(3, #result.rejected) + local boss = findBy(result.rejected, "option", "enemyIsBoss") + assert.is_truthy(boss.choices) + assert.is_truthy(isValueInArray(boss.choices, "Standard Boss")) + assert.is_truthy(findBy(result.rejected, "option", "noSuchOption")) + assert.is_truthy(findBy(result.rejected, "option", "enemyLevel").reason:find("number", 1, true)) + local message = toolError("config_set", { options = { bandit = "Help Nobody" } }) + assert.is_truthy(message:find("Help Oak", 1, true)) + end) + + it("creates, selects and deletes config sets with the config set list", function() + local created = callTool("config_set", { set_action = "new", title = "Bossing" }) + assert.are.equals(2, #build.configTab.configSetOrderList) + local id = created.configSetChange.id + callTool("config_set", { set_action = "select", set = "Bossing", options = { usePowerCharges = true } }) + assert.are.equals(id, build.configTab.activeConfigSetId) + assert.is_true(build.configTab.configSets[id].input.usePowerCharges) + assert.is_falsy(build.configTab.configSets[1].input.usePowerCharges) + callTool("config_set", { set_action = "delete", set = id }) + assert.are.equals(1, #build.configTab.configSetOrderList) + assert.are.equals(1, build.configTab.activeConfigSetId) + end) + + it("appends custom modifiers and reports lines PoB does not recognise", function() + local lifeBefore = build.calcsTab.mainOutput.Life + local result = callTool("config_set", { custom_mods = "+100 to maximum Life" }) + assert.are.equals(lifeBefore + 100, build.calcsTab.mainOutput.Life) + assert.is_nil(result.customModifiers.unrecognised) + result = callTool("config_set", { custom_mods = "This is not a modifier" }) + assert.are.equals("+100 to maximum Life\nThis is not a modifier", build.configTab.configSets[1].customModsList[1].text) + assert.are.same({ "This is not a modifier" }, result.customModifiers.unrecognised) + local config = callTool("config_get") + assert.are.same({ "This is not a modifier" }, config.customModifiers[1].unrecognised) + callTool("config_set", { custom_mods = "", custom_mods_mode = "replace" }) + assert.are.equals(lifeBefore, build.calcsTab.mainOutput.Life) + end) + end) + + describe("calcs", function() + it("returns PoB's breakdown of a stat and puts the Calcs tab back", function() + build.skillsTab:PasteSocketGroup("Fireball 20/0 1\n") + build.skillsTab:PasteSocketGroup("Arc 20/0 1\n") + -- PoB only breaks Life down when something increases it. + build.configTab.configSets[1].customModsList[1].text = "10% increased maximum Life" + build.configTab:BuildModList() + build.buildFlag = true + runCallback("OnFrame") + local inputBefore = copyTable(build.calcsTab.input) + local result = callTool("calcs_breakdown", { stat = "Life" }) + local lines = result.breakdown[1].lines + assert.is_truthy(lines and #lines > 0) + local base = callTool("calcs_breakdown", { stat = "Total Base", section = "Life" }) + local sourceTable = base.breakdown[1] + assert.are.equals("table", sourceTable.type) + assert.is_truthy(isValueInArray(sourceTable.columns, "Source")) + assert.is_truthy(#sourceTable.rows > 0) + assert.are.equals("Life", result.cell.section) + assert.are.equals("Life", result.cell.output) + local rows = 0 + for _, section in ipairs(result.breakdown) do + rows = rows + #(section.rows or section.lines or { }) + end + assert.is_truthy(rows > 0) + local listed = callTool("calcs_breakdown", { filter = "total", section = "Life" }) + assert.is_truthy(#listed.cells >= 1) + assert.are.same({ "Life" }, listed.sections) + for _, cell in ipairs(listed.cells) do + assert.are.equals("Life", cell.section) + end + assert.is_truthy(findBy(listed.cells, "id", result.cell.id)) + -- Another skill and mode, then the tab is as it was. + local other = callTool("calcs_breakdown", { stat = "AverageHit", group = 2, mode = "UNBUFFED" }) + assert.are.equals("Arc", other.view.skill) + assert.are.equals("UNBUFFED", other.view.mode) + assert.are.same(inputBefore, build.calcsTab.input) + assert.are.equals("Fireball", build.calcsTab.calcsEnv.player.mainSkill.activeEffect.grantedEffect.name) + assert.are.equals(build.calcsTab.mainOutput.Life, build.calcsTab.calcsOutput.Life) + assert.is_truthy(toolError("calcs_breakdown", { stat = "No Such Stat Here" }):find("No Calcs tab cell", 1, true)) + end) + end) +end) diff --git a/spec/System/TestMcpTree_spec.lua b/spec/System/TestMcpTree_spec.lua new file mode 100644 index 00000000000..480bae06b27 --- /dev/null +++ b/spec/System/TestMcpTree_spec.lua @@ -0,0 +1,402 @@ +local McpProtocol = LoadModule("Modules/McpProtocol") + +local PORT = 49290 +local TOKEN = "0123456789abcdef0123456789abcdef" + +local protocol + +local function request(method, params) + local message = { jsonrpc = "2.0", id = 1, method = method, params = params } + local response + protocol:HandleHttp({ + method = "POST", + path = "/mcp", + version = "1.1", + headers = { + host = "127.0.0.1:" .. PORT, + authorization = "Bearer " .. TOKEN, + ["content-type"] = "application/json", + }, + body = McpProtocol.Encode(message), + }, function(r) + response = r + end) + assert.is_truthy(response, "no response") + local body = response.body ~= "" and McpProtocol.Decode(response.body) or nil + return response.status, body, response +end + +local function callTool(name, args, allowError) + local status, body = request("tools/call", { name = name, arguments = args or McpProtocol.Object() }) + assert.are.equals(200, status) + assert.is_nil(body.error) + if body.result.isError and not allowError then + error(name .. " failed: " .. tostring(body.result.content[1].text), 2) + end + return body.result.structuredContent, body.result +end + +local function toolError(name, args) + local _, result = callTool(name, args, true) + assert.is_true(result.isError, "expected an error from " .. name) + return result.content[1].text +end + +-- Synthetic Kurgal (Baleful Dominion) lookup table, as in TestAbyssTimelessJewel_spec. +local function uint16(value) + return string.char(value % 256, math.floor(value / 256) % 256) +end + +local function abyssModification(components) + local encoded = { string.char(#components) } + for _, component in ipairs(components) do + encoded[#encoded + 1] = string.char(component.type, component.id, #component.rolls) + for _, roll in ipairs(component.rolls) do + encoded[#encoded + 1] = uint16(roll < 0 and roll + 65536 or roll) + end + end + return table.concat(encoded) +end + +local function kurgalExampleData() + local affectedNodes = { + { id = 4367, modification = abyssModification({ { type = 1, id = 24, rolls = { 6 } } }) }, + { id = 15117, modification = abyssModification({ { type = 1, id = 19, rolls = { 8 } } }) }, + { id = 20528, modification = abyssModification({ { type = 2, id = 207, rolls = { -15 } } }) }, + { id = 21958, modification = abyssModification({ { type = 2, id = 211, rolls = { 12, 18 } } }) }, + } + local encoded = { "ABYS" .. string.char(1, 9) .. uint16(533) .. uint16(533) .. uint16(1), string.char(1, 60), uint16(61419), string.char(#affectedNodes) } + for _, affectedNode in ipairs(affectedNodes) do + encoded[#encoded + 1] = uint16(affectedNode.id) + encoded[#encoded + 1] = affectedNode.modification + end + return table.concat(encoded) +end + +-- The closest unallocated node of a type needing at least 'points' points. +local function findNode(nodeType, points, filter) + local found + for _, node in pairs(build.spec.nodes) do + if node.type == nodeType and not node.alloc and not node.ascendancyName and node.path and #node.path >= points + and (not filter or filter(node)) + and (not found or #node.path < #found.path or (#node.path == #found.path and node.id < found.id)) then + found = node + end + end + return assert(found, "no " .. nodeType .. " node found") +end + +local function idSet(list) + local set = { } + for _, entry in ipairs(list) do + set[entry.id] = true + end + return set +end + +describe("MCP tree tools", function() + before_each(function() + main.mcpServer.token = TOKEN + protocol = main.mcpServer:NewProtocol(PORT) + -- A build an earlier spec changed would be autosaved by Dev Mode when replaced; there is nowhere to save it here. + build.abortSave = true + while main.popups[1] do + main:ClosePopup() + end + newBuild() + end) + + after_each(function() + data.timelessJewelLUTs[9] = nil + build.abortSave = true + local popup = main.popups[1] + while main.popups[1] do + main:ClosePopup() + end + assert.is_nil(popup, popup and ("dialog left open: " .. tostring(popup.title))) + end) + + it("lists the tree tools with full descriptions", function() + local _, body = request("tools/list") + local byName = { } + for _, tool in ipairs(body.result.tools) do + byName[tool.name] = tool + end + for _, name in ipairs({ "tree_get", "tree_search", "tree_edit", "tree_specs", "tree_node_power", "tree_timeless_jewel", "tree_tattoos" }) do + assert.is_truthy(byName[name], name .. " is missing") + assert.is_truthy(#byName[name].description > 200, name .. " needs a fuller description") + end + assert.is_true(byName.tree_get.annotations.readOnlyHint) + assert.is_true(byName.tree_specs.annotations.destructiveHint) + assert.is_true(byName.tree_timeless_jewel.annotations.readOnlyHint) + end) + + it("reads the tree as PoB counts it", function() + local target = findNode("Notable", 3) + build.spec:AllocNode(target) + build.buildFlag = true + runCallback("OnFrame") + build:ResetModFlags() + local used, ascUsed = build.spec:CountAllocNodes() + + local tree = callTool("tree_get") + assert.are.equals("Scion", tree.class) + assert.are.equals(used, tree.points.passives) + assert.are.equals(ascUsed, tree.points.ascendancy) + assert.is_truthy(isValueInArray(tree.notables, target.dn)) + assert.are.equals(1, #tree.specs) + assert.is_true(tree.specs[1].current) + assert.are.equals(used, tree.specs[1].points) + assert.is_truthy(tree.pointCounter:find(tostring(used), 1, true)) + assert.is_truthy(tree.pointCounterTooltip[1]:find("Required Level", 1, true)) + assert.is_truthy(tree.url:match("^https://")) + assert.are.equals(0, tree.tattooCount) + + local nodes = callTool("tree_get", { detail = "nodes" }) + assert.are.equals(used, nodes.page.total) + for _, node in ipairs(nodes.nodes) do + assert.is_truthy(build.spec.allocNodes[node.id]) + end + -- Reading changes nothing. + assert.is_false(build:HasUnsavedChanges()) + end) + + it("searches with the Tree tab's search", function() + local target = findNode("Notable", 3) + local result = callTool("tree_search", { query = '"' .. target.dn .. '"', limit = 200 }) + assert.is_truthy(idSet(result.nodes)[target.id]) + for _, node in ipairs(result.nodes) do + if node.id == target.id then + assert.are.equals(#target.path, node.pointsNeeded) + assert.are.equals("notable", node.type) + assert.is_false(node.allocated) + end + end + + -- The same matches as PoB's own search function, with the filters applied. + local viewer = build.treeTab.viewer + local proxy = { searchParams = viewer:ParseSearchString("life") } + local expected = 0 + for _, node in pairs(build.spec.nodes) do + if node.type == "Keystone" and not node.ascendancyName and viewer.DoesNodeMatchSearchParams(proxy, node) then + expected = expected + 1 + end + end + result = callTool("tree_search", { query = "life", types = { "keystone" }, allocated = "unallocated" }) + assert.are.equals(expected, result.page.total) + + result = callTool("tree_search", { types = { "mastery" }, limit = 1 }) + assert.is_truthy(result.nodes[1].effects[1].id) + assert.is_true(result.nodes[1].effects[1].available) + end) + + it("allocates and removes nodes as clicks do", function() + local target = findNode("Normal", 3) + local pathLength = #target.path + local pathIds = { } + for _, node in ipairs(target.path) do + pathIds[node.id] = true + end + build:ResetModFlags() + local result = callTool("tree_edit", { allocate = { target.id, "No Such Passive" }, deallocate = { target.id } }) + local added = idSet(result.added) + assert.are.same(pathIds, added) + for id in pairs(pathIds) do + assert.is_truthy(build.spec.allocNodes[id]) + end + assert.are.equals(2, #result.failed) + assert.is_truthy(result.failed[1].reason:find("not allocated", 1, true)) + assert.is_truthy(result.failed[2].reason:find("No passive node is named", 1, true)) + assert.is_true(build:HasUnsavedChanges()) + assert.is_truthy(result.statChanges) + + -- Removing the first node of the path removes the rest with it. + local first + for id in pairs(pathIds) do + local node = build.spec.nodes[id] + if not first or #node.depends > #first.depends then + first = node + end + end + result = callTool("tree_edit", { deallocate = { first.id } }) + assert.are.same(pathIds, idSet(result.removed)) + assert.are.equals(pathLength - 1, #result.deallocated[1].alsoRemoved) + assert.are.equals(0, (build.spec:CountAllocNodes())) + end) + + it("chooses mastery effects through the mastery dialog", function() + local mastery, twin + for _, node in pairs(build.spec.nodes) do + if node.type == "Mastery" and node.masteryEffects and node.path and (not mastery or #node.path < #mastery.path) then + mastery = node + end + end + for _, node in pairs(build.spec.nodes) do + if node ~= mastery and node.type == "Mastery" and node.dn == mastery.dn and node.path then + twin = node + end + end + local effectId = mastery.masteryEffects[1].effect + local result = callTool("tree_edit", { masteries = { { node = mastery.id, effect = effectId } } }) + assert.are.equals(effectId, build.spec.masterySelections[mastery.id]) + assert.is_true(mastery.alloc) + assert.are.equals(1, #result.masteries) + assert.are.equals(0, #result.failed) + if twin then + result = callTool("tree_edit", { masteries = { { node = twin.id, effect = effectId } } }) + assert.is_truthy(result.failed[1].reason:find("already chosen", 1, true)) + assert.is_nil(build.spec.masterySelections[twin.id]) + end + -- Choosing it again changes nothing. + result = callTool("tree_edit", { masteries = { { node = mastery.id, effect = effectId } } }) + assert.is_nil(result.masteries) + end) + + it("changes class and ascendancy", function() + local result = callTool("tree_edit", { class = "Witch", ascendancy = "Necromancer" }) + assert.are.equals("Witch", build.spec.curClassName) + assert.are.equals("Necromancer", build.spec.curAscendClassName) + assert.are.equals("Necromancer", result.ascendancy) + local message = toolError("tree_edit", { class = "Nobody" }) + assert.is_truthy(message:find("Unknown class", 1, true)) + build:UpdateSecondaryAscendancyDropdown(true) + local drop = build.controls.secondaryAscendDrop + if drop.list[2] then + result = callTool("tree_edit", { secondary_ascendancy = drop.list[2].label }) + assert.are.equals(drop.list[2].ascendClassId, build.spec.curSecondaryAscendClassId) + else + message = toolError("tree_edit", { secondary_ascendancy = "Anything" }) + assert.is_truthy(message:find("no secondary ascendancies", 1, true)) + end + end) + + it("manages the tree list through PoB's list control", function() + local result = callTool("tree_specs", { action = "new", title = "Second" }) + assert.are.equals(2, #build.treeTab.specList) + assert.are.equals("Second", build.treeTab.specList[2].title) + assert.are.equals(2, result.index) + assert.are.equals(1, build.treeTab.activeSpec) + + callTool("tree_specs", { action = "rename", spec = "Second", title = "Renamed" }) + assert.are.equals("Renamed", build.treeTab.specList[2].title) + + local message = toolError("tree_specs", { action = "copy", spec = 1 }) + assert.is_truthy(message:find("title", 1, true)) + callTool("tree_specs", { action = "copy", spec = 1, title = "Copied" }) + assert.are.equals("Copied", build.treeTab.specList[3].title) + + result = callTool("tree_specs", { action = "select", spec = "Renamed" }) + assert.are.equals(2, build.treeTab.activeSpec) + assert.are.equals(build.treeTab.specList[2], build.spec) + assert.is_true(result.specs[2].current) + + result = callTool("tree_specs", { action = "delete", spec = 3 }) + assert.are.equals("Copied", result.deleted) + assert.are.equals(2, #build.treeTab.specList) + callTool("tree_specs", { action = "delete", spec = 1 }) + message = toolError("tree_specs", { action = "delete", spec = 1 }) + assert.is_truthy(message:find("only one tree", 1, true)) + assert.are.equals("Renamed", build.spec.title) + end) + + it("reports node power sorted as asked and restores the Tree tab's stat", function() + local calcsTab = build.calcsTab + local statBefore, depthBefore = calcsTab.powerStat, calcsTab.nodePowerMaxDepth + local result = callTool("tree_node_power", { stat = "Life", max_depth = 5, limit = 200 }) + assert.is_truthy(#result.nodes > 3) + assert.are.equals("Life", result.stat) + assert.is_truthy(#result.nodes > 0) + for i = 2, #result.nodes do + assert.is_true(result.nodes[i - 1].power >= result.nodes[i].power) + assert.is_false(result.nodes[i].allocated) + end + assert.are.equals(statBefore, calcsTab.powerStat) + assert.are.equals(depthBefore, calcsTab.nodePowerMaxDepth) + assert.is_true(calcsTab.powerBuildFlag) + + result = callTool("tree_node_power", { stat = "life", max_depth = 5, sort = "per_point", types = { "normal" }, limit = 200 }) + for i, node in ipairs(result.nodes) do + assert.are.equals("Normal", node.type) + if i > 1 then + assert.is_true(result.nodes[i - 1].perPoint >= node.perPoint) + end + end + local message = toolError("tree_node_power", { stat = "Offence/Defence" }) + assert.is_truthy(message:find("no power report", 1, true)) + end) + + it("finds a timeless jewel seed and leaves the finder's settings alone", function() + local parseAbyssJewel = select(4, LoadModule("Modules/DataAbyssJewelLookUpTableHelper")) + data.timelessJewelLUTs[9] = parseAbyssJewel(9, kurgalExampleData()) + build.timelessData.searchList = "something the user typed" + build:ResetModFlags() + local saved = copyTable(build.timelessData) + local savedTradeType = build.treeTab.tradeTypeIndex + + local options = callTool("tree_timeless_jewel", { action = "options", jewel_type = "Baleful Dominion" }) + assert.are.equals(9, options.jewelType.id) + local modIds = idSet(options.mods) + assert.is_truthy(modIds["abyss_hypnotic_notable_16"]) + local sockets = idSet(options.sockets) + assert.is_truthy(sockets[61419]) + assert.is_truthy(sockets.all) + + local result = callTool("tree_timeless_jewel", { + action = "search", + jewel_type = 9, + socket = 61419, + desired = { + { node = "abyss_hypnotic_small_attribute19", weight = 1, weight2 = 0 }, + { node = "abyss_hypnotic_notable_16", weight = 1, weight2 = 0 }, + }, + trade = { league = "Standard" }, + }) + assert.are.equals(1, result.resultCount) + assert.are.equals(533, result.results[1].seed) + assert.are.equals(23, result.results[1].total) + assert.are.equals(2, #result.results[1].gives) + assert.is_truthy(result.trade.links[1].url:match("^https://www%.pathofexile%.com/trade/search/Standard")) + assert.are.same({ 533 }, result.trade.links[1].seeds) + + assert.are.same(saved, build.timelessData) + assert.are.equals(savedTradeType, build.treeTab.tradeTypeIndex) + assert.is_false(build:HasUnsavedChanges()) + + local message = toolError("tree_timeless_jewel", { action = "search", jewel_type = 9, socket = 61419, desired = { { node = "No such modifier" } } }) + assert.is_truthy(message:find("is not a Baleful Dominion modifier", 1, true)) + assert.are.same(saved, build.timelessData) + end) + + it("applies and resets a tattoo through PoB's dialog", function() + local target + for _, node in pairs(build.spec.nodes) do + if node.type == "Normal" and node.dn == "Strength" and not node.ascendancyName and (not target or node.id < target.id) then + target = node + end + end + local treeTab = build.treeTab + local listing = callTool("tree_tattoos", { action = "list", node = target.id }) + assert.is_truthy(#listing.options > 0) + assert.are.equals(0, listing.tattooCount) + assert.is_nil(treeTab.defaultTattoo.Strength) + + local result = callTool("tree_tattoos", { action = "apply", node = target.id, tattoo = listing.options[1].id }) + assert.is_truthy(build.spec.hashOverrides[target.id]) + assert.are.equals(listing.options[1].name, result.applied.name) + assert.are.equals(1, result.tattooCount) + assert.is_nil(treeTab.defaultTattoo.Strength) + assert.is_falsy(treeTab.showLegacyTattoo) + assert.are.equals(1, callTool("tree_get").tattooCount) + + result = callTool("tree_tattoos", { action = "reset", node = target.id }) + assert.is_nil(build.spec.hashOverrides[target.id]) + assert.are.equals("Strength", build.spec.nodes[target.id].dn) + assert.are.equals(0, result.tattooCount) + + local message = toolError("tree_tattoos", { action = "reset", node = target.id }) + assert.is_truthy(message:find("has no tattoo", 1, true)) + local notable = findNode("Notable", 3, function(node) return not (node.sd[1] or ""):match("^%+30 to") end) + message = toolError("tree_tattoos", { action = "list", node = notable.id }) + assert.is_truthy(message:find("cannot be tattooed", 1, true)) + end) +end) diff --git a/src/Classes/CompareBuySimilar.lua b/src/Classes/CompareBuySimilar.lua index 099da211de4..a34f4a6a2e8 100644 --- a/src/Classes/CompareBuySimilar.lua +++ b/src/Classes/CompareBuySimilar.lua @@ -532,4 +532,7 @@ function M.openPopup(item, slotName, primaryBuild) main:OpenPopup(popupWidth, popupHeight, title, controls, "search", nil, "close") end +-- Shared with the MCP server (Modules/McpTools/Compare), which composes the same URL without the popup +M.buildURL = buildURL + return M diff --git a/src/Classes/CompareTab.lua b/src/Classes/CompareTab.lua index 7682fe7b02d..f3cc86163df 100644 --- a/src/Classes/CompareTab.lua +++ b/src/Classes/CompareTab.lua @@ -124,6 +124,8 @@ end ---@class CompareTab: ControlHost, Control local CompareTabClass = newClass("CompareTab", "ControlHost", "Control") +-- Shared with the MCP server's comparison report (Modules/McpTools/Compare) +CompareTabClass.matchFlags = matchFlags ---@param primaryBuild Build function CompareTabClass:CompareTab(primaryBuild) @@ -4680,6 +4682,10 @@ local function subSectionExtraMatches(subSecData, primaryActor, compareActor) return primaryExtraOk and compareExtraOk and tostring(primaryExtraText or "") == tostring(compareExtraText or "") end +-- Shared with the MCP server's comparison report (Modules/McpTools/Compare) +CompareTabClass.calcRowMatchesBetweenBuilds = calcRowMatchesBetweenBuilds +CompareTabClass.subSectionExtraMatches = subSectionExtraMatches + function CompareTabClass:DrawCalcs(vp, compareEntry) -- Use calcsEnv for both values and tooltips (has breakdown data + respects Calcs skill selection) local primaryEnv = self.primaryBuild.calcsTab.calcsEnv diff --git a/src/Classes/SkillsTab.lua b/src/Classes/SkillsTab.lua index 1a09ef95ad4..44d7b244f97 100644 --- a/src/Classes/SkillsTab.lua +++ b/src/Classes/SkillsTab.lua @@ -707,7 +707,7 @@ function SkillsTabClass:CopySocketGroup(socketGroup) end function SkillsTabClass:PasteSocketGroup(testInput) - local skillText = sanitiseText(Paste() or testInput) + local skillText = sanitiseText(testInput or Paste()) if skillText then local newGroup = { label = "", enabled = true, gemList = { } } local label = skillText:match("Label: (%C+)") diff --git a/src/Modules/McpTools.lua b/src/Modules/McpTools.lua index a6b240e69ca..e46420859f9 100644 --- a/src/Modules/McpTools.lua +++ b/src/Modules/McpTools.lua @@ -216,6 +216,17 @@ function T.Defer(starter, timeoutSeconds) return { mcpDeferred = starter, timeout = timeoutSeconds or 60 } end +--- Run fn(...) and pass its result, or its failure message, to a deferred +--- tool's resolve. Use it for work done in a callback PoB calls later (a +--- download finishing), where a T.Fail would otherwise escape into PoB. +function T.Settle(resolve, fn, ...) + local ok, result = pcall(fn, ...) + if ok then + return resolve(result) + end + resolve(nil, type(result) == "table" and result.mcpFailure or ("Path of Building raised an error: " .. tostring(result))) +end + --- A PoB tooltip stand-in that records its lines, for PoB functions that --- report through a tooltip (stat comparisons, for example). function T.LineCollector() diff --git a/src/Modules/McpTools/Build.lua b/src/Modules/McpTools/Build.lua index ad9a849dbc0..6898840186d 100644 --- a/src/Modules/McpTools/Build.lua +++ b/src/Modules/McpTools/Build.lua @@ -140,8 +140,8 @@ T.Tool { T.Tool { name = "builds_list", title = "List saved builds", - description = "Lists the builds saved in Path of Building's builds folder, with their class, ascendancy, level and last-edit time, " - .. "the same list the build screen shows. Without search it lists one folder (the top folder unless 'folder' is given); with " + description = "Lists the builds saved in Path of Building's builds folder, with their class, ascendancy and level, " + .. "the same list the build screen shows (sort 'edited' puts the most recently saved first). Without search it lists one folder (the top folder unless 'folder' is given); with " .. "search it looks through every folder, using PoB's own filter (words match the name, folder or class; 'class:Witch' matches " .. "the class or ascendancy only). Pass a build's 'path' to build_open to open it.", readOnly = true, @@ -175,7 +175,6 @@ T.Tool { class = entry.className, ascendancy = entry.ascendClassName ~= "None" and entry.ascendClassName or nil, level = entry.level, - edited = entry.modified and os.date("%Y-%m-%d %H:%M", entry.modified) or nil, }) end end @@ -254,11 +253,13 @@ T.Tool { if not isSuccess then return resolve(nil, s_format("Could not download the build from %s: %s", site.label, tostring(data))) end - -- The user may have changed something while the download ran. - T.CheckCanReplaceBuild(args) - local xml = T.DecodeBuildCode(data) - local build = T.SwitchToBuild(false, name or "Imported build", xml, false, link) - resolve({ opened = T.BuildSummary(build), source = site.label }) + T.Settle(resolve, function() + -- The user may have changed something while the download ran. + T.CheckCanReplaceBuild(args) + local xml = T.DecodeBuildCode(data) + local build = T.SwitchToBuild(false, name or "Imported build", xml, false, link) + return { opened = T.BuildSummary(build), source = site.label } + end) end) end, 60) else diff --git a/src/Modules/McpTools/Calcs.lua b/src/Modules/McpTools/Calcs.lua index f0ab46e9e89..e8a7bf829ac 100644 --- a/src/Modules/McpTools/Calcs.lua +++ b/src/Modules/McpTools/Calcs.lua @@ -1,6 +1,462 @@ -- Path of Building -- -- Module: MCP Tools - Calcs +-- The Calcs tab: its sections and cells (Modules/CalcSections), and the +-- breakdown PoB shows for a cell (CalcBreakdownControl). -- local T = ... +local t_insert = table.insert +local t_concat = table.concat + +local CALC_MODES = { "UNBUFFED", "BUFFED", "COMBAT", "EFFECTIVE" } +local MAX_TABLE_ROWS = 200 + +local function text(value) + if value == nil then + return nil + end + return (T.Clean(tostring(value)):gsub("^%s+", ""):gsub("%s+$", "")) +end + +local function normalise(value) + return (tostring(value or ""):lower():gsub("[^%w]", "")) +end + +-- The Calcs tab's own calculation, as CalcsTab:BuildOutput makes it, with the +-- refresh of its pinned breakdown. The side bar's calculation is not touched. +local function rebuildCalcsEnv(calcsTab) + calcsTab.calcsEnv = calcsTab.calcs.buildOutput(calcsTab.build, "CALCS") + calcsTab.calcsOutput = calcsTab.calcsEnv.player.output + if calcsTab.displayData then + calcsTab.controls.breakdown:SetBreakdownData() + calcsTab.controls.breakdown:SetBreakdownData(calcsTab.displayData, calcsTab.displayPinned) + end +end + +-- Run fn with the Calcs tab showing the skill, mode and actor asked for, then put +-- the tab's selection back (it is saved with the build) and recalculate it. +local function withCalcsView(build, args, fn) + local calcsTab = build.calcsTab + local skillsTab = build.skillsTab + local inputCopy = copyTable(calcsTab.input, true) + local changes = { } + local function change(t, key, value) + t_insert(changes, { t, key, t[key] }) + t[key] = value + end + local recalculated = false + local function recalculate() + recalculated = true + rebuildCalcsEnv(calcsTab) + end + local ok, result = pcall(function() + if args.group ~= nil then + local index = args.group + if type(index) ~= "number" then + index = isValueInArray(skillsTab.socketGroupList, T.Find(skillsTab.socketGroupList, args.group, function(group) + return group.displayLabel or group.label + end, "socket group")) + elseif not skillsTab.socketGroupList[index] then + T.Fail("There is no socket group %d (see skills_get).", index) + end + change(calcsTab.input, "skill_number", index) + recalculate() + end + local group = skillsTab.socketGroupList[calcsTab.input.skill_number] + if args.active_skill ~= nil then + local list = group and group.displaySkillListCalcs or { } + local index = args.active_skill + if type(index) ~= "number" then + local entries = { } + for i, activeSkill in ipairs(list) do + t_insert(entries, { index = i, name = activeSkill.activeEffect.grantedEffect.name }) + end + index = T.Find(entries, args.active_skill, function(entry) return entry.name end, "active skill").index + elseif not list[index] then + T.Fail("The socket group has %d active skill%s.", #list, #list == 1 and "" or "s") + end + change(group, "mainActiveSkillCalcs", index) + recalculate() + end + if args.skill_part ~= nil then + local activeSkill = group and group.displaySkillListCalcs and group.displaySkillListCalcs[group.mainActiveSkillCalcs or 1] + local parts = activeSkill and activeSkill.activeEffect.grantedEffect.parts + if not parts or #parts < 2 then + T.Fail("The Calcs tab's skill has no skill parts to choose.") + end + local index = args.skill_part + if type(index) ~= "number" then + local entries = { } + for i, part in ipairs(parts) do + t_insert(entries, { index = i, name = part.name }) + end + index = T.Find(entries, args.skill_part, function(entry) return entry.name end, "skill part").index + elseif not parts[index] then + T.Fail("The skill has %d parts.", #parts) + end + change(activeSkill.activeEffect.srcInstance, "skillPartCalcs", index) + recalculate() + end + if args.mode and args.mode ~= calcsTab.input.misc_buffMode then + change(calcsTab.input, "misc_buffMode", args.mode) + recalculate() + end + if args.minion ~= nil then + change(calcsTab.input, "showMinion", args.minion or nil) + if args.minion and not calcsTab.calcsEnv.minion then + T.Fail("The Calcs tab's skill has no minion, so there are no minion stats to show.") + end + end + return fn(calcsTab) + end) + for i = #changes, 1, -1 do + local entry = changes[i] + entry[1][entry[2]] = entry[3] + end + wipeTable(calcsTab.input) + for key, value in pairs(inputCopy) do + calcsTab.input[key] = value + end + if recalculated then + rebuildCalcsEnv(calcsTab) + end + if not ok then + error(result, 0) + end + return result +end + +-- What the Calcs tab is showing. +local function viewInfo(build, calcsTab) + local env = calcsTab.calcsEnv + local skill = env.player.mainSkill + local group = build.skillsTab.socketGroupList[calcsTab.input.skill_number] + local info = { + mode = calcsTab.input.misc_buffMode, + actor = calcsTab.input.showMinion and env.minion and "minion" or "player", + hasMinion = env.minion ~= nil, + group = calcsTab.input.skill_number, + groupLabel = group and text(group.displayLabel or group.label) or nil, + } + if skill and skill.activeEffect then + info.skill = text(skill.activeEffect.grantedEffect.name) + info.skillPart = skill.skillPartName and text(skill.skillPartName) or nil + end + return info +end + +-- A subsection whose first row has no label holds column headers (Physical, Lightning, ...). +local function columnHeaders(subSec) + local first = subSec.data[1] + if not first or first.label then + return nil + end + local headers = { } + for i, cell in ipairs(first) do + headers[i] = cell.format and (text(cell.format):gsub(":$", "")) or nil + end + return headers +end + +-- Every labelled cell of the Calcs tab, in the tab's order, and whether the tab +-- shows it for this build (the CheckFlag tests CalcSectionControl:UpdateSize makes). +local function collectCells(calcsTab) + local cells = { } + for _, section in ipairs(calcsTab.sectionList) do + local sectionShown = calcsTab:CheckFlag(section) + for subIndex, subSec in ipairs(section.subSection) do + local headers = columnHeaders(subSec) + for rowIndex, rowData in ipairs(subSec.data) do + if rowData.label then + local rowShown = sectionShown and calcsTab:CheckFlag(rowData) + for colIndex, colData in ipairs(rowData) do + if colData.format then + local breakdowns = { } + for _, sectionData in ipairs(colData) do + if sectionData.breakdown then + t_insert(breakdowns, sectionData.breakdown) + end + end + t_insert(cells, { + id = section.id .. "/" .. subIndex .. "/" .. rowIndex .. "/" .. colIndex, + section = section.id, + subsection = text(subSec.label), + row = text(rowData.label), + column = headers and headers[colIndex] or nil, + outputKey = colData.format:match("{%d*:?output:([%a%.]+)}"), + breakdowns = breakdowns, + hasBreakdown = colData[1] ~= nil, + shown = rowShown and calcsTab:CheckFlag(colData) and true or false, + colData = colData, + }) + end + end + end + end + end + end + return cells +end + +-- The names a cell answers to, strongest first: its id; the output it shows; +-- the breakdowns it shows; then its labels. +local function cellNames(cell) + local tiers = { { cell.id }, { }, { }, { } } + if cell.outputKey then + t_insert(tiers[2], cell.outputKey) + t_insert(tiers[2], (cell.outputKey:gsub("^%a+%.", ""))) + end + for _, name in ipairs(cell.breakdowns) do + t_insert(tiers[3], name) + t_insert(tiers[3], (name:gsub("^%a+%.", ""))) + end + local row, column, sub = cell.row or "", cell.column, cell.subsection or "" + if column then + t_insert(tiers[4], row .. " " .. column) + t_insert(tiers[4], column .. " " .. row) + t_insert(tiers[4], sub .. " " .. row .. " " .. column) + else + t_insert(tiers[4], row) + t_insert(tiers[4], sub .. " " .. row) + t_insert(tiers[4], cell.section .. " " .. row) + end + return tiers +end + +-- Every word of the filter must appear in one of the cell's names. +local function cellMatches(cell, filter) + local terms = { } + for term in tostring(filter):gmatch("%S+") do + if normalise(term) ~= "" then + t_insert(terms, normalise(term)) + end + end + if not terms[1] then + return true + end + for _, tier in ipairs(cellNames(cell)) do + for _, name in ipairs(tier) do + local n = normalise(name) + local all = true + for _, term in ipairs(terms) do + if not n:find(term, 1, true) then + all = false + break + end + end + if all then + return true + end + end + end + return false +end + +local function cellValue(calcsTab, cell) + if not cell.shown then + return nil + end + local actor = calcsTab.input.showMinion and calcsTab.calcsEnv.minion or calcsTab.calcsEnv.player + local ok, value = pcall(formatCalcStr, cell.colData.format, actor, cell.colData) + return ok and text(value) or nil +end + +local function publicCell(calcsTab, cell) + return { + id = cell.id, + section = cell.section, + subsection = cell.subsection, + row = cell.row, + column = cell.column, + value = cellValue(calcsTab, cell), + output = cell.outputKey, + hasBreakdown = cell.hasBreakdown, + shown = cell.shown, + } +end + +-- The breakdown PoB shows for a cell: CalcBreakdownControl:SetBreakdownData run +-- on a stand-in object, so the tab's own breakdown pane is left alone. +local function breakdownOf(calcsTab, cell) + local proxy = setmetatable({ + calcsTab = calcsTab, + sectionList = { }, + clearDisplayFunc = function() end, + }, common.classes.CalcBreakdownControl) + proxy:SetBreakdownData(cell.colData, false) + local sections = { } + for _, section in ipairs(proxy.sectionList) do + if section.type == "TEXT" then + local lines = { } + for _, line in ipairs(section.lines) do + t_insert(lines, text(line)) + end + t_insert(sections, { type = "lines", lines = lines }) + elseif section.type == "TABLE" then + -- The columns PoB draws: those with a value in some row. + local columns, keys = { }, { } + for _, col in ipairs(section.colList) do + for _, row in ipairs(section.rowList) do + if row[col.key] ~= nil then + t_insert(columns, text(col.label)) + t_insert(keys, col.key) + break + end + end + end + local rows = { } + for i, row in ipairs(section.rowList) do + if i > MAX_TABLE_ROWS then + break + end + local cells = { } + for c, key in ipairs(keys) do + cells[c] = row[key] ~= nil and text(row[key]) or "" + end + t_insert(rows, cells) + end + t_insert(sections, { + type = "table", + label = text(section.label), + footer = text(section.footer), + columns = columns, + rows = T.Array(rows), + truncated = #section.rowList > MAX_TABLE_ROWS and #section.rowList or nil, + }) + elseif section.type == "RADIUS" then + t_insert(sections, { type = "radius", radius = section.radius }) + end + end + return sections +end + +-- The cell a stat name means; fails with the closest cells when it is not clear. +local function findCell(calcsTab, cells, stat, sectionName) + local wanted = normalise(stat) + local sectionWanted = sectionName and normalise(sectionName) + local matches + for tier = 1, 4 do + local found = { } + for _, cell in ipairs(cells) do + if not sectionWanted or normalise(cell.section) == sectionWanted or normalise(cell.subsection) == sectionWanted then + for _, name in ipairs(cellNames(cell)[tier]) do + if normalise(name) == wanted then + t_insert(found, cell) + break + end + end + end + end + if found[1] then + matches = found + break + end + end + local function describe(list) + local names = { } + for _, cell in ipairs(list) do + if #names < 15 then + t_insert(names, cell.id .. " (" .. cell.section .. ": " .. (cell.row or "") .. (cell.column and (" " .. cell.column) or "") .. ")") + end + end + return t_concat(names, "; ") + end + if not matches then + local close = { } + for _, cell in ipairs(cells) do + if cell.shown and cellMatches(cell, stat) then + t_insert(close, cell) + end + end + T.Fail("No Calcs tab cell is called '%s'.%s", stat, close[1] and (" Similar: " .. describe(close)) or " List the cells with a filter to find it.") + end + -- Prefer cells the tab shows for this build; hidden ones have nothing to break down. + local shown = { } + for _, cell in ipairs(matches) do + if cell.shown then + t_insert(shown, cell) + end + end + local pool = shown[1] and shown or matches + if #pool > 1 then + T.Fail("'%s' matches several Calcs tab cells; give one of their ids as stat, or a section: %s", stat, describe(pool)) + end + return pool[1] +end + +T.Tool { + name = "calcs_breakdown", + title = "Calcs tab breakdown", + description = "Reads Path of Building's Calcs tab. Without 'stat' it lists the tab's sections and cells (section, row, column, the " + .. "value shown, whether it has a breakdown) matching 'filter' (words matched against labels and output names, for example 'crit chance' or " + .. "'fire resist'). With 'stat' (a cell id from the list, an output name such as 'Life' or 'AverageHit', or a label such as " + .. "'Life Total') it returns the breakdown PoB shows when hovering that cell: the formula lines, and the tables of sources and " + .. "modifiers (value, stat, source, source name...). The Calcs tab normally details the main skill in Effective DPS mode; " + .. "'group', 'active_skill', 'skill_part', 'mode' and 'minion' look at another skill, calculation mode or the minion, and the " + .. "tab's selection is put back afterwards. Nothing in the build changes.", + readOnly = true, + idempotent = true, + input = { + stat = { type = "string", maxLength = 100, description = "The cell to break down: id, output name or label." }, + section = { type = "string", maxLength = 100, description = "Only cells of this section or subsection (for example 'Life', 'Offence')." }, + filter = { type = "string", maxLength = 100, description = "Without stat: list only cells whose names contain all these words." }, + include_hidden = { type = "boolean", description = "Without stat: also list cells the tab hides for this build." }, + group = { type = { "integer", "string" }, description = "Socket group to detail (index or label). Default: the Calcs tab's current one." }, + active_skill = { type = { "integer", "string" }, description = "Active skill of that group (name or position)." }, + skill_part = { type = { "integer", "string" }, description = "Skill part (name or position), for skills with parts." }, + mode = { type = "string", enum = CALC_MODES, description = "Calculation mode: UNBUFFED, BUFFED, COMBAT or EFFECTIVE (the tab's default)." }, + minion = { type = "boolean", description = "Show the minion's stats instead of the player's." }, + limit = T.PageArgs(50).limit, + offset = T.PageArgs(50).offset, + }, + run = function(args) + local build = T.Build() + build:ProcessBuildFlag() + return withCalcsView(build, args, function(calcsTab) + local cells = collectCells(calcsTab) + if args.section and not args.stat then + local wanted = normalise(args.section) + local inSection = { } + for _, cell in ipairs(cells) do + if normalise(cell.section) == wanted or normalise(cell.subsection) == wanted then + t_insert(inSection, cell) + end + end + cells = inSection + end + local result = { view = viewInfo(build, calcsTab) } + if args.stat then + local cell = findCell(calcsTab, cells, args.stat, args.section) + result.cell = publicCell(calcsTab, cell) + if not cell.shown then + result.note = "The Calcs tab does not show this cell for this build, so it has no breakdown." + result.breakdown = T.Array({ }) + else + result.breakdown = T.Array(breakdownOf(calcsTab, cell)) + end + return result + end + local list, sections, seen = { }, { }, { } + for _, cell in ipairs(cells) do + if (cell.shown or args.include_hidden) and cellMatches(cell, args.filter or "") then + t_insert(list, cell) + if not seen[cell.section] then + seen[cell.section] = true + t_insert(sections, cell.section) + end + end + end + -- The sections the listed cells are in, in the tab's order. + result.sections = T.Array(sections) + local page, paging = T.Page(list, args, 50) + local cellsOut = { } + for _, cell in ipairs(page) do + t_insert(cellsOut, publicCell(calcsTab, cell)) + end + result.cells = T.Array(cellsOut) + result.page = paging + return result + end) + end, +} diff --git a/src/Modules/McpTools/Compare.lua b/src/Modules/McpTools/Compare.lua index 0ce233596db..efd4cfbd186 100644 --- a/src/Modules/McpTools/Compare.lua +++ b/src/Modules/McpTools/Compare.lua @@ -1,6 +1,1783 @@ -- Path of Building -- -- Module: MCP Tools - Compare +-- The Compare tab (comparison builds, their differences, the compare power +-- report, buy similar and the copy buttons), the Party tab, and character +-- import through Path of Building's own Path of Exile login. -- local T = ... +local t_insert = table.insert +local t_concat = table.concat +local t_sort = table.sort +local s_format = string.format +local m_max = math.max + +local tradeHelpers = require("Classes.TradeHelpers") +local buySimilar = require("Classes.CompareBuySimilar") +local configVisibility = require("Modules.ConfigVisibility") + +-- The views of the Compare tab a report can include. +local REPORT_SECTIONS = { "stats", "tree", "items", "skills", "config", "calcs" } +local DEFAULT_REPORT_SECTIONS = { "stats", "tree", "items", "skills", "config" } +-- The slots of the Compare tab's Items view (CompareTab:DrawItems). +local ITEM_BASE_SLOTS = { "Weapon 1", "Weapon 2", "Weapon 1 Swap", "Weapon 2 Swap", "Helmet", "Body Armour", "Gloves", + "Boots", "Amulet", "Ring 1", "Ring 2", "Belt", "Flask 1", "Flask 2", "Flask 3", "Flask 4", "Flask 5" } +-- Config option types the Compare tab's Config view shows (makeConfigControl in CompareTab). +local CONFIG_VIEW_TYPES = { check = true, count = true, integer = true, countAllowZero = true, float = true, list = true } +-- The power report's sortable columns (ComparePowerReportListControl:ReSort). +local POWER_SORT_COLUMNS = { category = 1, impact = 3, points = 4, per_point = 5 } +local POWER_CATEGORIES = { tree = "treeNodes", items = "items", skill_gems = "skillGems", support_gems = "supportGems", config = "config" } +-- The Buy Similar popup's realm and listed-status dropdowns (CompareBuySimilar). +local BUY_REALMS = { pc = "PC", sony = "PS4", xbox = "Xbox" } +local BUY_LISTED = { securable = 1, available = 2, online = 3, any = 4 } + +-- A path below the builds folder, refusing anything that could leave it. +local function buildFolderFile(relative) + relative = relative:gsub("\\", "/"):gsub("^/+", "") + if relative:match("%.%.") or relative:match(":") then + T.Fail("path must be a build file inside the builds folder, without '..' or a drive") + end + if not relative:lower():match("%.xml$") then + relative = relative .. ".xml" + end + return relative +end + +local function findLinkSite(link) + local site = T.FindBuildSite(link) + if not site then + local labels = { } + for _, entry in ipairs(buildSites.websiteList) do + t_insert(labels, entry.label) + end + T.Fail("Path of Building does not recognise that link. Supported sites: %s.", t_concat(labels, ", ")) + end + return site +end + +-- PoB reads build files in text mode, so on Windows the CRLF of its own saves +-- reaches it as LF; text handed over directly gets the same conversion. +local function normaliseNewlines(text) + return (text:gsub("\r\n", "\n")) +end + +local function socketGroupLabel(group, index) + local label = group.displayLabel or group.label + if not label or not label:match("%S") then + label = "Group " .. index + end + if group.slot then + label = label .. " (" .. group.slot .. ")" + end + return T.Clean(label) +end + +-- The skill the build (or comparison) is calculated for. +local function mainSkillName(calcsTab) + local env = calcsTab and calcsTab.mainEnv + local skill = env and env.player and env.player.mainSkill + if not skill or not skill.activeEffect then + return nil + end + return skill.activeEffect.grantedEffect.name .. (skill.skillPartName and (" (" .. skill.skillPartName .. ")") or "") +end + +local function setTitles(orderList, sets, activeId) + local list = { } + for index, id in ipairs(orderList or { }) do + local set = sets and sets[id] + t_insert(list, { index = index, title = T.Clean(set and set.title or "Default"), active = id == activeId or nil }) + end + return T.Array(list) +end + +------------------------------------------------------------------------------ +-- Compare tab +------------------------------------------------------------------------------ + +local function entryInfo(ct, entry, index) + local spec = entry.spec + local out = entry:GetOutput() or { } + local treeSets = { } + for i, title in ipairs(entry.treeTab:GetSpecList()) do + t_insert(treeSets, { index = i, title = T.Clean(title), active = i == entry.treeTab.activeSpec or nil }) + end + local groups = { } + for i, group in ipairs(entry.skillsTab.socketGroupList) do + t_insert(groups, { index = i, label = socketGroupLabel(group, i), enabled = group.enabled ~= false, main = i == entry.mainSocketGroup or nil }) + end + local used, ascUsed = spec:CountAllocNodes() + return { + index = index, + label = T.Clean(entry.label), + active = index == ct.activeCompareIndex, + class = spec.curClassName, + ascendancy = spec.curAscendClassId ~= 0 and spec.curAscendClassName or nil, + level = entry.characterLevel, + passivePointsUsed = used, + ascendancyPointsUsed = ascUsed, + mainSkill = mainSkillName(entry.calcsTab), + treeSets = T.Array(treeSets), + itemSets = setTitles(entry.itemsTab.itemSetOrderList, entry.itemsTab.itemSets, entry.itemsTab.activeItemSetId), + skillSets = setTitles(entry.skillsTab.skillSetOrderList, entry.skillsTab.skillSets, entry.skillsTab.activeSkillSetId), + configSets = setTitles(entry.configTab.configSetOrderList, entry.configTab.configSets, entry.configTab.activeConfigSetId), + socketGroups = T.Array(groups), + stats = { + Life = T.Round(out.Life), EnergyShield = T.Round(out.EnergyShield), Mana = T.Round(out.Mana), TotalEHP = T.Round(out.TotalEHP), + CombinedDPS = T.Round(out.CombinedDPS), FullDPS = T.Round(out.FullDPS), + }, + } +end + +-- A comparison by its number (default: the one the tab shows), recalculated if flagged. +local function compareEntryAt(build, index) + local ct = build.compareTab + if not ct.compareEntries[1] then + T.Fail("No comparison build is loaded; add one with compare_builds action 'add'.") + end + index = index or ct.activeCompareIndex + local entry = ct.compareEntries[index] + if not entry then + T.Fail("There is no comparison %d; they are numbered 1 to %d (see action 'list').", index, #ct.compareEntries) + end + -- CompareTab:Draw rebuilds a flagged comparison before using it. + if entry.buildFlag then + entry:Rebuild() + end + return entry, index +end + +-- CompareTab:ImportBuild, as its Import and Import from Folder popups call it. +local function addComparison(build, xml, label) + local ct = build.compareTab + local before = #ct.compareEntries + local ok, imported = pcall(ct.ImportBuild, ct, normaliseNewlines(xml), (T.Sanitise(label))) + if not ok then + T.Fail("Path of Building could not load that build for comparison: %s", tostring(imported)) + end + if not imported or #ct.compareEntries == before then + T.Fail("Path of Building could not load that build for comparison; check that it is a valid Path of Building build.") + end + return { added = entryInfo(ct, ct.compareEntries[#ct.compareEntries], #ct.compareEntries), count = #ct.compareEntries } +end + +-- Summary view: CompareTab:DrawSummary and DrawStatList. +local function compareStats(build, entry, onlyDifferences) + local ct = build.compareTab + local matchFlags = ct.matchFlags + local primaryCalcs, compareCalcs = build.calcsTab, entry.calcsTab + local pEnv, cEnv = primaryCalcs.mainEnv, compareCalcs.mainEnv + local pMinion = pEnv and pEnv.player and pEnv.player.mainSkill and pEnv.player.mainSkill.minion and pEnv.minion + local cMinion = cEnv and cEnv.player and cEnv.player.mainSkill and cEnv.player.mainSkill.minion and cEnv.minion + local pOut = pMinion and pEnv.minion.output or primaryCalcs.mainOutput + local cOut = cMinion and cEnv.minion.output or entry:GetOutput() + if not pOut or not cOut then + T.Fail("One of the builds has no calculated output.") + end + local displayStats = (pMinion or cMinion) and build.minionDisplayStats or build.displayStats + local pActor = pMinion and pEnv.minion or pEnv.player + local cActor = cMinion and cEnv.minion or cEnv.player + local pFlags = pActor and pActor.mainSkill and pActor.mainSkill.skillFlags or { } + local cFlags = cActor and cActor.mainSkill and cActor.mainSkill.skillFlags or { } + local rows = { } + for _, statData in ipairs(displayStats) do + if (not statData.stat and not statData.label) or statData.stat == "SkillDPS" or statData.hideStat then + -- Spacers, the multi-row SkillDPS and hidden stats are not listed. + elseif not matchFlags(statData.flag, statData.notFlag, pFlags) and not matchFlags(statData.flag, statData.notFlag, cFlags) then + -- Not relevant to either build's skill. + elseif statData.stat then + local pVal = pOut[statData.stat] or 0 + local cVal = cOut[statData.stat] or 0 + if statData.childStat then + pVal = type(pVal) == "table" and pVal[statData.childStat] or 0 + cVal = type(cVal) == "table" and cVal[statData.childStat] or 0 + end + if type(pVal) == "table" or type(cVal) == "table" then + pVal, cVal = 0, 0 + end + if (pVal ~= 0 or cVal ~= 0) and (not statData.condFunc or statData.condFunc(pVal, pOut) or statData.condFunc(cVal, cOut)) then + local fmt = statData.fmt or "d" + local multiplier = (statData.pc or statData.mod) and 100 or 1 + local diff = cVal - pVal + local differs = diff > 0.001 or diff < -0.001 + if differs or not onlyDifferences then + local row = { + label = T.Clean(statData.label or statData.stat), + stat = statData.stat, + primary = formatNumSep(s_format("%" .. fmt, pVal * multiplier)), + compare = formatNumSep(s_format("%" .. fmt, cVal * multiplier)), + } + if differs then + row.difference = formatNumSep(s_format("%+" .. fmt, diff * multiplier)) + if pVal ~= 0 then + row.difference = row.difference .. s_format(" (%+.1f%%)", cVal / pVal * 100 - 100) + end + row.compareIsBetter = (statData.lowerIsBetter and diff < 0) or (not statData.lowerIsBetter and diff > 0) + end + t_insert(rows, row) + end + end + elseif statData.label and statData.condFunc then + local pShown = statData.condFunc(pOut) and true or false + local cShown = statData.condFunc(cOut) and true or false + if (pShown or cShown) and (pShown ~= cShown or not onlyDifferences) then + t_insert(rows, { + label = T.Clean(statData.label), + primary = pShown and (statData.val or "") or "-", + compare = cShown and (statData.val or "") or "-", + }) + end + end + end + return { minionStats = (pMinion or cMinion) and true or false, rows = T.Array(rows) } +end + +local function capped(list, limit, sortFunc) + if sortFunc then + t_sort(list, sortFunc) + end + local out = { } + for i = 1, math.min(#list, limit) do + out[i] = list[i] + end + return T.Array(out), #list +end + +-- Tree view, overlay mode: the tab hands the comparison's spec to the open +-- build's tree view as compareSpec; PassiveTreeView:GetCompareNodeColor colours +-- nodes green (compared build only), red (open build only) or blue (both, but +-- a different mastery choice or jewel). +local function compareTree(build, entry, limit) + local spec, cSpec = build.spec, entry.spec + local viewer = build.treeTab.viewer + local function jewelName(jewel) + return jewel and T.Clean(jewel.title or jewel.name) or nil + end + local function nodeInfo(node, cNode) + local info = { id = node.id, name = node.dn, type = node.type, ascendancy = node.ascendancyName } + if node.type == "Mastery" then + info.primaryEffect = node.alloc and T.Clean(t_concat(node.sd or { }, " / ")) or nil + info.compareEffect = cNode and cNode.alloc and T.Clean(t_concat(cNode.sd or { }, " / ")) or nil + elseif node.type == "Socket" then + local pJewelId = spec.jewels[node.id] + info.primaryJewel = jewelName(pJewelId and build.itemsTab.items[pJewelId]) + info.compareJewel = jewelName(viewer:GetCompareJewel(node.id)) + end + return info + end + local compareOnly, primaryOnly, differs = { }, { }, { } + local shared = 0 + local savedCompareSpec = viewer.compareSpec + viewer.compareSpec = cSpec + local ok, err = pcall(function() + for nodeId, node in pairs(spec.nodes) do + local cNode = cSpec.nodes[nodeId] + local r, g, b = viewer:GetCompareNodeColor(node, cNode, spec, build, "same") + if r == 0 and g == 1 and b == 0 then + t_insert(compareOnly, nodeInfo(node, cNode)) + elseif r == 1 and g == 0 and b == 0 then + t_insert(primaryOnly, nodeInfo(node, cNode)) + elseif r == 0 and g == 0 and b == 1 then + t_insert(differs, nodeInfo(node, cNode)) + elseif node.alloc then + shared = shared + 1 + end + end + -- Nodes only the compared build has (its cluster jewel subgraphs), drawn green by the tree view. + for nodeId, cNode in pairs(cSpec.nodes) do + if not spec.nodes[nodeId] and cNode.alloc and cNode.type ~= "ClassStart" and cNode.type ~= "AscendClassStart" then + t_insert(compareOnly, { id = nodeId, name = cNode.dn, type = cNode.type, clusterJewelNode = true }) + end + end + end) + viewer.compareSpec = savedCompareSpec + if not ok then + error(err, 0) + end + local byName = function(a, b) + return tostring(a.name) < tostring(b.name) + end + local result = { sharedAllocated = shared } + result.compareOnly, result.compareOnlyCount = capped(compareOnly, limit, byName) + result.primaryOnly, result.primaryOnlyCount = capped(primaryOnly, limit, byName) + result.differs, result.differsCount = capped(differs, limit, byName) + for key, s in pairs({ primary = spec, compare = cSpec }) do + local used, ascUsed = s:CountAllocNodes() + result[key] = { + treeSet = T.Clean(s.title or "Default"), class = s.curClassName, + ascendancy = s.curAscendClassId ~= 0 and s.curAscendClassName or nil, + passivePointsUsed = used, ascendancyPointsUsed = ascUsed, + } + end + return result +end + +local function itemSummary(item) + if not item then + return nil + end + return { name = T.Clean(item.name), rarity = item.rarity } +end + +-- Mod lines with the Items view's expanded-mode markers (CompareTab:DrawItemExpanded): +-- '+' only on this side, '>' / '<' the same mod with a higher / lower value. +local function itemModLines(item, otherModMap) + local lines = { } + if not item then + return lines + end + for _, modList in ipairs({ item.enchantModLines or { }, item.scourgeModLines or { }, item.implicitModLines or { }, item.explicitModLines or { }, item.crucibleModLines or { } }) do + for _, modLine in ipairs(modList) do + if item:CheckModLineVariant(modLine) then + local formatted = itemLib.formatModLine(modLine) + if formatted then + local marker + local other = otherModMap[tradeHelpers.modLineTemplate(modLine.line)] + if not other then + marker = "+" + elseif other.line ~= modLine.line then + local mine = tradeHelpers.modLineValue(modLine.line) + if mine and other.value and mine > other.value then + marker = ">" + elseif mine and other.value and mine < other.value then + marker = "<" + end + end + t_insert(lines, (marker and (marker .. " ") or "") .. T.Clean(formatted)) + end + end + end + end + return T.Array(lines) +end + +-- The Equip button's hover tooltip in the Items view: the open build's stat +-- changes with the compared item in that slot. +local function equipStatChanges(build, slotName, item) + local calcFunc, calcBase = build.compareTab.calcs.getMiscCalculator(build) + local newItem = new("Item"):Item(item.raw) + newItem:NormaliseQuality() + local override = { repSlotName = slotName, repItem = newItem } + local pSlot = build.itemsTab.slots[slotName] + if pSlot and pSlot.nodeId and not build.spec.allocNodes[pSlot.nodeId] then + local node = build.spec.nodes[pSlot.nodeId] + if node then + override.addNodes = { [node] = true } + end + end + local collector = T.LineCollector() + build:AddStatComparesToTooltip(collector, calcBase, calcFunc(override), "") + return T.Array(collector.lines) +end + +-- Items view: CompareTab:DrawItems (gear slots, then jewel sockets). +local function compareItems(build, entry, onlyDifferences, expanded, statChanges) + local ct = build.compareTab + local baseSlots = { } + for _, slotName in ipairs(ITEM_BASE_SLOTS) do + t_insert(baseSlots, slotName) + end + if ct:ShouldShowRing3(entry) then + t_insert(baseSlots, 10, "Ring 3") + end + ct:AddAbyssSockets(entry, baseSlots, false) + local pEnv = build.calcsTab.mainEnv + local primaryHasRing3 = pEnv and pEnv.modDB:Flag(nil, "AdditionalRingSlot") + local pTab, cTab = build.itemsTab, entry.itemsTab + local function row(label, slotName, pItem, cItem, extra) + -- PoB's label calls items with the same name a match; whether they are + -- identical is decided on the full item text, as the tree view compares jewels. + local identical = (not pItem and not cItem) or (pItem and cItem and pItem:BuildRaw() == cItem:BuildRaw()) or false + if onlyDifferences and identical then + return + end + local r = { + slot = label, + status = T.Clean(tradeHelpers.getSlotDiffLabel(pItem, cItem)):gsub("^%((.*)%)$", "%1"), + identical = identical, + primary = itemSummary(pItem), + compare = itemSummary(cItem), + } + for k, v in pairs(extra or { }) do + r[k] = v + end + if expanded then + r.primaryMods = itemModLines(pItem, tradeHelpers.buildModMap(cItem)) + r.compareMods = itemModLines(cItem, tradeHelpers.buildModMap(pItem)) + end + -- No Equip button (and so no tooltip) where the open build lacks the slot. + if statChanges and cItem and cItem.raw and not identical and not r.missingSlotInPrimary then + r.equipStatChanges = equipStatChanges(build, slotName, cItem) + end + return r + end + local slots = { } + for _, slotName in ipairs(baseSlots) do + local pSlot, cSlot = pTab.slots[slotName], cTab.slots[slotName] + local pItem = pSlot and pTab.items[pSlot.selItemId] + local cItem = cSlot and cTab.items[cSlot.selItemId] + local r = row(slotName, slotName, pItem, cItem, { missingSlotInPrimary = (slotName == "Ring 3" and not primaryHasRing3) or nil }) + if r then + t_insert(slots, r) + end + end + local jewels = { } + for _, jEntry in ipairs(ct:GetJewelComparisonSlots(entry)) do + local r = row(T.Clean(jEntry.label), jEntry.pSlotName, jEntry.pItem, jEntry.cItem, { + socketNodeId = jEntry.nodeId, + primarySocketAllocated = jEntry.pNodeAllocated, + compareSocketAllocated = jEntry.cNodeAllocated, + }) + if r then + t_insert(jewels, r) + end + end + local function activeSet(tab) + local set = tab.itemSets[tab.activeItemSetId] + return T.Clean(set and set.title or "Default") + end + return { primaryItemSet = activeSet(pTab), compareItemSet = activeSet(cTab), slots = T.Array(slots), jewels = T.Array(jewels) } +end + +-- Skills view: CompareTab:DrawSkills. Socket groups are paired greedily by +-- the similarity of their gem names; within a pair common gems come first, +-- then gems only on that side ("additional"), then gems only on the other side +-- ("missing"). Imbued supports count as gems of their group. +local function compareSkills(build, entry, onlyDifferences) + local pSkillsTab, cSkillsTab = build.skillsTab, entry.skillsTab + local pGroups, cGroups = pSkillsTab.socketGroupList, cSkillsTab.socketGroupList + local imbuedCache = { } + local function imbuedGem(group, skillsTab) + if not group or not group.imbuedSupport then + return nil + end + if not imbuedCache[group] then + local grantedEffect = skillsTab.imbuedSupportBySlot and group.slot and skillsTab.imbuedSupportBySlot[group.slot] + if not grantedEffect then + local gemId = data.gemForBaseName and data.gemForBaseName[group.imbuedSupport:lower() .. " support"] + grantedEffect = gemId and data.gems[gemId] and data.gems[gemId].grantedEffect or nil + end + imbuedCache[group] = { grantedEffect = grantedEffect, nameSpec = group.imbuedSupport, level = 1, quality = 0, isImbuedSupport = true } + end + return imbuedCache[group] + end + local function gemName(gem) + return gem.grantedEffect and gem.grantedEffect.name or gem.nameSpec + end + local function gemsOf(group, skillsTab) + local gems = { } + if group then + for _, gem in ipairs(group.gemList or { }) do + t_insert(gems, gem) + end + t_insert(gems, imbuedGem(group, skillsTab)) + end + return gems + end + local function nameSet(group, skillsTab) + local set = { } + for _, gem in ipairs(gemsOf(group, skillsTab)) do + if gemName(gem) then + set[gemName(gem)] = true + end + end + return set + end + local pSets, cSets = { }, { } + for i, group in ipairs(pGroups) do + pSets[i] = nameSet(group, pSkillsTab) + end + for i, group in ipairs(cGroups) do + cSets[i] = nameSet(group, cSkillsTab) + end + local scored = { } + for pi = 1, #pGroups do + for ci = 1, #cGroups do + local inter, union, keys = 0, 0, { } + for k in pairs(pSets[pi]) do keys[k] = true end + for k in pairs(cSets[ci]) do keys[k] = true end + for k in pairs(keys) do + union = union + 1 + if pSets[pi][k] and cSets[ci][k] then + inter = inter + 1 + end + end + if union > 0 and inter > 0 then + t_insert(scored, { pIdx = pi, cIdx = ci, score = inter / union }) + end + end + end + t_sort(scored, function(a, b) return a.score > b.score end) + local pMatched, cMatched, pairList = { }, { }, { } + for _, pair in ipairs(scored) do + if not pMatched[pair.pIdx] and not cMatched[pair.cIdx] then + t_insert(pairList, pair) + pMatched[pair.pIdx], cMatched[pair.cIdx] = true, true + end + end + for i = 1, #pGroups do + if not pMatched[i] then t_insert(pairList, { pIdx = i }) end + end + for i = 1, #cGroups do + if not cMatched[i] then t_insert(pairList, { cIdx = i }) end + end + + local function gemEntry(gem, name, status) + local e = { name = name, status = status } + if gem then + e.level, e.quality = gem.level, gem.quality + e.enabled = gem.enabled ~= false + e.imbued = gem.isImbuedSupport or nil + end + return e + end + local out = { } + for _, pair in ipairs(pairList) do + local pGroup, cGroup = pair.pIdx and pGroups[pair.pIdx], pair.cIdx and cGroups[pair.cIdx] + local pSet, cSet = pair.pIdx and pSets[pair.pIdx] or { }, pair.cIdx and cSets[pair.cIdx] or { } + local pGems, cGems = gemsOf(pGroup, pSkillsTab), gemsOf(cGroup, cSkillsTab) + local pList, cList = { }, { } + local cByName, emitted = { }, { } + for _, gem in ipairs(cGems) do + local name = gemName(gem) + if name and pSet[name] and not cByName[name] then + cByName[name] = gem + end + end + for _, gem in ipairs(pGems) do + local name = gemName(gem) + if name and cSet[name] and not emitted[name] then + emitted[name] = true + t_insert(pList, gemEntry(gem, name, "common")) + t_insert(cList, gemEntry(cByName[name], name, "common")) + end + end + for _, gem in ipairs(pGems) do + if gemName(gem) and not cSet[gemName(gem)] then t_insert(pList, gemEntry(gem, gemName(gem), "additional")) end + end + for _, gem in ipairs(cGems) do + if gemName(gem) and not pSet[gemName(gem)] then t_insert(cList, gemEntry(gem, gemName(gem), "additional")) end + end + if pGroup and cGroup then + local pMissing, cMissing = { }, { } + for name in pairs(cSet) do if not pSet[name] then t_insert(pMissing, name) end end + for name in pairs(pSet) do if not cSet[name] then t_insert(cMissing, name) end end + t_sort(pMissing) + t_sort(cMissing) + for _, name in ipairs(pMissing) do t_insert(pList, gemEntry(nil, name, "missing")) end + for _, name in ipairs(cMissing) do t_insert(cList, gemEntry(nil, name, "missing")) end + end + -- A pair differs when the view would show something different in its columns. + local differs = not pGroup or not cGroup + for i, e in ipairs(pList) do + local c = cList[i] + if e.status ~= "common" or not c or c.level ~= e.level or c.quality ~= e.quality then + differs = true + end + end + for _, e in ipairs(cList) do + if e.status ~= "common" then differs = true end + end + if differs or not onlyDifferences then + t_insert(out, { + primaryGroup = pGroup and { index = pair.pIdx, label = socketGroupLabel(pGroup, pair.pIdx), enabled = pGroup.enabled ~= false, main = pair.pIdx == build.mainSocketGroup or nil } or nil, + compareGroup = cGroup and { index = pair.cIdx, label = socketGroupLabel(cGroup, pair.cIdx), enabled = cGroup.enabled ~= false, main = pair.cIdx == entry.mainSocketGroup or nil } or nil, + primaryGems = T.Array(pList), + compareGems = T.Array(cList), + differs = differs, + }) + end + end + local function activeSet(tab) + local set = tab.skillSets[tab.activeSkillSetId] + return T.Clean(set and set.title or "Default") + end + return { primarySkillSet = activeSet(pSkillsTab), compareSkillSet = activeSet(cSkillsTab), groups = T.Array(out) } +end + +-- Config view: the sections of CompareTab:RebuildConfigControls and the rows +-- LayoutConfigView lists (differences first; equal options only when relevant +-- to either build, or all but the excluded ones with show_all). +local function compareConfig(build, entry, onlyDifferences, showAll) + local ct = build.compareTab + local pInput, cInput = build.configTab.input, entry.configTab.input + local sections, current = { }, nil + local total = 0 + for _, varData in ipairs(ct.configOptions) do + if varData.section then + if varData.section ~= "Custom Modifiers" and varData.section ~= "Map Modifiers and Player Debuffs" then + current = { name = varData.section, diffs = { }, commons = { } } + t_insert(sections, current) + else + current = nil + end + elseif current and varData.var and CONFIG_VIEW_TYPES[varData.type] and (varData.type ~= "list" or varData.list) then + local pVal, cVal = ct:NormalizeConfigVals(varData, pInput[varData.var], cInput[varData.var]) + local row = { + option = varData.var, + label = T.Clean((varData.label or varData.var):gsub(":$", "")), + primary = T.Clean(ct:FormatConfigValue(varData, pInput[varData.var])), + compare = T.Clean(ct:FormatConfigValue(varData, cInput[varData.var])), + } + if tostring(pVal) ~= tostring(cVal) then + t_insert(current.diffs, row) + elseif not onlyDifferences then + local relevant = configVisibility.isRelevantForBuild(varData, build) or configVisibility.isRelevantForBuild(varData, entry) + if relevant or (showAll and not configVisibility.isShowAllExcluded(varData)) then + row.same = true + t_insert(current.commons, row) + end + end + end + end + local out = { } + for _, section in ipairs(sections) do + local rows = { } + for _, r in ipairs(section.diffs) do t_insert(rows, r) end + for _, r in ipairs(section.commons) do t_insert(rows, r) end + if rows[1] then + total = total + #section.diffs + t_insert(out, { section = section.name, differences = #section.diffs, rows = rows }) + end + end + local function activeSet(tab) + local set = tab.configSets[tab.activeConfigSetId] + return T.Clean(set and set.title or "Default") + end + return { primaryConfigSet = activeSet(build.configTab), compareConfigSet = activeSet(entry.configTab), differences = total, sections = T.Array(out) } +end + +-- Calcs view: CompareTab:DrawCalcs over Modules/CalcSections, with the tab's +-- own row and sub-section comparisons for "Show only differences". +local function compareCalcs(build, entry, onlyDifferences, filter, limit) + local ct = build.compareTab + local rowMatches = ct.calcRowMatchesBetweenBuilds + local extraMatches = ct.subSectionExtraMatches + local pEnv, cEnv = build.calcsTab.calcsEnv, entry.calcsTab.calcsEnv + if not pEnv or not cEnv then + T.Fail("The Calcs view has no calculation for one of the builds yet.") + end + local pActor = (build.calcsTab.input.showMinion and pEnv.minion) or pEnv.player + local cActor = (entry.calcsTab.input.showMinion and cEnv.minion) or cEnv.player + local needle = filter and filter:match("%S") and filter:lower() or nil + local function fmt(colData, actor) + local ok, str = pcall(formatCalcStr, colData.format, actor, colData) + return ok and str and T.Clean(tostring(str)) or nil + end + local sections, rowCount = { }, 0 + for _, secDef in ipairs(ct.calcSections) do + local id, subSections = secDef[2], secDef[5] + if build.calcsTab:CheckFlag(subSections[1].data, pActor) then + local subs = { } + for _, subSec in ipairs(subSections) do + local subMatches = not needle or tostring(id):lower():find(needle, 1, true) or tostring(subSec.label or ""):lower():find(needle, 1, true) + local rows = { } + for _, rowData in ipairs(subSec.data) do + if rowData.label and rowData[1] and rowData[1].format and rowCount < limit then + local pVisible = build.calcsTab:CheckFlag(rowData, pActor) + local cVisible = build.calcsTab:CheckFlag(rowData, cActor) + if pVisible or cVisible then + local keep = true + if onlyDifferences and pVisible and cVisible then + keep = not rowMatches(ct, rowData[1], pActor, cActor, entry) + end + local label = T.Clean(rowData.label) + if keep and (subMatches or label:lower():find(needle, 1, true)) then + t_insert(rows, { label = label, primary = fmt(rowData[1], pActor), compare = fmt(rowData[1], cActor) }) + rowCount = rowCount + 1 + end + end + end + end + if rows[1] or (onlyDifferences and subMatches and not extraMatches(subSec.data, pActor, cActor)) then + local sub = { label = T.Clean(subSec.label), rows = T.Array(rows) } + if subSec.data.extra then + local okP, pExtra = pcall(formatCalcStr, subSec.data.extra, pActor) + local okC, cExtra = pcall(formatCalcStr, subSec.data.extra, cActor) + if okP and okC then + sub.primaryExtra, sub.compareExtra = T.Clean(pExtra), T.Clean(cExtra) + end + end + t_insert(subs, sub) + end + end + if subs[1] then + t_insert(sections, { section = id, subSections = subs }) + end + end + end + return { rows = rowCount, truncated = rowCount >= limit or nil, sections = T.Array(sections) } +end + +-- Pick a set by its position (1-based) or its title. +local function pickSet(titles, value, what) + if type(value) == "number" then + if not titles[value] then + T.Fail("There is no %s %d; there are %d.", what, value, #titles) + end + return value + end + local list = { } + for i, title in ipairs(titles) do + t_insert(list, { index = i, title = title }) + end + return T.Find(list, value, function(e) return e.title end, what).index +end + +local function setTitleList(orderList, sets) + local titles = { } + for i, id in ipairs(orderList) do + titles[i] = T.Clean(sets[id] and sets[id].title or "Default") + end + return titles +end + +-- The comparison's selectors (CompareTab:InitControls): compareSpecSelect, +-- compareSkillSetSelect, compareItemSetSelect, compareConfigSetSelect, cmpSocketGroup. +local function selectComparison(build, args) + local ct = build.compareTab + local entry, index = compareEntryAt(build, args.index) + -- Validate every choice before changing anything. + local sel = { } + if args.tree_set ~= nil then + local titles = { } + for i, spec in ipairs(entry.treeTab.specList) do + titles[i] = T.Clean(spec.title or "Default") + end + sel.tree = pickSet(titles, args.tree_set, "tree set") + end + if args.skill_set ~= nil then + sel.skill = pickSet(setTitleList(entry.skillsTab.skillSetOrderList, entry.skillsTab.skillSets), args.skill_set, "skill set") + end + if args.item_set ~= nil then + sel.item = pickSet(setTitleList(entry.itemsTab.itemSetOrderList, entry.itemsTab.itemSets), args.item_set, "item set") + end + if args.config_set ~= nil then + sel.config = pickSet(setTitleList(entry.configTab.configSetOrderList, entry.configTab.configSets), args.config_set, "config set") + end + if args.main_socket_group ~= nil then + -- Socket groups belong to the skill set that will be active. + local groups = entry.skillsTab.socketGroupList + if sel.skill then + local skillSet = entry.skillsTab.skillSets[entry.skillsTab.skillSetOrderList[sel.skill]] + groups = skillSet and skillSet.socketGroupList or groups + end + if not groups[args.main_socket_group] then + T.Fail("The compared build has no socket group %d; it has %d (see action 'list').", args.main_socket_group, #groups) + end + end + -- The "Compare with" dropdown. + ct.activeCompareIndex = index + ct.treeSearchNeedsSync = true + ct:UpdateBuildSelector() + if sel.tree then + entry:SetActiveSpec(sel.tree) + -- SetActiveSpec changes the window title; the tab puts the open build's back. + build.spec:SetWindowTitleWithBuildClass() + end + if sel.skill then + entry:SetActiveSkillSet(entry.skillsTab.skillSetOrderList[sel.skill]) + end + if sel.item then + entry:SetActiveItemSet(entry.itemsTab.itemSetOrderList[sel.item]) + end + if sel.config then + entry.configTab:SetActiveConfigSet(entry.configTab.configSetOrderList[sel.config]) + entry.buildFlag = true + ct.configNeedsRebuild = true + end + if args.main_socket_group then + entry:SetMainSocketGroup(args.main_socket_group) + end + if entry.buildFlag then + entry:Rebuild() + end + return { selected = entryInfo(ct, entry, index) } +end + +local function powerMetrics() + local list = { } + for _, e in ipairs(data.powerStatList) do + if e.stat and not e.ignoreForNodes then + t_insert(list, e) + end + end + return list +end + +-- CompareTab:ComparePowerBuilder run to the end the way RunComparePowerReport +-- resumes it each frame; the rows are sorted and worded by the tab's own +-- ComparePowerReportListControl, which then shows the same report. +local function powerReport(build, args) + local ct = build.compareTab + local entry, index = compareEntryAt(build, args.index) + local metrics = powerMetrics() + local wanted = (args.metric or "Full DPS"):lower() + local powerStat + for _, e in ipairs(metrics) do + if e.stat:lower() == wanted or e.label:lower() == wanted then + powerStat = e + end + end + if not powerStat then + local names = { } + for _, e in ipairs(metrics) do + t_insert(names, e.label .. " (" .. e.stat .. ")") + end + T.Fail("Unknown metric '%s'. Metrics: %s", args.metric, t_concat(names, ", ")) + end + local categories = { } + if args.categories and args.categories[1] then + for _, key in pairs(POWER_CATEGORIES) do + categories[key] = false + end + for _, name in ipairs(args.categories) do + categories[POWER_CATEGORIES[name]] = true + end + else + for _, key in pairs(POWER_CATEGORIES) do + categories[key] = true + end + end + build:ProcessBuildFlag() + -- The builder adds and removes skills, config values and abyssal jewels on + -- the open build while it measures them; none of that is a change to keep. + local flags = { build.modFlag, build.itemsTab.modFlag, build.skillsTab.modFlag, build.configTab.modFlag } + local co = coroutine.create(function() + ct:ComparePowerBuilder(entry, powerStat, categories) + end) + local ok, err = true, nil + while ok and coroutine.status(co) ~= "dead" do + ok, err = coroutine.resume(co) + end + build.buildFlag = true + T.Recalculate(build) + build.modFlag, build.itemsTab.modFlag, build.skillsTab.modFlag, build.configTab.modFlag = flags[1], flags[2], flags[3], flags[4] + if not ok then + T.Fail("The power report failed: %s", tostring(err)) + end + -- Show the report in the tab, as choosing the metric there would. + ct.comparePowerStat = powerStat + ct.comparePowerCategories = categories + ct.comparePowerCompareId = entry + ct.comparePowerDirty = false + ct.comparePowerCoroutine = nil + ct.comparePowerProgress = 100 + ct.comparePowerListSynced = false + ct.controls.comparePowerStatSelect:SelByValue(powerStat.stat, "stat") + ct.controls.comparePowerTreeCheck.state = categories.treeNodes + ct.controls.comparePowerItemsCheck.state = categories.items + ct.controls.comparePowerGemsCheck.state = categories.skillGems + ct.controls.comparePowerSupportGemsCheck.state = categories.supportGems + ct.controls.comparePowerConfigCheck.state = categories.config + local listControl = ct.controls.comparePowerReportList + listControl:SetReport(powerStat, ct.comparePowerResults or { }) + local sortCol = POWER_SORT_COLUMNS[args.sort_by or "impact"] + if sortCol ~= 3 then + listControl:ReSort(sortCol) + end + local rows = { } + for i, r in ipairs(listControl.list) do + t_insert(rows, { + category = r.category, + name = T.Clean(r.name), + impact = T.Round(r.impact), + impactText = T.Clean(listControl:GetRowValue(3, i, r)), + percent = T.Round(r.impactPercent, 2), + points = r.pathDist, + perPoint = T.Round(r.perPoint), + nodeId = r.nodeId, + slot = r.slotName, + }) + end + local page, paging = T.Page(rows, args, 25) + local used = { } + for name, key in pairs(POWER_CATEGORIES) do + if categories[key] then + t_insert(used, name) + end + end + t_sort(used) + return { + comparison = index, + compareName = T.Clean(entry.label), + metric = { stat = powerStat.stat, label = powerStat.label }, + categories = used, + status = listControl.statusText, + rows = page, + page = paging, + } +end + +-- A compared item for the Items view's Copy / Equip / Buy buttons: a gear +-- slot name, or a jewel socket ("Jewel ", its label, or the node id). +-- Returns the item and the slot name both builds use for it. +local function comparedItem(build, entry, slot) + if not slot then + T.Fail("slot is required: a gear slot such as 'Helmet' or 'Ring 1', or a jewel socket from the report's jewels list.") + end + local cSlot = entry.itemsTab.slots[slot] + if cSlot and not cSlot.nodeId then + local item = entry.itemsTab.items[cSlot.selItemId] + if not item then + T.Fail("The compared build has nothing in %s.", slot) + end + return item, slot + end + local wanted = slot:lower() + for _, jEntry in ipairs(build.compareTab:GetJewelComparisonSlots(entry)) do + if jEntry.pSlotName:lower() == wanted or T.Clean(jEntry.label):lower() == wanted or tostring(jEntry.nodeId) == slot then + if not jEntry.cItem then + T.Fail("The compared build has no jewel in %s.", slot) + end + return jEntry.cItem, jEntry.pSlotName + end + end + T.Fail("Unknown slot '%s'. Use a gear slot (%s) or a jewel socket from the report's jewels list.", slot, t_concat(ITEM_BASE_SLOTS, ", ")) +end + +-- The Items view's "Buy" button opens CompareBuySimilar's popup, whose URL +-- builder turns the popup's choices into a trade search URL. Here stand-ins +-- for the popup's controls hold the requested choices (the popup's defaults +-- otherwise: nothing ticked, minimums prefilled with the item's values), so +-- the URL is composed without opening the popup or fetching the league list. +local function buySimilarUrl(build, args) + local entry, index = compareEntryAt(build, args.index) + local buildURL = buySimilar.buildURL + local item, slotName = comparedItem(build, entry, args.slot) + local isUnique = item.rarity == "UNIQUE" or item.rarity == "RELIC" + local modEntries = buySimilar.addModEntries(item, { + { list = item.enchantModLines, type = "enchant" }, + { list = item.implicitModLines, type = "implicit" }, + { list = item.explicitModLines, type = "explicit" }, + { list = item.scourgeModLines, type = "scourge" }, + }) + local defenceEntries = { } + if not isUnique and item.armourData and item.base and item.base.armour then + for _, def in ipairs({ { key = "Armour", label = "Armour", tradeKey = "ar" }, { key = "Evasion", label = "Evasion", tradeKey = "ev" }, + { key = "EnergyShield", label = "Energy Shield", tradeKey = "es" }, { key = "Ward", label = "Ward", tradeKey = "ward" } }) do + local val = item.armourData[def.key] + if val and val > 0 then + t_insert(defenceEntries, { label = def.label, value = val, tradeKey = def.tradeKey }) + end + end + end + local realm = BUY_REALMS[args.realm or "pc"] + local league = args.league and args.league:match("%S") and args.league or "Standard" + local function edit(value) + return { buf = value ~= nil and tostring(value) or "" } + end + local controls = { + realmDrop = { GetSelValue = function() return realm end }, + leagueDrop = { GetSelValue = function() return league end }, + listedDrop = { selIndex = BUY_LISTED[args.listed or "securable"] }, + } + if not isUnique then + controls.baseTypeCheck = { state = args.use_base_type == true } + controls.ilvlMin = edit(args.item_level_min) + controls.ilvlMax = edit(args.item_level_max) + end + local wantAll = args.mods == "all" + local wantedMods = { } + if type(args.mods) == "table" then + for _, i in ipairs(args.mods) do + if not modEntries[i] then + T.Fail("The item has no mod %d; its mods are numbered 1 to %d (call without mods to see them).", i, #modEntries) + end + wantedMods[i] = true + end + end + local modValues = args.mod_values or { } + local mods = { } + for i, e in ipairs(modEntries) do + local searchable = #e.tradeIds > 0 + local selected = searchable and (wantAll or wantedMods[i]) or false + local hasRange = not (e.isOption or e.needsExactValue) and e.value ~= nil + local minVal = (hasRange and e.value ~= 0) and e.value or nil + local maxVal + local override = modValues[tostring(i)] + if override then + minVal = override.min ~= nil and override.min or minVal + maxVal = override.max + end + controls["mod" .. i .. "Check"] = { state = selected } + controls["mod" .. i .. "Min"] = edit(minVal) + controls["mod" .. i .. "Max"] = edit(maxVal) + local lines = { } + for _, line in ipairs(e.formattedLines) do + t_insert(lines, T.Clean(line)) + end + t_insert(mods, { + index = i, type = e.type, text = t_concat(lines, " + "), searchable = searchable, selected = selected, + min = hasRange and minVal or nil, max = hasRange and maxVal or nil, + }) + end + local wantAllDef = args.defences == "all" + local wantedDef = { } + if type(args.defences) == "table" then + for _, name in ipairs(args.defences) do + wantedDef[name:lower()] = true + end + end + local defences = { } + for i, def in ipairs(defenceEntries) do + local selected = wantAllDef or wantedDef[def.label:lower()] or wantedDef[def.tradeKey] or false + controls["def" .. i .. "Check"] = { state = selected } + controls["def" .. i .. "Min"] = edit(math.floor(def.value)) + controls["def" .. i .. "Max"] = edit(nil) + t_insert(defences, { name = def.label, value = def.value, selected = selected }) + end + local ok, url = pcall(buildURL, item, slotName, controls, modEntries, defenceEntries, isUnique) + if not ok then + T.Fail("Path of Building could not compose the trade URL: %s", tostring(url)) + end + return { + comparison = index, + item = itemSummary(item), + slot = slotName, + url = url, + realm = args.realm or "pc", + league = league, + mods = T.Array(mods), + defences = T.Array(defences), + note = "Nothing was opened or searched; give the URL to the user to open in a browser.", + } +end + +T.Tool { + name = "compare_builds", + title = "Compare builds", + description = "Path of Building's Compare tab: load other builds next to the open one and see how they differ. Actions: 'add' loads " + .. "a comparison build from exactly one of path (a saved build, as builds_list returns), code (a build code or build XML), " + .. "link (a build link; PoB downloads it) or current (a copy of the open build, to try changes against); 'list' shows the " + .. "loaded comparisons with their tree/item/skill/config sets and socket groups; 'select' makes one active and picks its " + .. "sets or main socket group; 'remove' drops one; 'report' returns what the tab shows as different (side-bar stats, " + .. "passive tree nodes, items per slot, socket groups, config options, optionally calcs rows; only differences unless " + .. "only_differences is false); 'power_report' measures, for one metric, how much each thing the compared build has and the " + .. "open one lacks (passives, items, gem groups, supports, config values) would change the open build, and shows it in the tab; " + .. "'buy_similar' composes the trade search URL of the Buy button for a compared item (nothing is opened or fetched). " + .. "Comparisons are not saved with the build and do not mark it unsaved; to copy something across use compare_copy.", + destructive = true, + openWorld = true, + input = { + action = { type = "string", enum = { "add", "list", "select", "remove", "report", "power_report", "buy_similar" }, description = "What to do." }, + index = { type = "integer", minimum = 1, description = "Comparison number (from 'list'). Default: the one the tab shows." }, + path = { type = "string", description = "add: a build file in the builds folder, for example 'Guides/Witch.xml'." }, + code = { type = "string", description = "add: a build code or build XML." }, + link = { type = "string", description = "add: a build link (pobb.in, pob.codes, poe.ninja, Maxroll, pastebin, ...)." }, + current = { type = "boolean", description = "add: a copy of the open build as it is now, unsaved changes included." }, + name = { type = "string", maxLength = 100, description = "add: the name the tab shows for it." }, + tree_set = { type = { "integer", "string" }, description = "select: tree set of the comparison, by position or title." }, + item_set = { type = { "integer", "string" }, description = "select: item set, by position or title." }, + skill_set = { type = { "integer", "string" }, description = "select: skill set, by position or title." }, + config_set = { type = { "integer", "string" }, description = "select: config set, by position or title." }, + main_socket_group = { type = "integer", minimum = 1, description = "select: the comparison's main socket group (its number in 'list')." }, + sections = { type = "array", items = { type = "string", enum = REPORT_SECTIONS }, maxItems = 6, description = "report: sections to include (default stats, tree, items, skills, config; calcs is long)." }, + only_differences = { type = "boolean", description = "report: list only what differs (default true)." }, + item_mods = { type = "boolean", description = "report: list each item's mod lines, marked '+' (only this side), '>' or '<' (higher or lower value)." }, + item_stat_changes = { type = "boolean", description = "report: for each differing item, the open build's stat changes if it equipped the compared one (slower)." }, + config_show_all = { type = "boolean", description = "report with only_differences false: also list equal options not relevant to either build." }, + calcs_filter = { type = "string", description = "report: only calcs rows whose section or label contains this text." }, + limit = { type = "integer", minimum = 1, maximum = 500, description = "report: most nodes per tree list and calcs rows (default 100); power_report: rows per page (default 25)." }, + offset = T.PageArgs(25).offset, + metric = { type = "string", description = "power_report: the stat to measure, by name or label, for example 'Full DPS', 'Life', 'TotalEHP' (default Full DPS)." }, + categories = { type = "array", items = { type = "string", enum = { "tree", "items", "skill_gems", "support_gems", "config" } }, maxItems = 5, description = "power_report: what to measure (default all)." }, + sort_by = { type = "string", enum = { "impact", "category", "points", "per_point" }, description = "power_report: row order (default impact)." }, + slot = { type = "string", description = "buy_similar: the compared item's slot, for example 'Helmet', 'Ring 2', or a jewel socket." }, + league = { type = "string", description = "buy_similar: trade league (default Standard)." }, + realm = { type = "string", enum = { "pc", "xbox", "sony" }, description = "buy_similar: realm (default pc)." }, + listed = { type = "string", enum = { "securable", "available", "online", "any" }, description = "buy_similar: listing status (default securable = instant buyout)." }, + use_base_type = { type = "boolean", description = "buy_similar: search the item's base type only." }, + item_level_min = { type = "integer", minimum = 1, maximum = 100, description = "buy_similar: minimum item level." }, + item_level_max = { type = "integer", minimum = 1, maximum = 100, description = "buy_similar: maximum item level." }, + mods = { anyOf = { { type = "string", enum = { "all" } }, { type = "array", items = { type = "integer", minimum = 1 }, maxItems = 50 } }, description = "buy_similar: mods to search for, by their number in the result, or 'all'. Default none (category only)." }, + mod_values = { type = "object", additionalProperties = { type = "object", properties = { min = { type = "number" }, max = { type = "number" } }, additionalProperties = false }, description = "buy_similar: per mod number (as a string key) its min/max, replacing the item's own value as minimum." }, + defences = { anyOf = { { type = "string", enum = { "all" } }, { type = "array", items = { type = "string" }, maxItems = 4 } }, description = "buy_similar: defences to require at least the item's value of (Armour, Evasion, Energy Shield, Ward), or 'all'." }, + }, + required = { "action" }, + run = function(args) + local build = T.Build() + local ct = build.compareTab + local action = args.action + if action == "add" then + local sources = 0 + for _, key in ipairs({ "path", "code", "link" }) do + if args[key] ~= nil then + sources = sources + 1 + end + end + if args.current then + sources = sources + 1 + end + if sources ~= 1 then + T.Fail("Give exactly one of path, code, link or current.") + end + if args.path then + local relative = buildFolderFile(args.path) + local file = io.open(main.buildPath .. relative, "r") + if not file then + T.Fail("No build file '%s' in the builds folder; use builds_list to find it.", relative) + end + local xml = file:read("*a") + file:close() + return addComparison(build, xml, args.name or relative:match("([^/]+)%.[xX][mM][lL]$")) + elseif args.code then + return addComparison(build, T.DecodeBuildCode(args.code), args.name or "Imported build") + elseif args.current then + build:ProcessBuildFlag() + return addComparison(build, build:SaveDB("code"), args.name or ("Copy of " .. (build.buildName or "build"))) + end + local link = args.link:gsub("^%s+", ""):gsub("%s+$", "") + local site = findLinkSite(link) + return T.Defer(function(resolve) + buildSites.DownloadBuild(link, site, function(isSuccess, data) + if not isSuccess then + return resolve(nil, s_format("Could not download the build from %s: %s", site.label, tostring(data))) + end + T.Settle(resolve, function() + local result = addComparison(T.Build(), T.DecodeBuildCode(data), args.name or ("Imported from " .. site.label)) + result.source = site.label + return result + end) + end) + end, 60) + elseif action == "list" then + local entries = { } + for i, entry in ipairs(ct.compareEntries) do + if entry.buildFlag then + entry:Rebuild() + end + t_insert(entries, entryInfo(ct, entry, i)) + end + return { + primary = { name = build.buildName, class = build.spec.curClassName, level = build.characterLevel, mainSkill = mainSkillName(build.calcsTab) }, + active = ct.activeCompareIndex > 0 and ct.activeCompareIndex or nil, + comparisons = T.Array(entries), + } + elseif action == "select" then + return selectComparison(build, args) + elseif action == "remove" then + local entry, index = compareEntryAt(build, args.index) + ct:RemoveBuild(index) + return { removed = T.Clean(entry.label), remaining = #ct.compareEntries, active = ct.activeCompareIndex > 0 and ct.activeCompareIndex or nil } + elseif action == "report" then + local entry, index = compareEntryAt(build, args.index) + build:ProcessBuildFlag() + local onlyDifferences = args.only_differences ~= false + local limit = args.limit or 100 + local wanted = { } + for _, name in ipairs(args.sections and args.sections[1] and args.sections or DEFAULT_REPORT_SECTIONS) do + wanted[name] = true + end + local result = { + comparison = index, + primaryName = T.Clean(ct:GetShortBuildName(build.buildName)), + compareName = T.Clean(entry.label), + primaryLevel = build.characterLevel, + compareLevel = entry.characterLevel, + primaryMainSkill = mainSkillName(build.calcsTab), + compareMainSkill = mainSkillName(entry.calcsTab), + onlyDifferences = onlyDifferences, + } + if wanted.stats then result.stats = compareStats(build, entry, onlyDifferences) end + if wanted.tree then result.tree = compareTree(build, entry, limit) end + if wanted.items then result.items = compareItems(build, entry, onlyDifferences, args.item_mods, args.item_stat_changes) end + if wanted.skills then result.skills = compareSkills(build, entry, onlyDifferences) end + if wanted.config then result.config = compareConfig(build, entry, onlyDifferences, args.config_show_all) end + if wanted.calcs then result.calcs = compareCalcs(build, entry, onlyDifferences, args.calcs_filter, limit) end + return result + elseif action == "power_report" then + return powerReport(build, args) + else + return buySimilarUrl(build, args) + end + end, +} + +-- Copy socket groups as the Skills tab's Copy and Paste buttons do +-- (SkillsTab:CopySocketGroup, SkillsTab:PasteSocketGroup), without the clipboard. +local function copySocketGroup(skillsTab, group) + -- CopySocketGroup writes the group's text to the clipboard; capture it instead. + local copy = Copy + local text + local ok, err = pcall(function() + Copy = function(value) + text = value + end + skillsTab:CopySocketGroup(group) + end) + Copy = copy + if not ok then + error(err, 0) + end + skillsTab:PasteSocketGroup(text) +end + +T.Tool { + name = "compare_copy", + title = "Copy from a compared build", + description = "Copies something from a comparison build (compare_builds) into the open build, as the Compare tab's buttons do. " + .. "what='tree' adds the compared build's active passive tree as a new tree set named ' (Compared)' (\"Copy tree\"; " + .. "with use=true it also becomes the active tree, \"Copy and use\"; jewels are not copied). what='item' adds the compared item " + .. "in 'slot' to the open build's items (\"Copy\"; with use=true it is also equipped in that slot, \"Equip\"). what='config' " + .. "copies every Config tab option of the compared build (\"Copy Config from Compare Build\"). what='skills' adds the compared " + .. "build's socket groups listed in socket_groups as new groups, as the Skills tab's copy and paste do (gem name, level, quality, " + .. "enabled, count, label and slot; groups granted by items come with the item and are skipped). The build is marked unsaved and " + .. "statChanges lists what changed.", + modifies = true, + input = { + what = { type = "string", enum = { "tree", "item", "config", "skills" }, description = "What to copy." }, + index = { type = "integer", minimum = 1, description = "Comparison number (default: the one the tab shows)." }, + slot = { type = "string", description = "item: the compared item's slot, for example 'Helmet', 'Ring 1', or a jewel socket from the report's jewels list." }, + use = { type = "boolean", description = "tree: make the copy the active tree; item: equip it in that slot." }, + socket_groups = { type = "array", items = { type = "integer", minimum = 1 }, maxItems = 50, description = "skills: numbers of the compared build's socket groups to copy (from compare_builds list)." }, + }, + required = { "what" }, + run = function(args, ctx) + local build = T.Build() + local ct = build.compareTab + local entry, index = compareEntryAt(build, args.index) + local result = { comparison = index, compareName = T.Clean(entry.label), copied = args.what } + if args.what == "tree" then + if not entry.treeTab.specList[entry.treeTab.activeSpec] then + T.Fail("The compared build has no active tree.") + end + local before = #build.treeTab.specList + ct:CopyCompareSpecToPrimary(args.use == true) + if #build.treeTab.specList == before then + T.Fail("Path of Building did not copy the tree.") + end + local spec = build.treeTab.specList[#build.treeTab.specList] + result.treeSet = { index = #build.treeTab.specList, title = T.Clean(spec.title), active = build.treeTab.activeSpec == #build.treeTab.specList } + elseif args.what == "item" then + local item, slotName = comparedItem(build, entry, args.slot) + local pEnv = build.calcsTab.mainEnv + if args.use and slotName == "Ring 3" and not (pEnv and pEnv.modDB:Flag(nil, "AdditionalRingSlot")) then + T.Fail("The open build has no third ring slot (the tab shows 'Missing slot' there); copy it without use to add it unequipped.") + end + -- ItemsTab:AddItem takes the lowest free id: find the item that was not there before. + local idsBefore = { } + for id in pairs(build.itemsTab.items) do + idsBefore[id] = true + end + ct:CopyCompareItemToPrimary(slotName, entry, args.use == true) + local newItem + for id, it in pairs(build.itemsTab.items) do + if not idsBefore[id] then + newItem = it + end + end + if not newItem then + T.Fail("Path of Building did not copy the item.") + end + local pSlot = build.itemsTab.slots[slotName] + result.item = itemSummary(newItem) + result.slot = slotName + result.equipped = pSlot and pSlot.selItemId == newItem.id or false + elseif args.what == "config" then + ct:CopyCompareConfig() + else + if not args.socket_groups or not args.socket_groups[1] then + T.Fail("socket_groups is required for skills: the numbers of the compared build's socket groups (compare_builds list).") + end + local groups = entry.skillsTab.socketGroupList + local copied, skipped = { }, { } + for _, i in ipairs(args.socket_groups) do + if not groups[i] then + T.Fail("The compared build has no socket group %d; it has %d.", i, #groups) + end + end + for _, i in ipairs(args.socket_groups) do + local group = groups[i] + if group.source then + t_insert(skipped, socketGroupLabel(group, i)) + else + local before = #build.skillsTab.socketGroupList + copySocketGroup(build.skillsTab, group) + if #build.skillsTab.socketGroupList > before then + t_insert(copied, socketGroupLabel(group, i)) + else + t_insert(skipped, socketGroupLabel(group, i)) + end + end + end + if not copied[1] then + T.Fail("Nothing was copied: %s come from items or have no gems.", t_concat(skipped, ", ")) + end + result.socketGroups = copied + result.skipped = skipped[1] and skipped or nil + end + ctx:Changed() + return result + end, +} + +------------------------------------------------------------------------------ +-- Party tab +------------------------------------------------------------------------------ + +-- partyDestinations in PartyTab. +local PARTY_DESTINATIONS = { "All", "Party Member Stats", "Aura", "Curse", "Warcry Skills", "Link Skills", "EnemyConditions", "EnemyMods" } +-- PartyTab:Save's export sections, keyed by the buffExports entry each one reads. +local PARTY_EXPORTS = { { "PlayerMods", "PartyMemberStats" }, { "Aura", "Aura" }, { "Curse", "Curse" }, { "Warcry", "Warcry Skills" }, + { "Link", "Link Skills" }, { "EnemyConditions", "EnemyConditions" }, { "EnemyMods", "EnemyMods" } } + +-- The effects of one of the party actor's buff lists (PartyTab:ParseBuffs keys +-- them by name, Vaal skills in a nested "Vaal" list). +local function partyEffects(list) + local out = { } + for name, entry in pairs(list or { }) do + if name == "Vaal" and type(entry) == "table" and entry.effectMult == nil then + for vaalName, vaalEntry in pairs(entry) do + t_insert(out, { name = vaalName, effect = vaalEntry.effectMult }) + end + elseif type(entry) == "table" and entry.effectMult then + t_insert(out, { name = name, effect = entry.effectMult, mark = entry.isMark or nil }) + end + end + t_sort(out, function(a, b) return tostring(a.name) < tostring(b.name) end) + return T.Array(out) +end + +local function partySummary(build, includeText) + local partyTab = build.partyTab + local c = partyTab.controls + local actor = partyTab.actor + local aura, curse = actor.Aura or { }, actor.Curse or { } + local memberStats = { } + for k, v in pairs(actor.output or { }) do + if type(v) == "number" then + memberStats[k] = T.Round(v) + elseif type(v) == "table" then + for k2, v2 in pairs(v) do + if type(v2) == "number" then + memberStats[k .. "." .. k2] = T.Round(v2) + end + end + end + end + local memberFlags = { } + for name in pairs(actor.modDB and actor.modDB.mods or { }) do + t_insert(memberFlags, name) + end + t_sort(memberFlags) + local otherEffects = { } + for name in pairs(aura.otherEffects or { }) do + t_insert(otherEffects, name) + end + t_sort(otherEffects) + local extraAura = aura.extraAura and aura.extraAura.extraAura + local summary = { + exportSupport = partyTab.enableExportBuffs == true, + auras = partyEffects(aura.Aura), + auraDebuffs = partyEffects(aura.AuraDebuff), + extraAuraMods = extraAura and #extraAura.modList or 0, + otherEffects = T.Array(otherEffects), + curses = partyEffects(curse.Curse), + curseLimit = curse.limit, + warcries = partyEffects((actor.Warcry or { }).Warcry), + links = partyEffects((actor.Link or { }).Link), + partyMemberStats = T.Object(memberStats), + partyMemberFlags = T.Array(memberFlags), + enemyMods = #partyTab.enemyModList, + } + local texts = { + partyMemberStats = c.editPartyMemberStats.buf, auras = c.editAuras.buf, curses = c.editCurses.buf, warcries = c.editWarcries.buf, + links = c.editLinks.buf, enemyConditions = c.enemyCond.buf, enemyMods = c.enemyMods.buf, + } + local imported = { } + for key, text in pairs(texts) do + if text ~= "" then + imported[key] = includeText and text or select(2, text:gsub("\n", "\n")) + 1 + end + end + summary.importedText = T.Object(imported) + return summary +end + +-- Run fn with the Party tab's destination and Append controls set, as the +-- user would set them before pressing Import or Clear; put them back after. +local function withPartyControls(partyTab, destination, append, fn) + local c = partyTab.controls + local saved = { c.importCodeDestination.selIndex, c.appendNotReplace.state } + local wanted = destination or "All" + local found + for _, name in ipairs(c.importCodeDestination.list) do + if name == wanted then + found = true + end + end + if not found then + T.Fail("Unknown destination '%s'. Destinations: %s", wanted, t_concat(c.importCodeDestination.list, ", ")) + end + c.importCodeDestination:SelByValue(wanted) + c.appendNotReplace.state = append == true + local ok, err = pcall(fn) + c.importCodeDestination.selIndex, c.appendNotReplace.state = saved[1], saved[2] + if not ok then + error(err, 0) + end +end + +-- The Party tab's Import button, once its code box holds a valid code: the +-- state importCodeHandle leaves for it, then the button, then the code box +-- state put back as it was. +local function partyImport(build, xml, args) + xml = normaliseNewlines(xml) + -- finishImport reports bad XML through an error popup; check what it needs first. + local dbXML, parseErr = common.xml.ParseXML(xml) + if not dbXML or not dbXML[1] or dbXML[1].elem ~= "PathOfBuilding" then + T.Fail("That is not a Path of Building build (%s).", tostring(parseErr or "no PathOfBuilding element")) + end + local sections = { } + for _, tabNode in ipairs(dbXML[1]) do + if type(tabNode) == "table" and tabNode.elem == "Party" then + for _, node in ipairs(tabNode) do + if type(node) == "table" and node.elem == "ExportedBuffs" and node.attrib.name then + t_insert(sections, node.attrib.name) + end + end + end + end + if not sections[1] then + T.Fail("That build carries nothing for the Party tab: it must be exported with 'Export Support' enabled " + .. "(Import/Export tab, or party action export_support on that build).") + end + local partyTab = build.partyTab + local fields = { "importCodeSite", "importCodeXML", "importCodeValid", "importCodeDetail", "importCodeFetching" } + local saved = { } + for _, field in ipairs(fields) do + saved[field] = partyTab[field] + end + partyTab.importCodeSite = nil + partyTab.importCodeFetching = nil + partyTab.importCodeXML = xml + partyTab.importCodeValid = true + local ok, err = pcall(withPartyControls, partyTab, args.destination, args.append, partyTab.controls.importCodeGo.onClick) + for _, field in ipairs(fields) do + partyTab[field] = saved[field] + end + if not ok then + error(err, 0) + end + return sections +end + +T.Tool { + name = "party", + title = "Party tab", + description = "Path of Building's Party tab, which adds the auras, curses, warcries, link skills, party member stats and enemy " + .. "modifiers of other party members to the open build's calculations. Actions: 'get' summarises what is imported and active " + .. "(include_text adds the tab's text boxes); 'import' adds a party member from a build that was exported with 'Export Support' " + .. "enabled, given as code (build code or build XML) or link, into a destination (default All; append keeps what is there, " + .. "except curses); 'clear' empties a destination; 'disable_effects' stops the effects but keeps the text ('Disable Party " + .. "Effects'); 'rebuild' parses all the text again ('Rebuild All'); 'export_support' turns the Import/Export tab's 'Export " + .. "Support' on or off for the open build, so its own export can be imported into another build's Party tab (the result " + .. "lists the sections it exports). Changes mark the build unsaved and statChanges shows their effect.", + modifies = true, + openWorld = true, + input = { + action = { type = "string", enum = { "get", "import", "clear", "disable_effects", "rebuild", "export_support" }, description = "What to do." }, + code = { type = "string", description = "import: build code or build XML of the party member." }, + link = { type = "string", description = "import: build link of the party member (PoB downloads it)." }, + destination = { type = "string", enum = PARTY_DESTINATIONS, description = "import/clear: which part (default All)." }, + append = { type = "boolean", description = "import: add to what is there instead of replacing it (curses still replace)." }, + enabled = { type = "boolean", description = "export_support: on or off." }, + include_text = { type = "boolean", description = "Include the Party tab's text boxes (or, for export_support, the exported text)." }, + }, + required = { "action" }, + run = function(args, ctx) + local build = T.Build() + local partyTab = build.partyTab + local action = args.action + if action == "get" then + return partySummary(build, args.include_text) + elseif action == "import" then + if (args.code == nil) == (args.link == nil) then + T.Fail("Give exactly one of code or link.") + end + if args.code then + local sections = partyImport(build, T.DecodeBuildCode(args.code), args) + ctx:Changed() + T.Recalculate(build) + local result = partySummary(build, args.include_text) + result.importedSections = sections + return result + end + local link = args.link:gsub("^%s+", ""):gsub("%s+$", "") + local site = findLinkSite(link) + return T.Defer(function(resolve) + buildSites.DownloadBuild(link, site, function(isSuccess, data) + if not isSuccess then + return resolve(nil, s_format("Could not download the build from %s: %s", site.label, tostring(data))) + end + T.Settle(resolve, function() + local current = T.Build() + if current ~= build then + T.Fail("The open build changed while the download ran; nothing was imported.") + end + local sections = partyImport(build, T.DecodeBuildCode(data), args) + ctx:Changed() + T.Recalculate(build) + local result = partySummary(build, args.include_text) + result.importedSections = sections + return result + end) + end) + end, 60) + elseif action == "clear" then + withPartyControls(partyTab, args.destination, nil, partyTab.controls.clear.onClick) + elseif action == "disable_effects" then + partyTab.controls.removeEffects.onClick() + elseif action == "rebuild" then + partyTab.controls.rebuild.onClick() + else + if args.enabled == nil then + T.Fail("enabled is required for export_support.") + end + local checkbox = build.importTab.controls.enablePartyExportBuffs + checkbox.state = args.enabled + checkbox.changeFunc(args.enabled) + ctx:Changed() + T.Recalculate(build) + local exports = { } + for _, pair in ipairs(PARTY_EXPORTS) do + local text = partyTab:exportBuffs(pair[1]) + if text ~= "" then + exports[pair[2]] = args.include_text and text or (select(2, text:gsub("\n", "\n")) + 1) + end + end + return { exportSupport = partyTab.enableExportBuffs == true, exports = T.Object(exports) } + end + ctx:Changed() + T.Recalculate(build) + return partySummary(build, args.include_text) + end, +} + +------------------------------------------------------------------------------ +-- Character import (Import/Export tab, "Import From Your Account") +------------------------------------------------------------------------------ + +-- realmList in ImportTab. +local REALMS = { pc = "PC", xbox = "XBOX", sony = "SONY" } +-- The inventory ids ImportTab:ImportItem puts into a slot. +local IMPORTED_INVENTORIES = { Weapon = true, Offhand = true, Weapon2 = true, Offhand2 = true, Helm = true, BodyArmour = true, + Gloves = true, Boots = true, Amulet = true, Ring = true, Ring2 = true, Ring3 = true, Belt = true, BrequelGrafts = true, + BrequelGrafts2 = true, Flask = true, PassiveJewels = true } +local NOT_LOGGED_IN = "Path of Building is not logged in to Path of Exile. Ask the user to log in from the Import/Export tab " + .. "('Authorize with Path of Exile'), then try again." + +local function poeApi() + -- As ImportTab creates it, from the login PoB remembers. + if not main.api then + main.api = new("PoEAPI"):PoEAPI(main.lastToken, main.lastRefreshToken, main.tokenExpiry) + end + return main.api +end + +-- What an answer from PoEAPI's download functions means (as the Import tab reads them). +local function apiFailure(api, err, timeNext, name) + err = tostring(err or "no answer") + if err == "Response code: 429" then + local wait = timeNext and m_max(0, timeNext - os.time()) + return "pathofexile.com is rate limiting these requests" .. (wait and s_format("; try again in %d seconds.", wait) or "; try again later.") + elseif not api.authToken or err:match("401") then + -- PoEAPI drops the login when the token cannot be refreshed. + return "The Path of Exile login in Path of Building has expired. Ask the user to log in again from the Import/Export tab ('Authorize with Path of Exile')." + elseif name and err:match("404") then + return s_format("pathofexile.com has no character '%s' on the account Path of Building is logged in to. The name must match exactly " + .. "(use action 'list'); other accounts' characters cannot be imported this way.", name) + end + return "pathofexile.com answered: " .. err +end + +-- What the import left out: items in slots PoB imports that did not arrive, +-- and mod lines PoB does not understand (shown in red, counting for nothing). +local function auditImport(build, char, withItems, withTree) + local present = { } + for _, item in pairs(build.itemsTab.items) do + if item.uniqueID then + present[item.uniqueID] = true + end + end + local missing = { } + local function check(list) + for _, itemData in ipairs(list or { }) do + if IMPORTED_INVENTORIES[itemData.inventoryId] and itemData.id and not present[itemData.id] then + t_insert(missing, { inventory = itemData.inventoryId, name = T.Clean((itemData.name ~= "" and (itemData.name .. ", ") or "") .. tostring(itemData.typeLine)) }) + end + end + end + if withItems then + check(char.equipment) + end + if withTree then + check(char.jewels) + end + local unsupported = { } + for slotName, slot in pairs(build.itemsTab.slots) do + local item = build.itemsTab.items[slot.selItemId] + if item then + for _, listName in ipairs({ "enchantModLines", "scourgeModLines", "implicitModLines", "explicitModLines", "crucibleModLines" }) do + for _, modLine in ipairs(item[listName] or { }) do + if modLine.extra then + t_insert(unsupported, { slot = slotName, line = T.Clean(modLine.line) }) + end + end + end + end + end + t_sort(unsupported, function(a, b) return a.slot < b.slot end) + return { itemsNotImported = T.Array(missing), unsupportedModLines = T.Array(unsupported) } +end + +-- The Import tab's "Items and Skills" and "Passive Tree and Jewels" buttons +-- with the character PoB downloaded (the order of its JSON import). +local function importCharacterInto(build, char, realmCode, args, withItems, withTree) + local importTab = build.importTab + -- saveDetails in ImportTab: the realm, league and character the tab remembers. + main.lastRealm, importTab.lastRealm = REALMS[realmCode], REALMS[realmCode] + main.lastLeague, importTab.lastLeague = char.league, char.league + main.lastCharacterHash = common.sha1(char.name) + importTab.lastCharacterHash = main.lastCharacterHash + if withItems then + importTab:ImportItemsAndSkills(char, args.delete_equipment ~= false, args.delete_skills ~= false, args.ignore_weapon_swap == true) + end + if withTree then + importTab:ImportPassiveTreeAndJewels(char, args.delete_jewels ~= false) + end + T.Recalculate(build) + local equipped = 0 + for _, slot in pairs(build.itemsTab.slots) do + if build.itemsTab.items[slot.selItemId] then + equipped = equipped + 1 + end + end + local input = build.configTab.input + return { + character = { name = char.name, class = char.class, league = char.league, level = char.level }, + imported = withItems and withTree and "tree, jewels, items and skills" or withTree and "tree and jewels" or "items and skills", + build = T.BuildSummary(build), + equippedItems = equipped, + socketGroups = #build.skillsTab.socketGroupList, + questChoices = { bandit = input.bandit, pantheonMajor = input.pantheonMajorGod, pantheonMinor = input.pantheonMinorGod }, + audit = auditImport(build, char, withItems, withTree), + } +end + +T.Tool { + name = "import_character", + title = "Import a Path of Exile character", + description = "Imports a character from the Path of Exile account Path of Building is logged in to, exactly as the Import/Export " + .. "tab's 'Import From Your Account' does (PoB's own login, token refresh and rate limiting; the login never leaves PoB). " + .. "action 'list' lists the account's characters (optionally of one league). action 'import' downloads one character by " + .. "name: mode 'new_build' (default) opens a new build and imports everything into it (refused while the open build has " + .. "unsaved changes unless discard_unsaved); mode 'update' imports into the open build: parts 'tree' (passive tree and jewels, " + .. "replacing the tree), 'items_skills' (items and skills) or 'both'; by default equipped jewels, equipment and skills are " + .. "deleted first, as the tab's checkboxes are. The result includes an audit of items PoB could not import and mod lines it " + .. "does not support. It fails when PoB is not logged in: only the user can log in, from the Import/Export tab " + .. "('Authorize with Path of Exile'). Builds from other people's accounts are imported with build_open link instead.", + destructive = true, + openWorld = true, + modifies = true, + replacesBuild = true, + needsBuild = false, + input = { + action = { type = "string", enum = { "list", "import" }, description = "List the account's characters, or import one." }, + realm = { type = "string", enum = { "pc", "xbox", "sony" }, description = "Realm (default: the one last used, else pc)." }, + league = { type = "string", description = "list: only characters in this league, for example 'Standard'." }, + name = { type = "string", maxLength = 50, description = "import: the character name, exactly as in the game." }, + mode = { type = "string", enum = { "new_build", "update" }, description = "import: into a new build (default) or the open one." }, + parts = { type = "string", enum = { "both", "tree", "items_skills" }, description = "import with mode update: what to import (default both)." }, + delete_jewels = { type = "boolean", description = "Delete the equipped jewels before importing the tree (default true)." }, + delete_equipment = { type = "boolean", description = "Delete the equipped items before importing items (default true)." }, + delete_skills = { type = "boolean", description = "Delete the existing skills before importing skills (default true)." }, + ignore_weapon_swap = { type = "boolean", description = "Skip weapon swap items and their skills (default false)." }, + build_name = { type = "string", maxLength = 100, description = "mode new_build: name of the new build (default the character name)." }, + discard_unsaved = T.discardUnsavedArg, + limit = T.PageArgs(50).limit, + offset = T.PageArgs(50).offset, + }, + required = { "action" }, + run = function(args, ctx) + local realmCode = args.realm or (main.lastRealm and main.lastRealm:lower()) or "pc" + if not REALMS[realmCode] then + realmCode = "pc" + end + local api = poeApi() + if args.action == "list" then + if not api.authToken then + T.Fail(NOT_LOGGED_IN) + end + return T.Defer(function(resolve) + api:DownloadCharacterList(realmCode, function(body, err, timeNext) + T.Settle(resolve, function() + if err or type(body) ~= "table" or type(body.characters) ~= "table" then + T.Fail(apiFailure(api, err, timeNext)) + end + local list, leagues = { }, { } + for _, char in ipairs(body.characters) do + -- ImportTab:BuildCharacterList + if char.realm == realmCode and (not args.league or char.league == args.league) then + t_insert(list, { name = char.name, class = char.class, league = char.league, level = char.level }) + end + if char.league then + leagues[char.league] = true + end + end + t_sort(list, function(a, b) return tostring(a.name):lower() < tostring(b.name):lower() end) + local leagueList = { } + for league in pairs(leagues) do + t_insert(leagueList, league) + end + t_sort(leagueList) + local page, paging = T.Page(list, args, 50) + return { realm = realmCode, leagues = T.Array(leagueList), characters = page, page = paging } + end) + end) + end, 60) + end + -- PoB puts the name into the URL path as it is: allow only what character names contain. + if type(args.name) ~= "string" or not args.name:match("^[%w_]+$") then + T.Fail("name must be a character name (letters, digits and underscores), exactly as in the game.") + end + local mode = args.mode or "new_build" + local withItems = mode == "new_build" or args.parts ~= "tree" + local withTree = mode == "new_build" or args.parts ~= "items_skills" + local target + if mode == "update" then + target = T.Build() + else + T.CheckCanReplaceBuild(args) + end + if not api.authToken then + T.Fail(NOT_LOGGED_IN) + end + return T.Defer(function(resolve) + api:DownloadCharacter(realmCode, args.name, function(body, err, timeNext) + T.Settle(resolve, function() + if err or type(body) ~= "table" or type(body.character) ~= "table" then + T.Fail(apiFailure(api, err, timeNext, args.name)) + end + local char = body.character + local build + if mode == "update" then + build = T.Build() + if build ~= target then + T.Fail("The open build changed while the download ran; nothing was imported.") + end + local result = importCharacterInto(build, char, realmCode, args, withItems, withTree) + ctx:Changed() + return result + end + -- The user may have changed something while the download ran. + T.CheckCanReplaceBuild(args) + build = T.SwitchToBuild(false, (T.Sanitise(args.build_name or char.name))) + return importCharacterInto(build, char, realmCode, args, true, true) + end) + end) + end, 60) + end, +} diff --git a/src/Modules/McpTools/Config.lua b/src/Modules/McpTools/Config.lua index 7359c9b3e2c..c44029c6765 100644 --- a/src/Modules/McpTools/Config.lua +++ b/src/Modules/McpTools/Config.lua @@ -1,6 +1,466 @@ -- Path of Building -- -- Module: MCP Tools - Config +-- The Config tab: its options (Modules/ConfigOptions), config sets and the +-- custom modifier groups. -- local T = ... +local t_insert = table.insert +local t_concat = table.concat +local m_floor = math.floor + +local varList = require("Modules.ConfigOptions") + +local NUMBER_TYPES = { count = true, integer = true, countAllowZero = true, float = true } + +-- Every option of the Config tab with the section it is in, in the tab's order. +local optionList, optionsByVar +local function options() + if not optionList then + optionList, optionsByVar = { }, { } + local section + for _, varData in ipairs(varList) do + if varData.section then + section = varData.section + elseif varData.var then + local label = varData.label and T.Clean(varData.label):gsub("%s*:%s*$", "") or varData.var + local option = { varData = varData, var = varData.var, label = label, section = section } + t_insert(optionList, option) + optionsByVar[varData.var] = option + end + end + end + return optionList, optionsByVar +end + +local function listLabel(varData, value) + for _, entry in ipairs(varData.list) do + if entry.val == value then + return T.Clean(entry.label) + end + end + return value ~= nil and tostring(value) or nil +end + +local function listChoices(varData) + local choices = { } + for _, entry in ipairs(varData.list) do + t_insert(choices, T.Clean(entry.label)) + end + return choices +end + +-- An option's value as the Config tab shows it, and whether it differs from +-- the default (the test ConfigTab uses to highlight changed options). +local function describeOption(configTab, option, withChoices) + local varData = option.varData + local configSet = configTab.configSets[configTab.activeConfigSetId] + local current = configSet.input[varData.var] + local default = configTab:GetDefaultState(varData.var, type(current)) + local entry = { var = option.var, label = option.label, section = option.section, type = varData.type } + if varData.type == "check" then + entry.value = current and true or false + entry.default = default and true or false + elseif varData.type == "list" then + entry.value = listLabel(varData, current ~= nil and current or default) + entry.default = listLabel(varData, default) + if withChoices then + entry.choices = listChoices(varData) + end + elseif NUMBER_TYPES[varData.type] then + entry.value = T.Number(current) + entry.default = T.Number(default) + -- An empty number box uses its placeholder (enemy stats follow the boss choice this way). + local placeholder = configSet.placeholder[varData.var] + if current == nil and type(placeholder) == "number" then + entry.usesPlaceholder = true + end + else + entry.value = current + entry.default = default + end + return entry, current ~= nil and current ~= default +end + +local function configSetList(configTab) + local sets = { } + for _, id in ipairs(configTab.configSetOrderList) do + t_insert(sets, { id = id, title = T.Clean(configTab.configSets[id].title or "Default"), active = id == configTab.activeConfigSetId }) + end + return sets +end + +-- The lines of a custom modifier group PoB does not recognise: the ones its +-- edit box shows in red, as ConfigTab:BuildModList skips them. +local function unrecognisedLines(text) + local lines = { } + for line in (text or ""):gmatch("([^\n]*)\n?") do + local stripped = StripEscapes(line):match("^%s*(.-)%s*$") + if stripped ~= "" then + local mods, extra = modLib.parseMod(stripped) + if not (mods and not extra) then + t_insert(lines, stripped) + end + end + end + return lines +end + +local function customModGroups(configTab) + local groups = { } + for index, block in ipairs(configTab.configSets[configTab.activeConfigSetId].customModsList or { }) do + local group = { index = index, title = block.title or "Default", enabled = block.enabled ~= false, text = block.text or "" } + local unrecognised = unrecognisedLines(block.text) + if unrecognised[1] then + group.unrecognised = unrecognised + end + t_insert(groups, group) + end + return groups +end + +local function activeSetTitle(configTab) + return T.Clean(configTab.configSets[configTab.activeConfigSetId].title or "Default") +end + +------------------------------------------------------------------------------ + +T.Tool { + name = "config_get", + title = "Config tab", + description = "Returns the Config tab of the open build's active config set: by default only the options that differ from " + .. "their defaults (what PoB highlights), which together with the defaults describe every assumption the numbers rest on " + .. "(enemy boss type and resistances, charges, buffs, conditions, bandit, pantheon...). With 'search' it lists every option whose " + .. "label, var name or section contains the text, with the choices of list options; with 'all' it lists every option. Each " + .. "option has its var (the name config_set takes), label, section, type (check, count, integer, countAllowZero, float, list, " + .. "text), current value (list options by the label PoB shows) and default. Also returns the config sets, the effective enemy " + .. "level and the custom modifier groups with the lines PoB does not recognise.", + readOnly = true, + idempotent = true, + input = { + search = { type = "string", maxLength = 100, description = "Only options whose label, var or section contains this text (any value)." }, + all = { type = "boolean", description = "List every option, not only changed ones (use limit/offset to page)." }, + limit = T.PageArgs(50).limit, + offset = T.PageArgs(50).offset, + }, + run = function(args) + local build = T.Build() + build:ProcessBuildFlag() + local configTab = build.configTab + local list = { } + local search = args.search and args.search:lower():match("^%s*(.-)%s*$") + if search == "" then + search = nil + end + for _, option in ipairs((options())) do + local matches + if search then + matches = option.label:lower():find(search, 1, true) or option.var:lower():find(search, 1, true) + or (option.section or ""):lower():find(search, 1, true) + end + local entry, changed = describeOption(configTab, option, search ~= nil) + if (search and matches) or (not search and (args.all or changed)) then + t_insert(list, entry) + end + end + local page, paging = T.Page(list, args, 50) + return { + configSet = activeSetTitle(configTab), + configSets = configSetList(configTab), + listed = search and "matching" or args.all and "all" or "changed from default", + options = page, + page = paging, + enemyLevel = configTab.enemyLevel, + customModifiers = T.Array(customModGroups(configTab)), + } + end, +} + +------------------------------------------------------------------------------ + +-- The option a client means: its var, or its exact label. +local function findOption(key) + local list, byVar = options() + if byVar[key] then + return byVar[key] + end + local wanted = T.Clean(tostring(key)):gsub("%s*:%s*$", ""):lower() + local found = { } + for _, option in ipairs(list) do + if option.label:lower() == wanted or option.var:lower() == wanted then + t_insert(found, option) + end + end + if #found == 1 then + return found[1] + elseif #found > 1 then + local vars = { } + for _, option in ipairs(found) do + t_insert(vars, option.var) + end + return nil, "several options have that label; use the var: " .. t_concat(vars, ", ") + end + -- Suggest options with a similar label. + local close = { } + for _, option in ipairs(list) do + if #close < 8 and (option.label:lower():find(wanted, 1, true) or option.var:lower():find(wanted, 1, true)) then + t_insert(close, option.var .. " (" .. option.label .. ")") + end + end + return nil, "no such option" .. (close[1] and ("; similar: " .. t_concat(close, "; ")) or "; find it with config_get search") +end + +-- Check a value against the option's type, as its control would accept it. +-- Returns the value to apply (for lists, the index of the choice) or nil and a reason. +local function checkValue(varData, value) + local kind = varData.type + if kind == "check" then + if type(value) == "boolean" then + return value + elseif value == "true" or value == "false" then + return value == "true" + end + return nil, "expects true or false" + elseif NUMBER_TYPES[kind] then + local number = tonumber(value) + if not T.Number(number) then + return nil, "expects a number" + end + -- The edit boxes accept digits only (count), digits and a minus sign (integer, countAllowZero), or digits and a point (float). + if kind ~= "float" and number ~= m_floor(number) then + return nil, "expects a whole number" + end + if (kind == "count" or kind == "float") and number < 0 then + return nil, "expects a number of 0 or more" + end + return number + elseif kind == "list" then + for index, entry in ipairs(varData.list) do + if entry.val == value then + return index + end + end + local wanted = tostring(value):lower() + for index, entry in ipairs(varData.list) do + if T.Clean(entry.label):lower() == wanted or tostring(entry.val):lower() == wanted then + return index + end + end + return nil, "is not one of the choices" + elseif kind == "text" then + if type(value) ~= "string" then + return nil, "expects text" + end + return value + end + return nil, "cannot be set" +end + +-- Set an option through its Config tab control, so the control's own callback runs +-- (input, undo state, BuildModList, buildFlag). +local function applyOption(configTab, varData, value) + local control = configTab.varControls[varData.var] + local kind = varData.type + if kind == "check" then + control.state = value + control.changeFunc(value) + elseif NUMBER_TYPES[kind] then + control:SetText(value == nil and "" or tostring(value), true) + elseif kind == "list" then + control.selIndex = value + control.selFunc(value, control.list[value]) + elseif kind == "text" then + control:SetText(T.Sanitise((value:gsub("\r\n", "\n"))), true) + end +end + +local function optionValue(configTab, option) + return (describeOption(configTab, option)).value +end + +-- Text for a custom modifier group's edit box, which keeps printable characters, tabs and new lines. +local function cleanModText(text) + text = text:gsub("\r\n", "\n"):gsub("%c", function(c) + return (c == "\n" or c == "\t") and c or "" + end) + return (T.Sanitise(text)) +end + +local function editCustomMods(configTab, args, result) + if not configTab.customSection then + T.Fail("This version of Path of Building has no custom modifiers section.") + end + local list = configTab.configSets[configTab.activeConfigSetId].customModsList + local index + if args.new_custom_mods_group then + configTab.controls.customModsAddBlock.onClick() + index = #configTab.configSets[configTab.activeConfigSetId].customModsList + local title = T.Sanitise((args.new_custom_mods_group:gsub("%c", " "))) + if title:match("%S") then + configTab.customModsBlockControls[index].controls.titleEdit:SetText(title, true) + end + elseif args.custom_mods_group ~= nil then + local ref = args.custom_mods_group + if type(ref) == "number" then + if not list[ref] then + T.Fail("There is no custom modifier group %d; there are %d.", ref, #list) + end + index = ref + else + index = isValueInArray(list, T.Find(list, ref, function(block) return block.title or "Default" end, "custom modifier group")) + end + else + index = 1 + end + local blockControl = configTab.customModsBlockControls[index] + local block = configTab.configSets[configTab.activeConfigSetId].customModsList[index] + if args.custom_mods then + local text = cleanModText(args.custom_mods) + if args.custom_mods_mode == "replace" then + blockControl.controls.textEdit:SetText(text, true) + else + local existing = block.text or "" + if existing ~= "" and not existing:match("\n$") then + existing = existing .. "\n" + end + blockControl.controls.textEdit:SetText(existing .. text, true) + end + end + if args.custom_mods_enabled ~= nil and args.custom_mods_enabled ~= (block.enabled ~= false) then + blockControl.controls.enableCheck.state = args.custom_mods_enabled + blockControl.controls.enableCheck.changeFunc(args.custom_mods_enabled) + end + local group = customModGroups(configTab)[index] + result.customModifiers = group + if group.unrecognised then + result.note = "Path of Building does not recognise the lines in customModifiers.unrecognised; they have no effect. " + .. "Write them as item or passive modifiers are worded in the game." + end +end + +T.Tool { + name = "config_set", + title = "Change the Config tab", + description = "Changes the Config tab of the open build through its own controls, so PoB applies them exactly as when the user " + .. "clicks: 'options' sets options by var (or exact label), for example {\"enemyIsBoss\": \"Pinnacle\", \"usePowerCharges\": true, " + .. "\"enemyFireResist\": 40, \"bandit\": \"Kill all\"}; boss types and boss skill presets ('enemyIsBoss', 'presetBossSkills') are " + .. "list options like any other. Values are checked against the option's type (check: true/false; count/integer/float: numbers; " + .. "list: one of its choices, by the label PoB shows or the stored value; text: text); invalid ones are listed under 'rejected' " + .. "with the reason and the valid choices. 'reset' puts options back to their defaults. 'set_action' manages config sets " + .. "(select, new, copy, rename, delete) and runs first, so options then apply to the selected set. 'custom_mods' replaces or " + .. "appends text in a custom modifier group and reports lines PoB does not recognise. Use config_get to find vars and choices.", + destructive = true, + idempotent = true, + modifies = true, + usesDialog = true, + input = { + options = { type = "object", description = "Options to set: { var or exact label: value }." }, + reset = { type = "array", items = { type = "string" }, maxItems = 100, description = "Options (var or exact label) to put back to their default." }, + set_action = { type = "string", enum = { "select", "new", "copy", "rename", "delete" }, description = "Config set action. new/copy do not select the new set; select it in another call." }, + set = { type = { "integer", "string" }, description = "The config set for select, copy, rename or delete (id or title)." }, + title = { type = "string", maxLength = 100, description = "Name for new, copy or rename." }, + custom_mods = { type = "string", maxLength = 20000, description = "Custom modifier text, one modifier per line, worded as on items (for example '10% increased maximum Life')." }, + custom_mods_mode = { type = "string", enum = { "append", "replace" }, description = "Append to the group's text (default) or replace it." }, + custom_mods_group = { type = { "integer", "string" }, description = "Custom modifier group (index or title). Default: the first." }, + new_custom_mods_group = { type = "string", maxLength = 100, description = "Add a new custom modifier group with this title and write custom_mods there." }, + custom_mods_enabled = { type = "boolean", description = "Enable or disable the custom modifier group." }, + }, + run = function(args, ctx) + local build = T.Build() + build:ProcessBuildFlag() + local configTab = build.configTab + local result = { } + local didSomething = false + + if args.set_action then + local control = new("ConfigSetListControl"):ConfigSetListControl(nil, { 0, 0, 350, 200 }, configTab) + local done = T.ManageSetList({ + control = control, sets = configTab.configSets, order = configTab.configSetOrderList, what = "config set", + activeId = function() return configTab.activeConfigSetId end, + action = args.set_action, ref = args.set, title = args.title, + }) + if not done.unchanged then + ctx:Changed() + end + didSomething = true + result.configSetChange = done + end + + local applied, rejected = { }, { } + local function reject(key, reason, option) + local entry = { option = tostring(key), reason = reason } + if option and option.varData.type == "list" then + entry.choices = listChoices(option.varData) + end + t_insert(rejected, entry) + end + local keys = { } + for key in pairs(args.options or { }) do + t_insert(keys, key) + end + table.sort(keys, function(a, b) return tostring(a) < tostring(b) end) + for _, key in ipairs(keys) do + local option, err = findOption(key) + if not option then + reject(key, err) + else + local value, reason = checkValue(option.varData, args.options[key]) + if value == nil then + reject(key, option.var .. " " .. reason, option) + else + local previous = optionValue(configTab, option) + applyOption(configTab, option.varData, value) + t_insert(applied, { var = option.var, label = option.label, value = optionValue(configTab, option), previous = previous }) + end + end + end + for _, key in ipairs(args.reset or { }) do + local option, err = findOption(key) + if not option then + reject(key, err) + else + local varData = option.varData + local previous = optionValue(configTab, option) + if varData.type == "check" then + applyOption(configTab, varData, varData.defaultState or false) + elseif varData.type == "list" then + applyOption(configTab, varData, varData.defaultIndex or 1) + elseif NUMBER_TYPES[varData.type] then + applyOption(configTab, varData, nil) + elseif varData.type == "text" then + applyOption(configTab, varData, varData.defaultState or "") + end + t_insert(applied, { var = option.var, label = option.label, value = optionValue(configTab, option), previous = previous, reset = true }) + end + end + if applied[1] then + ctx:Changed() + didSomething = true + end + + if args.custom_mods or args.new_custom_mods_group or args.custom_mods_enabled ~= nil then + editCustomMods(configTab, args, result) + ctx:Changed() + didSomething = true + end + + if not didSomething then + if rejected[1] then + local reasons = { } + for _, entry in ipairs(rejected) do + t_insert(reasons, entry.option .. ": " .. entry.reason .. (entry.choices and (" (choices: " .. t_concat(entry.choices, ", ") .. ")") or "")) + end + T.Fail("Nothing was changed. %s", t_concat(reasons, "; ")) + end + T.Fail("Nothing to change: give options, reset, set_action or custom_mods.") + end + build:ProcessBuildFlag() + result.applied = T.Array(applied) + result.rejected = T.Array(rejected) + result.configSet = activeSetTitle(configTab) + result.configSets = configSetList(configTab) + result.enemyLevel = configTab.enemyLevel + return result + end, +} diff --git a/src/Modules/McpTools/Items.lua b/src/Modules/McpTools/Items.lua index cd6ad92934f..43a1415008e 100644 --- a/src/Modules/McpTools/Items.lua +++ b/src/Modules/McpTools/Items.lua @@ -1,6 +1,1723 @@ -- Path of Building -- -- Module: MCP Tools - Items +-- The Items tab: equipped items and item sets, the unique and rare template +-- databases, crafting with the tab's own controls and dialogs, and the +-- weighted trade search of PoB's trader. -- local T = ... +local t_insert = table.insert +local t_concat = table.concat +local s_format = string.format +local m_min = math.min +local m_max = math.max + +local dkjson = require("dkjson") +local tradeHelpers = require("Classes.TradeHelpers") + +------------------------------------------------------------------------------ +-- Shared helpers +------------------------------------------------------------------------------ + +local MOD_LINE_LISTS = { "enchantModLines", "scourgeModLines", "implicitModLines", "explicitModLines", "crucibleModLines" } + +-- The text of a dropdown or list entry, without colour codes. +local function labelOf(entry) + if type(entry) == "table" then + entry = entry.label or entry.name + end + return T.Clean(tostring(entry or "")) +end + +-- Selects a dropdown entry as a click does. +local function choose(control, index) + control.selIndex = index + if control.selFunc then + control.selFunc(index, control.list[index]) + end +end + +-- The index of the entry of a PoB list the client named: an entry isMatch +-- recognises (an id), the label (case-insensitive, without colour codes), or a +-- unique part of a label. +local function pick(list, want, what, isMatch, first) + first = first or 1 + local wanted = T.Clean(tostring(want)):lower() + local partial = { } + for i = first, #list do + local entry = list[i] + if isMatch and isMatch(entry, want) then + return i + end + local label = labelOf(entry):lower() + if label == wanted then + return i + end + if wanted ~= "" and label:find(wanted, 1, true) then + t_insert(partial, i) + end + end + if #partial == 1 then + return partial[1] + end + local names = { } + if #partial > 1 then + for k = 1, m_min(#partial, 10) do + t_insert(names, labelOf(list[partial[k]])) + end + T.Fail("The %s '%s' matches %d options, for example: %s. Give more of the text.", what, tostring(want), #partial, t_concat(names, " | ")) + end + if #list - first + 1 <= 30 then + for i = first, #list do + t_insert(names, labelOf(list[i])) + end + T.Fail("No %s matches '%s'. Options: %s", what, tostring(want), t_concat(names, " | ")) + end + T.Fail("No %s matches '%s'; leave it out to list the options.", what, tostring(want)) +end + +-- The entry of a "Sort by" list (data.powerStatList entries) for a stat key or label. +local function findSortIndex(list, sortBy) + local wanted = (tostring(sortBy):lower():gsub("^sort by ", "")) + local names = { } + for i, entry in ipairs(list) do + if type(entry) == "table" then + local label = ((entry.label or ""):lower():gsub("^sort by ", "")) + if (entry.stat and entry.stat:lower() == wanted) or label == wanted then + return i + end + t_insert(names, entry.stat or (entry.label or ""):gsub("^Sort by ", "")) + end + end + T.Fail("Unknown sort '%s'. Sort by one of: %s", tostring(sortBy), t_concat(names, ", ")) +end + +-- Lines a PoB item shows (enchants, implicits, explicits), for the selected variant. +local function modLines(item) + local lines = { } + for _, key in ipairs(MOD_LINE_LISTS) do + for _, modLine in ipairs(item[key] or { }) do + if item:CheckModLineVariant(modLine) then + local line = itemLib.formatModLine(modLine) + if line then + t_insert(lines, T.Clean(line)) + end + end + end + end + return lines +end + +-- Sockets as written in item text ("R-G-B B"). +local function socketString(item) + if not item.sockets or not item.sockets[1] then + return nil + end + local parts = { } + for i, socket in ipairs(item.sockets) do + if i > 1 then + t_insert(parts, socket.group == item.sockets[i - 1].group and "-" or " ") + end + t_insert(parts, socket.color) + end + return t_concat(parts) +end + +-- An item as reported to the client; detail gives the full text PoB copies +-- (Ctrl+C in the item list: Item:BuildRaw). +local function describeItem(item, detail) + local entry = { + id = item.id, + name = item.name, + rarity = item.rarity, + base = item.baseName, + type = item.type, + } + if detail then + entry.text = item:BuildRaw() + else + entry.quality = item.quality and item.quality > 0 and item.quality or nil + entry.sockets = socketString(item) + entry.corrupted = item.corrupted or nil + entry.mods = T.Array(modLines(item)) + end + return entry +end + +-- An item already in the build, by id or name. +local function findItem(itemsTab, ref) + local id = tonumber(ref) + if id then + local item = itemsTab.items[id] + if not item then + T.Fail("The build has no item with id %d; items_get lists the items and their ids.", id) + end + return item + end + local list = { } + for _, itemId in ipairs(itemsTab.itemOrderList) do + t_insert(list, itemsTab.items[itemId]) + end + return T.Find(list, ref, function(item) + return item.name + end, "item in the build") +end + +local function slotLabel(slot) + return slot.label or slot.slotName +end + +------------------------------------------------------------------------------ +-- items_get +------------------------------------------------------------------------------ + +local function setTitle(itemSet) + return itemSet.title or "Default" +end + +local function listSets(itemsTab) + local sets = { } + for position, setId in ipairs(itemsTab.itemSetOrderList) do + t_insert(sets, { position = position, title = setTitle(itemsTab.itemSets[setId]), active = setId == itemsTab.activeItemSetId }) + end + return sets +end + +T.Tool { + name = "items_get", + title = "Equipped items", + description = "Returns what the Items tab shows for the open build: the active item set's equipped items by slot (weapons, both " + .. "weapon sets when weapon swap is used, armour, jewellery, flasks and tinctures with whether each is switched on, abyssal " + .. "sockets, and the jewels in allocated passive tree sockets), which visible slots are empty, the list of item sets, and the " + .. "build's other items (not equipped in the active set), paged. Each item has its id (for items_equip), name, rarity, base " + .. "and type, and either a short summary (quality, sockets, the modifier lines PoB shows) or, with detail, the full item text " + .. "exactly as PoB copies it. Use it before recommending or changing items; it changes nothing.", + readOnly = true, + idempotent = true, + input = { + detail = { type = "boolean", description = "Return each item's full text (as PoB copies it) instead of a short summary." }, + slot = { type = "string", description = "Only this slot, for example 'Helmet', 'Ring 2', 'Flask 1', 'Weapon 1 Swap' or 'Socket #2'." }, + limit = T.PageArgs(25).limit, + offset = T.PageArgs(25).offset, + }, + run = function(args) + local build = T.Build() + local itemsTab = build.itemsTab + -- As the tab does when drawing or showing a tooltip: socket labels and which sockets are allocated. + itemsTab:UpdateSockets() + local activeWeaponSet = itemsTab.activeItemSet.useSecondWeaponSet and 2 or 1 + local onlySlot = args.slot and T.FindSlot(build, args.slot) + local equipped, empty = { }, { } + local inActiveSet = { } + for _, slot in ipairs(itemsTab.orderedSlots) do + local otherWeaponSet = slot.weaponSet and slot.weaponSet ~= activeWeaponSet + if not slot.inactive and (slot:IsShown() or otherWeaponSet) and (not onlySlot or onlySlot == slot) then + local item = itemsTab.items[slot.selItemId] + if item then + inActiveSet[item.id] = true + local entry = describeItem(item, args.detail) + entry.slot = slot.slotName + entry.label = slotLabel(slot) + if slot.controls.activate then + entry.active = slot.active and true or false + end + if otherWeaponSet then + entry.inactiveWeaponSet = true + end + t_insert(equipped, entry) + elseif not otherWeaponSet then + t_insert(empty, slot.nodeId and (slotLabel(slot) .. " (" .. slot.slotName .. ")") or slot.slotName) + end + end + end + local result = { + itemSet = setTitle(itemsTab.activeItemSet), + weaponSet = activeWeaponSet, + equipped = T.Array(equipped), + emptySlots = T.Array(empty), + } + if onlySlot then + return result + end + result.itemSets = listSets(itemsTab) + local others = { } + local itemList = itemsTab.controls.itemList + for _, itemId in ipairs(itemsTab.itemOrderList) do + local item = itemsTab.items[itemId] + if item and not inActiveSet[itemId] then + local entry = describeItem(item, args.detail) + local _, otherSet = itemsTab:GetEquippedSlotForItem(item) + local usedIn = otherSet and ("item set '" .. setTitle(otherSet) .. "'") + if not usedIn then + local tree = itemList:FindSocketedJewel(itemId, true) + usedIn = tree and ("passive tree '" .. tree .. "'") + end + if not usedIn then + local abyssSet = itemList:FindEquippedAbyssJewel(itemId, true) + usedIn = abyssSet and ("item set '" .. abyssSet .. "'") + end + entry.usedIn = usedIn + t_insert(others, entry) + end + end + result.otherItems, result.otherItemsPage = T.Page(others, args, 25) + return result + end, +} + +------------------------------------------------------------------------------ +-- items_equip +------------------------------------------------------------------------------ + +T.Tool { + name = "items_equip", + title = "Equip or remove items", + description = "Changes the open build's items as the Items tab does. action 'equip': with 'item' (item text copied from the game, " + .. "a trade site or PoB) the item is added to the build with PoB's paste normalisation (quality raised to 20 where PoB " + .. "assumes it, and the anoint and eldritch implicits of the item it replaces copied over, as pasting into the Items tab " + .. "does) and equipped in 'slot'; without 'slot' it goes into the first empty slot that fits, like 'Add to build', or is only " + .. "added with add_only. With 'item_ref' (an item id or name from items_get) an item already in the build is equipped, in " + .. "'slot' or its usual slot. action 'unequip' empties 'slot' (the item stays in the build). action 'set_active' switches a " + .. "flask or tincture on or off, like the slot's check box. action 'remove' deletes 'item_ref' from the build and every item " + .. "set; only use it when the user explicitly asked to delete the item. To measure a change first, use simulate. The result " + .. "says what was equipped or replaced and lists the side-bar stat changes.", + modifies = true, + destructive = true, + input = { + action = { type = "string", enum = { "equip", "unequip", "set_active", "remove" }, description = "What to do." }, + slot = { type = "string", description = "Slot name or label, for example 'Helmet', 'Ring 2', 'Weapon 1 Swap', 'Flask 3', 'Socket #2', 'Helmet Abyssal Socket 1'." }, + item = { type = "string", maxLength = 20000, description = "equip: the item text to add and equip." }, + item_ref = { type = { "string", "integer" }, description = "equip/remove: an item already in the build, by id or name (see items_get)." }, + add_only = { type = "boolean", description = "equip with 'item' and no slot: add the item to the build without equipping it." }, + active = { type = "boolean", description = "set_active: true switches the flask or tincture on, false off." }, + }, + required = { "action" }, + run = function(args, ctx) + local build = T.Build() + local itemsTab = build.itemsTab + itemsTab:UpdateSockets() + local action = args.action + local slot = args.slot and T.FindSlot(build, args.slot) + local function finish() + itemsTab:PopulateSlots() + itemsTab:AddUndoState() + build.buildFlag = true + ctx:Changed() + end + + if action == "equip" then + if (args.item ~= nil) == (args.item_ref ~= nil) then + T.Fail("Give either item (new item text) or item_ref (an item already in the build).") + end + local item, isNew + if args.item then + item = T.ParseItem(build, args.item, slot and slot.slotName) + isNew = true + else + item = findItem(itemsTab, args.item_ref) + if not slot then + -- As Ctrl+click in the item list: the item's primary slot, in the weapon set in use. + local slotName = item:GetPrimarySlot() + if not itemsTab.slots[slotName] then + T.Fail("%s has no single usual slot; give slot.", item.name) + end + if itemsTab.slots[slotName].weaponSet == 1 and itemsTab.activeItemSet.useSecondWeaponSet then + slotName = slotName .. " Swap" + end + slot = itemsTab.slots[slotName] + end + end + if slot then + if slot.inactive then + T.Fail("%s is not available (an unallocated jewel socket, or an abyssal socket the item there does not have).", slotLabel(slot)) + end + if not itemsTab:IsItemValidForSlot(item, slot.slotName) then + T.Fail("%s cannot be equipped in %s.", item.name, slotLabel(slot)) + end + end + local replaced = slot and itemsTab.items[slot.selItemId] + if isNew then + itemsTab:AddItem(item, slot ~= nil or args.add_only == true) + end + if slot then + slot:SetSelItemId(item.id) + end + if isNew then + itemsTab:AddForbiddenJewelCounterpart(item) + end + finish() + local where = itemsTab:GetEquippedSlotForItem(item) + local result = { + item = describeItem(item), + added = isNew or nil, + equippedIn = where and where.selItemId == item.id and where.slotName or nil, + replaced = replaced and replaced ~= item and replaced.name or nil, + } + if slot and slot.selItemId ~= item.id then + result.note = "Path of Building did not keep the item in " .. slotLabel(slot) .. "; check the slot with items_get." + elseif not slot and not result.equippedIn and not args.add_only then + result.note = "No empty slot fits this item, so it was only added to the build; equip it with item_ref and slot." + end + return result + elseif action == "unequip" then + if not slot then + T.Fail("slot is required for unequip.") + end + local item = itemsTab.items[slot.selItemId] + if not item then + T.Fail("Nothing is equipped in %s.", slotLabel(slot)) + end + slot:SetSelItemId(0) + finish() + return { unequipped = item.name, slot = slot.slotName, note = "The item stays in the build's item list." } + elseif action == "set_active" then + if not slot or not slot.controls.activate then + T.Fail("set_active needs a flask slot, for example 'Flask 1'.") + end + if args.active == nil then + T.Fail("active is required for set_active.") + end + local item = itemsTab.items[slot.selItemId] + if not item then + T.Fail("Nothing is equipped in %s.", slotLabel(slot)) + end + local checkBox = slot.controls.activate + if (slot.active and true or false) ~= args.active then + -- The slot's check box. + checkBox.state = args.active + checkBox.changeFunc(args.active) + ctx:Changed() + end + return { slot = slot.slotName, item = item.name, active = slot.active and true or false } + else + if args.item_ref == nil then + T.Fail("item_ref is required for remove.") + end + local item = findItem(itemsTab, args.item_ref) + local equippedSlot, equippedSet = itemsTab:GetEquippedSlotForItem(item) + -- What the item list's Delete does once confirmed. + itemsTab:DeleteItem(item) + itemsTab.controls.itemList:UpdateList() + build.buildFlag = true + ctx:Changed() + local wasIn = equippedSlot and (slotLabel(equippedSlot) .. (equippedSet and (" in item set '" .. setTitle(equippedSet) .. "'") or "")) or nil + return { removed = item.name, wasEquippedIn = wasIn } + end + end, +} + +------------------------------------------------------------------------------ +-- items_sets +------------------------------------------------------------------------------ + +local function findSet(itemsTab, ref) + local order = itemsTab.itemSetOrderList + if type(ref) == "number" then + if ref < 1 or ref > #order or ref % 1 ~= 0 then + T.Fail("There is no item set at position %s; positions go from 1 to %d.", tostring(ref), #order) + end + return ref, order[ref] + end + local id = T.Find(order, ref, function(setId) + return setTitle(itemsTab.itemSets[setId]) + end, "item set") + return isValueInArray(order, id), id +end + +T.Tool { + name = "items_sets", + title = "Manage item sets", + description = "Lists and manages the open build's item sets (the Items tab's 'Item set' dropdown and its Manage dialog): 'list', " + .. "'select' (makes a set the active one, which changes the calculated stats), 'new' (an empty set named 'title'), 'copy' " + .. "(a copy of 'set' named 'title'), 'rename' and 'delete' (removes the set but not its items; the last set cannot be deleted; " + .. "only delete when the user asked). A set is named by its title or by its 1-based position (an integer). It uses PoB's own " + .. "set list and name dialogs, so the result is what the user would get by clicking. Returns the sets with which is active.", + modifies = true, + destructive = true, + input = { + action = { type = "string", enum = { "list", "select", "new", "copy", "rename", "delete" }, description = "What to do." }, + set = { type = { "string", "integer" }, description = "The set to select, copy, rename or delete: its title or 1-based position (default for copy: the active set)." }, + title = { type = "string", maxLength = 100, description = "Name for new, copy and rename." }, + }, + required = { "action" }, + run = function(args, ctx) + local build = T.Build() + local itemsTab = build.itemsTab + local action = args.action + if action == "list" then + return { itemSets = listSets(itemsTab) } + end + local title + if action == "new" or action == "copy" or action == "rename" then + title = args.title and T.Sanitise(args.title) + if not title or not title:match("%S") then + T.Fail("title is required for %s.", action) + end + end + local position, setId + if args.set ~= nil then + position, setId = findSet(itemsTab, args.set) + elseif action == "copy" then + setId = itemsTab.activeItemSetId + position = isValueInArray(itemsTab.itemSetOrderList, setId) + elseif action ~= "new" then + T.Fail("set is required for %s.", action) + end + -- The Manage dialog's list, over the tab's own set order. + local list = new("ItemSetListControl"):ItemSetListControl(nil, { 0, 0, 300, 200 }, itemsTab) + list.selIndex, list.selValue = position, setId + -- Fills and saves the name dialog RenameSet opened. + local function saveName() + local popup = main.popups[1] + popup.controls.edit:SetText(title, true) + popup.controls.save.onClick() + end + local result = { action = action } + if action == "select" then + if setId == itemsTab.activeItemSetId then + result.note = "That set is already active." + else + list:OnSelClick(position, setId, true) + ctx:Changed() + end + elseif action == "new" then + list.controls.new.onClick() + saveName() + ctx:Changed() + elseif action == "copy" then + list.controls.copy.onClick() + saveName() + ctx:Changed() + elseif action == "rename" then + list.controls.rename.onClick() + saveName() + ctx:Changed() + else + if #itemsTab.itemSetOrderList < 2 then + T.Fail("The build has only one item set, and PoB does not delete the last one.") + end + result.deleted = setTitle(itemsTab.itemSets[setId]) + list:OnSelDelete(position, setId) + main.popups[1].controls.confirm.onClick() + ctx:Changed() + end + result.itemSets = listSets(itemsTab) + return result + end, +} + +------------------------------------------------------------------------------ +-- items_db_search +------------------------------------------------------------------------------ + +T.Tool { + name = "items_db_search", + title = "Search the item databases", + description = "Searches Path of Building's unique item database or its rare item templates, with the same filters and sorting as " + .. "the Items tab's database lists: search text (anywhere, names only or modifiers only), slot, type, and for uniques league, " + .. "requirements (what the character can use now) and source (obtainable, vendor recipe, boss drop, ...). Uniques can also be " + .. "sorted by a stat, which PoB computes by equipping each item in the build's matching slot (slow for broad searches: narrow " + .. "them first). Returns name, base, type, league and source, and the item text with include_text (pass it to simulate or " + .. "items_equip; a unique with several variants uses its default variant unless the 'Selected Variant' line is changed). " + .. "Pass list_filters to get the accepted filter values. Fails while PoB is still loading the databases after start-up.", + readOnly = true, + idempotent = true, + input = { + db = { type = "string", enum = { "unique", "rare" }, description = "Which database (default unique)." }, + search = { type = "string", maxLength = 100, description = "Search text, as typed in the list's search box (PoB's ' or ' and pattern rules apply)." }, + search_mode = { type = "string", description = "Anywhere (default), Names or Modifiers." }, + slot = { type = "string", description = "Slot filter, for example 'Helmet', 'Ring', 'Weapon 1', 'Jewel', 'Flask'." }, + type = { type = "string", description = "Type filter, for example 'Armour', 'Jewellery', 'One Handed Melee', 'Bow', 'Jewel'." }, + league = { type = "string", description = "Uniques: league filter, for example 'No league' (core items) or a league name." }, + requirement = { type = "string", description = "Uniques: 'Any requirements' (default), 'Current level', 'Current attributes' or 'Current useable'." }, + source = { type = "string", description = "Uniques: 'Obtainable' (default), 'Any source', 'Unobtainable', 'Vendor Recipe', 'Upgraded', 'Boss Item', 'Corruption' or 'Core Drop Pool'." }, + sort_by = { type = "string", description = "Uniques: 'Name' (default) or a stat to sort by, for example 'FullDPS', 'Life', 'TotalEHP'." }, + include_text = { type = "boolean", description = "Include each item's full text." }, + list_filters = { type = "boolean", description = "Also return the values each filter accepts." }, + limit = T.PageArgs(25, 100).limit, + offset = T.PageArgs(25, 100).offset, + }, + run = function(args) + local build = T.Build() + local itemsTab = build.itemsTab + local dbType = args.db == "rare" and "RARE" or "UNIQUE" + local db = dbType == "RARE" and main.rareDB or main.uniqueDB + if db.loading then + T.Fail("Path of Building is still loading its item databases; try again in a few seconds.") + end + -- A copy of the Items tab's database list, so the tab's own filters stay as the user left them. + local control = new("ItemDBControl"):ItemDBControl(nil, { 0, 0, 360, 300 }, itemsTab, db, dbType) + control:LoadLeaguesAndTypes() + local c = control.controls + local function filter(dropdown, value, what) + if value == nil then + return + end + if not dropdown then + T.Fail("%s is only a filter of the unique database.", what) + end + dropdown.selIndex = pick(dropdown.list, value, what) + end + filter(c.slot, args.slot, "slot") + filter(c.type, args.type, "type") + filter(c.league, args.league, "league") + filter(c.requirement, args.requirement, "requirement") + filter(c.obtainable, args.source, "source") + filter(c.searchMode, args.search_mode, "search_mode") + if args.search then + c.search:SetText(args.search) + end + local sortedByStat = false + if args.sort_by and args.sort_by:lower() ~= "name" then + if not c.sort then + T.Fail("Only the unique database can be sorted by a stat.") + end + local entry = control.sortDropList[findSortIndex(control.sortDropList, args.sort_by)] + control:SetSortMode(entry.sortMode) + sortedByStat = entry.stat ~= nil + end + -- Sorting by a stat stores measuredPower on the shared database items; keep the values the tab's list has. + local savedPower = { } + for _, item in pairs(db.list) do + savedPower[item] = item.measuredPower + end + -- The list is built by a coroutine the control resumes once per frame; finish it now. + local builder = coroutine.create(control.ListBuilder) + local ok, err + repeat + ok, err = coroutine.resume(builder, control) + until not ok or coroutine.status(builder) == "dead" + local page, paging = T.Page(ok and control.list or { }, args, 25, 100) + local found = { } + for _, item in ipairs(page) do + t_insert(found, { + name = item.name, + base = item.baseName, + type = item.type, + league = item.league, + source = item.source, + levelRequirement = item.requirements and item.requirements.level or nil, + variants = item.variantList and #item.variantList > 1 and #item.variantList or nil, + sortValue = sortedByStat and T.Round(item.measuredPower) or nil, + text = args.include_text and item.raw or nil, + }) + end + for item, power in pairs(savedPower) do + item.measuredPower = power + end + if not ok then + T.Fail("Path of Building's database search failed: %s", tostring(err)) + end + local result = { + db = dbType:lower(), + items = T.Array(found), + page = paging, + sortedBy = sortedByStat and (control.sortDetail.label:gsub("^Sort by ", "")) or "Name", + } + if args.list_filters then + local filters = { slot = control.slotList, type = control.typeList, searchMode = c.searchMode.list } + if c.league then + filters.league = control.leagueList + filters.requirement = c.requirement.list + filters.source = c.obtainable.list + local sorts = { "Name" } + for _, entry in ipairs(control.sortDropList) do + if entry.stat then + t_insert(sorts, entry.stat) + end + end + filters.sortBy = sorts + end + result.filters = filters + end + return result + end, +} + +------------------------------------------------------------------------------ +-- items_craft +------------------------------------------------------------------------------ + +local function parseCraftText(text) + if type(text) ~= "string" or not text:match("%S") then + T.Fail("item (the item text) is required for this action; start with action create.") + end + local item = new("Item"):Item((T.Sanitise((text:gsub("\r\n", "\n"))))) + if not item.base then + T.Fail("Path of Building could not read that item (unknown base type). Use the text returned by items_craft or copied from the game or PoB.") + end + return item +end + +-- Runs fn with item as the Items tab's display item (as double-clicking an item +-- does), then closes the dialogs it opened and puts back the display item and +-- the tab state its dialogs remember. +local function withDisplayItem(itemsTab, item, sortIndex, fn) + local controls = itemsTab.controls + local saved = { + displayItem = itemsTab.displayItem, + snapHScroll = itemsTab.snapHScroll, + sorting = controls.craftingSorting.selIndex, + lastCraftRaritySel = itemsTab.lastCraftRaritySel, + lastCraftTypeSel = itemsTab.lastCraftTypeSel, + lastCraftBaseSel = itemsTab.lastCraftBaseSel, + enchantSlot = itemsTab.enchantSlot, + anointEnchantSlot = itemsTab.anointEnchantSlot, + } + local popups = #main.popups + -- The affix dropdowns are ordered by the tab's "Modifier sorting"; use this call's (Default unless asked). + controls.craftingSorting.selIndex = sortIndex or 1 + local ok, result = pcall(function() + if item then + itemsTab:SetDisplayItem(item) + end + return fn() + end) + while #main.popups > popups do + main:ClosePopup() + end + controls.craftingSorting.selIndex = saved.sorting + itemsTab.lastCraftRaritySel, itemsTab.lastCraftTypeSel, itemsTab.lastCraftBaseSel = saved.lastCraftRaritySel, saved.lastCraftTypeSel, saved.lastCraftBaseSel + itemsTab.enchantSlot, itemsTab.anointEnchantSlot = saved.enchantSlot, saved.anointEnchantSlot + itemsTab:SetDisplayItem(saved.displayItem) + itemsTab.snapHScroll = saved.snapHScroll + if not ok then + error(result, 0) + end + return result +end + +-- Calls the Items tab function behind a button and returns the dialog's controls. +local function openDialog(open) + local before = #main.popups + open() + if #main.popups ~= before + 1 then + T.Fail("Path of Building did not open the dialog for this item.") + end + return main.popups[1].controls +end + +-- Prefix and suffix choices of an item made with "Craft item..." (the displayItemAffix dropdowns). +local function affixSlots(itemsTab) + local item = itemsTab.displayItem + local slots = { } + for i = 1, item.affixLimit or 0 do + local control = itemsTab.controls["displayItemAffix" .. i] + local affix = item[control.outputTable] and item[control.outputTable][control.outputIndex] + local entry = { + type = control.outputTable == "prefixes" and "prefix" or "suffix", + index = control.outputIndex, + } + local mod = affix and item.affixes[affix.modId] + if mod then + local group = control.list[control.selIndex] + local position = type(group) == "table" and group.modList and isValueInArray(group.modList, affix.modId) + entry.modId = affix.modId + entry.affix = mod.affix + entry.lines = T.Array(copyTable(mod)) + entry.tier = position and (#group.modList - position + 1) or nil + entry.tiers = position and #group.modList or nil + entry.roll = type(affix.range) == "number" and T.Round(affix.range, 3) or nil + else + entry.empty = true + end + t_insert(slots, entry) + end + return slots +end + +-- The result every crafting action returns: the item text and what it holds now. +local function craftResult(itemsTab, extra) + local item = itemsTab.displayItem + local result = extra or { } + result.item = item:BuildRaw() + result.name = item.name + result.rarity = item.rarity + result.base = item.baseName + result.mods = T.Array(modLines(item)) + if item.crafted then + result.affixes = affixSlots(itemsTab) + end + return result +end + +-- A page of dropdown entries as options. +local function listOptions(list, args, first, describe) + local options = { } + for i = first or 1, #list do + local entry = list[i] + local option = { label = labelOf(entry) } + if describe then + describe(entry, option) + end + t_insert(options, option) + end + local page, paging = T.Page(options, args, 50) + return { options = page, page = paging } +end + +-- Ids of PoB's mod tables, so options can be named by a key that survives re-sorting. +local function modIdLookup(build, item) + local ids + return function(mod) + if type(mod) ~= "table" then + return nil + end + if not ids then + ids = { } + for _, pool in ipairs({ item.affixes or { }, build.data.veiledMods or { }, build.data.necropolisMods or { } }) do + for id, candidate in pairs(pool) do + if type(id) == "string" and type(candidate) == "table" and not ids[candidate] then + ids[candidate] = id + end + end + end + end + return ids[mod] + end +end + +local function chooseSort(control, sortBy) + if sortBy then + local index = findSortIndex(control.list, sortBy) + if index ~= control.selIndex then + choose(control, index) + end + end +end + +local craftActions = { } + +-- "Craft item..." (ItemsTab:CraftItem): its Type and Base lists. +function craftActions.bases(itemsTab, args) + local p = openDialog(function() itemsTab:CraftItem() end) + local types = p.type.list + if not args.base_type and not args.search then + local list = { } + for i, typeName in ipairs(types) do + choose(p.type, i) + t_insert(list, { type = typeName, bases = #p.base.list }) + end + p.cancel.onClick() + return { baseTypes = list, note = "Pass base_type or search to list bases." } + end + local wantedType = args.base_type and pick(types, args.base_type, "base type") + local search = args.search and args.search:lower() + local bases = { } + for i, typeName in ipairs(types) do + if not wantedType or i == wantedType then + choose(p.type, i) + for _, entry in ipairs(p.base.list) do + local haystack = (entry.searchFilter or entry.name):lower() + if not search or haystack:find(search, 1, true) then + t_insert(bases, { + name = entry.name, + type = typeName, + level = entry.base.req and entry.base.req.level or nil, + implicit = entry.base.implicit, + }) + end + end + end + end + p.cancel.onClick() + local page, paging = T.Page(bases, args, 50) + return { bases = page, page = paging } +end + +-- "Craft item...": Rarity, Name, Type and Base, then Create. +function craftActions.create(itemsTab, args) + if not args.base then + T.Fail("base is required for create (see action bases).") + end + local p = openDialog(function() itemsTab:CraftItem() end) + p.rarity.selIndex = pick(p.rarity.list, args.rarity or "Rare", "rarity", function(entry, want) + return entry.rarity == tostring(want):upper() + end) + if args.name then + p.title:SetText((T.Sanitise(args.name))) + end + local wanted = args.base:lower() + local found + for i = 1, #p.type.list do + choose(p.type, i) + for b, entry in ipairs(p.base.list) do + if entry.name:lower() == wanted then + found = b + break + end + end + if found then + break + end + end + if not found then + T.Fail("Path of Building has no item base named '%s'; find it with action bases.", args.base) + end + p.base.selIndex = found + p.save.onClick() + local result = craftResult(itemsTab) + if not itemsTab.displayItem.crafted and itemsTab.displayItem.rarity ~= "NORMAL" then + result.note = "PoB creates unique and relic items without modifiers (its text editor opens next): add them by editing the returned item text." + end + return result +end + +-- The Prefix/Suffix dropdowns and roll sliders of a crafted magic or rare item. +function craftActions.affix(itemsTab, args) + local item = itemsTab.displayItem + if not item.crafted then + T.Fail("Only items made with action create as magic or rare have prefix and suffix choices; use action modifier for other items.") + end + local outputTable = args.affix_type == "suffix" and "suffixes" or "prefixes" + local control + for i = 1, item.affixLimit do + local candidate = itemsTab.controls["displayItemAffix" .. i] + local affix = item[candidate.outputTable][candidate.outputIndex] + if candidate.outputTable == outputTable + and (args.affix_index and candidate.outputIndex == args.affix_index or not args.affix_index and (not affix or affix.modId == "None")) then + control = candidate + break + end + end + if not control then + if args.affix_index then + T.Fail("This item has no %s %d.", args.affix_type or "prefix", args.affix_index) + end + T.Fail("Every %s of this item is taken; pass affix_index to replace one.", args.affix_type or "prefix") + end + local which = { type = outputTable == "prefixes" and "prefix" or "suffix", index = control.outputIndex } + if args.remove then + if not args.affix_index then + T.Fail("Give affix_index to say which %s to remove.", which.type) + end + choose(control, 1) + return craftResult(itemsTab, { removed = which }) + end + if not args.modifier then + local listing = listOptions(control.list, args, 2, function(entry, option) + option.ids = T.Array(copyTable(entry.modList)) + option.tiers = #entry.modList + end) + listing.affixSlot = which + listing.note = "Pass one of these labels (or a mod id) as modifier; tier 1 is the best tier." + return listing + end + local matchedId + local index = pick(control.list, args.modifier, "modifier", function(entry, want) + if type(entry) == "table" and entry.modList then + for _, modId in ipairs(entry.modList) do + if modId == want then + matchedId = modId + return true + end + end + end + end, 2) + local group = control.list[index] + local count = #group.modList + local position + if matchedId then + position = isValueInArray(group.modList, matchedId) + else + local tier = args.tier or 1 + if tier > count then + T.Fail("This modifier has %d tier%s for this item.", count, count == 1 and "" or "s") + end + position = count - tier + 1 + end + local roll = args.roll or main.defaultItemAffixQuality or 0.5 + if roll == 0 and position > 1 then + -- As UpdateAffixControl: an exact boundary would select the tier below. + roll = 1e-4 + end + -- The roll slider spans every tier; the dropdown's handler reads it. + control.slider.val = (position - 1 + roll) / count + choose(control, index) + return craftResult(itemsTab, { set = which }) +end + +-- The "Add modifier..." dialog (ItemsTab:AddCustomModifierToDisplayItem). +function craftActions.modifier(itemsTab, args, build) + if not itemsTab.controls.displayItemAddCustom:GetProperty("shown") then + T.Fail("PoB offers 'Add modifier...' only for magic and rare items (and rare-like uniques).") + end + local p = openDialog(function() itemsTab:AddCustomModifierToDisplayItem() end) + local sources = p.source.list + local sourceRef = args.source or (args.custom and "CUSTOM") + if sourceRef then + local index = pick(sources, sourceRef, "source", function(entry, want) + return entry.sourceId:lower() == tostring(want):lower() + end) + if index ~= p.source.selIndex then + choose(p.source, index) + end + end + local source = sources[p.source.selIndex] + local sourceLabels = { } + for _, entry in ipairs(sources) do + t_insert(sourceLabels, entry.label) + end + if source.sourceId == "CUSTOM" then + if not args.custom then + return { sources = sourceLabels, source = source.label, note = "Pass custom with the modifier line to add." } + end + p.custom:SetText((T.Sanitise(args.custom))) + p.save.onClick() + return craftResult(itemsTab, { added = args.custom }) + end + chooseSort(p.sort, args.sort_by) + local idOf = modIdLookup(build, itemsTab.displayItem) + if not args.modifier then + local listing = listOptions(p.modSelect.list, args, 1, function(entry, option) + option.id = idOf(entry.mod) + option.sortValue = T.Round(entry.sortValue) + end) + listing.sources = sourceLabels + listing.source = source.label + return listing + end + local index = pick(p.modSelect.list, args.modifier, "modifier", function(entry, want) + return idOf(entry.mod) == want + end) + local chosen = p.modSelect.list[index] + p.modSelect.selIndex = index + p.save.onClick() + return craftResult(itemsTab, { added = labelOf(chosen), source = source.label }) +end + +-- The "Add Implicit..." dialog (Modules/AddImplicitPopup). +function craftActions.implicit(itemsTab, args, build) + local button = itemsTab.controls.displayItemAddImplicit + if not button:GetProperty("shown") then + T.Fail("PoB offers 'Add Implicit...' only for normal, magic and rare equipment, and corruptible items whose implicits can change.") + end + local p = openDialog(button.onClick) + local sources = p.source.list + local sourceRef = args.source or (args.custom and "CUSTOM") + if sourceRef then + local index = pick(sources, sourceRef, "source", function(entry, want) + return entry.sourceId:lower() == tostring(want):lower() + end) + if index ~= p.source.selIndex then + choose(p.source, index) + end + end + local source = sources[p.source.selIndex] + local sourceLabels = { } + for _, entry in ipairs(sources) do + t_insert(sourceLabels, entry.label) + end + if source.sourceId == "CUSTOM" then + if not args.custom then + return { sources = sourceLabels, source = source.label, note = "Pass custom with the implicit line to add." } + end + p.custom:SetText((T.Sanitise(args.custom))) + p.save.onClick() + return craftResult(itemsTab, { added = args.custom }) + end + chooseSort(p.sort, args.sort_by) + if not args.group then + local listing = listOptions(p.modGroupSelect.list, args) + listing.sources = sourceLabels + listing.source = source.label + listing.note = "These are implicit types: pass one as group" .. (p.modSelect:GetProperty("shown") and ", then a modifier of that type." or ".") + return listing + end + choose(p.modGroupSelect, pick(p.modGroupSelect.list, args.group, "implicit type")) + local added = labelOf(p.modGroupSelect.list[p.modGroupSelect.selIndex]) + if p.modSelect:GetProperty("shown") then + local idOf = modIdLookup(build, itemsTab.displayItem) + if not args.modifier then + local listing = listOptions(p.modSelect.list, args, 1, function(entry, option) + option.id = idOf(entry.mod) + end) + listing.group = added + return listing + end + local index = pick(p.modSelect.list, args.modifier, "modifier", function(entry, want) + return idOf(entry.mod) == want + end) + p.modSelect.selIndex = index + added = labelOf(p.modSelect.list[index]) + end + p.save.onClick() + return craftResult(itemsTab, { added = added, source = source.label }) +end + +-- The "Change Enchantment..." dialogs (ItemsTab:EnchantDisplayItem). +function craftActions.enchant(itemsTab, args) + local slotNum = args.enchant_slot or 1 + if slotNum > 2 then + T.Fail("Items have at most two enchantment slots.") + end + local button = slotNum == 1 and itemsTab.controls.displayItemEnchant or itemsTab.controls.displayItemEnchant2 + if not button:GetProperty("shown") then + T.Fail(slotNum == 1 and "PoB has no enchantments for this item." or "A second enchantment needs an item that can have two and already has one.") + end + local p = openDialog(function() itemsTab:EnchantDisplayItem(slotNum) end) + if args.remove then + p.remove.onClick() + return craftResult(itemsTab, { removed = true }) + end + if p.skill then + if args.all_skills and p.allSkills:IsEnabled() and not p.allSkills.state then + p.allSkills.state = true + p.allSkills.changeFunc(true) + end + if args.skill then + choose(p.skill, pick(p.skill.list, args.skill, "skill")) + end + end + if args.source then + choose(p.enchantmentSource, pick(p.enchantmentSource.list, args.source, "enchantment source", function(entry, want) + return entry.name:lower() == tostring(want):lower() + end)) + end + chooseSort(p.sort, args.sort_by) + if not args.modifier then + local listing = listOptions(p.enchantment.list, args, 1, function(entry, option) + option.sortValue = T.Round(entry.sortValue) + end) + if p.skill then + listing.skill = labelOf(p.skill.list[p.skill.selIndex]) + listing.skills = #p.skill.list <= 60 and p.skill.list or nil + end + local sources = { } + for _, entry in ipairs(p.enchantmentSource.list) do + t_insert(sources, entry.label) + end + listing.sources = sources + listing.source = p.enchantmentSource.list[p.enchantmentSource.selIndex].label + return listing + end + local index = pick(p.enchantment.list, args.modifier, "enchantment") + p.enchantment.selIndex = index + local line = p.enchantment.list[index].line + p.save.onClick() + return craftResult(itemsTab, { added = line }) +end + +-- The "Anoint..." dialogs (ItemsTab:AnointDisplayItem and its NotableDBControl). +function craftActions.anoint(itemsTab, args, build) + local slotNum = args.enchant_slot or 1 + local buttons = { "displayItemAnoint", "displayItemAnoint2", "displayItemAnoint3", "displayItemAnoint4" } + local button = itemsTab.controls[buttons[slotNum]] + if not button or not button:GetProperty("shown") then + T.Fail(slotNum == 1 and "This item cannot be anointed." or "This item has no anoint slot %d yet (fill the earlier ones first).", slotNum) + end + local p = openDialog(function() itemsTab:AnointDisplayItem(slotNum) end) + local notableDB = p.notableDB + if args.remove then + notableDB.selValue = nil + p.save.onClick() + return craftResult(itemsTab, { removed = true }) + end + if not args.modifier then + if args.search then + notableDB.controls.search:SetText(args.search) + end + if args.sort_by then + notableDB:SetSortMode(notableDB.sortDropList[findSortIndex(notableDB.sortDropList, args.sort_by)].sortMode) + end + local builder = coroutine.create(notableDB.ListBuilder) + local ok, err + repeat + ok, err = coroutine.resume(builder, notableDB) + until not ok or coroutine.status(builder) == "dead" + if not ok then + T.Fail("Path of Building's notable list failed: %s", tostring(err)) + end + local sorted = notableDB.sortDetail and notableDB.sortDetail.stat + local listing = listOptions(notableDB.list, args, 1, function(node, option) + option.label = node.dn + option.recipe = T.Array(copyTable(node.recipe)) + option.stats = T.Array(copyTable(node.sd)) + option.sortValue = sorted and T.Round(node.measuredPower) or nil + end) + listing.note = "Pass a notable's name as modifier." + return listing + end + local notables = { } + for _, node in pairs(build.spec.tree.nodes) do + if node.recipe and #node.recipe >= 1 then + t_insert(notables, node) + end + end + local node = T.Find(notables, args.modifier, function(candidate) + return candidate.dn + end, "anointable notable") + notableDB.selValue = node + p.save.onClick() + return craftResult(itemsTab, { added = "Allocates " .. node.dn }) +end + +-- The "Corrupt..." dialog (ItemsTab:CorruptDisplayItem). +function craftActions.corrupt(itemsTab, args, build) + if not itemsTab.controls.displayItemCorrupt:GetProperty("shown") then + T.Fail("PoB cannot corrupt this item (it is not corruptible, or already corrupted).") + end + local p = openDialog(function() itemsTab:CorruptDisplayItem() end) + if args.source then + local index = pick(p.source.list, args.source, "corruption source") + if index ~= p.source.selIndex then + choose(p.source, index) + end + end + chooseSort(p.sort, args.sort_by) + local slots = { } + for i = 1, 5 do + if p["implicit" .. i] and p["implicit" .. i].shown == true then + t_insert(slots, i) + end + end + local rollLines = { } + for i = 1, #itemsTab.displayItem.explicitModLines do + if p["rollRangeSlider" .. i] then + t_insert(rollLines, { index = i, label = T.Clean(p["rollRangeLabel" .. i].label):gsub("\n", " ") }) + end + end + local idOf = modIdLookup(build, itemsTab.displayItem) + if args.implicits == nil and args.rolls == nil then + local implicitSlots = { } + for _, i in ipairs(slots) do + local listing = listOptions(p["implicit" .. i].list, args, 2, function(entry, option) + option.id = idOf(entry.mod) + end) + listing.slot = i + t_insert(implicitSlots, listing) + end + local lines = { } + for _, line in ipairs(rollLines) do + t_insert(lines, line.label) + end + return { + source = p.source.list[p.source.selIndex], + sources = p.source.list, + implicitSlots = T.Array(implicitSlots), + rollLines = lines[1] and lines or nil, + implicitsCannotBeChanged = itemsTab.displayItem.implicitsCannotBeChanged or nil, + note = "Pass implicits (one per slot, in order; [] corrupts without new implicits) or, for uniques, rolls.", + } + end + if args.implicits and args.rolls then + T.Fail("Pass implicits or rolls, not both: PoB corrupts with one or the other.") + end + local chosen = { } + if args.rolls then + if not rollLines[1] then + T.Fail("PoB offers roll ranges only for unique and relic items with lines that can change.") + end + p.rolls.onClick() + for _, roll in ipairs(args.rolls) do + local line = rollLines[pick(rollLines, roll.line, "roll line")] + local slider = p["rollRangeSlider" .. line.index] + -- SetVal only calls its handler on a change. + slider.val = -1 + slider:SetVal((roll.value - 0.78) / 0.44) + t_insert(chosen, T.Clean(p["rollRangeLabel" .. line.index].label)) + end + else + if #args.implicits > 0 and not slots[1] then + T.Fail("PoB cannot change the implicits of this item.") + end + for n, want in ipairs(args.implicits) do + local slot = slots[n] + if not slot then + T.Fail("PoB shows %d implicit choice%s for this source.", #slots, #slots == 1 and "" or "s") + end + if want:match("%S") and want:lower() ~= "none" then + -- Each choice rebuilds the other dropdowns, so it is found in the list as it is now. + local control = p["implicit" .. slot] + local index = pick(control.list, want, "implicit", function(entry, wanted) + return idOf(entry.mod) == wanted + end, 2) + control.selIndex = index + control.selFunc() + t_insert(chosen, labelOf(control.list[control.selIndex])) + end + end + end + p.save.onClick() + return craftResult(itemsTab, { chosen = T.Array(chosen) }) +end + +-- Parses "R-G-B B" into sockets { color, group }. +local function parseSockets(text) + local sockets = { } + local group = 0 + for word in text:upper():gmatch("%S+") do + for color in word:gmatch("[^%-]+") do + if not color:match("^[RGBW]$") then + T.Fail("sockets must be written like 'R-G-B B' (colours R, G, B, W; '-' links, space separates groups).") + end + t_insert(sockets, { color = color, group = group }) + end + group = group + 1 + end + return sockets +end + +-- The display item's own controls (ItemsTab constructor). +function craftActions.properties(itemsTab, args) + local c = itemsTab.controls + local applied = { } + local function shown(control) + return control:GetProperty("shown") + end + if args.influences then + if not shown(c.displayItemInfluence) then + T.Fail("PoB offers no influence for this item.") + end + local picks = { 1, 1 } + for k, name in ipairs(args.influences) do + if name:lower() ~= "none" then + picks[k] = pick(c.displayItemInfluence.list, name, "influence", nil, 2) + end + end + c.displayItemInfluence2.selIndex = picks[2] + choose(c.displayItemInfluence, picks[1]) + applied.influences = true + end + if args.quality ~= nil then + if not shown(c.displayItemQualityEdit) then + T.Fail("This item has no quality in PoB.") + end + c.displayItemQualityEdit:SetText(tostring(args.quality), true) + applied.quality = true + end + if args.catalyst then + if not shown(c.displayItemCatalyst) then + T.Fail("PoB offers catalysts only for crafted (or tagged) amulets, rings and belts.") + end + choose(c.displayItemCatalyst, pick(c.displayItemCatalyst.list, args.catalyst, "catalyst")) + applied.catalyst = true + end + if args.catalyst_quality ~= nil then + if not shown(c.displayItemCatalystQualityEdit) then + T.Fail("Choose a catalyst first.") + end + c.displayItemCatalystQualityEdit:SetText(tostring(args.catalyst_quality), true) + applied.catalystQuality = true + end + if args.variant then + local item = itemsTab.displayItem + if item.usesVariantGroups or not shown(c.displayItemVariant) then + T.Fail("This item has no single variant list; change its 'Selected Variant' line in the item text instead.") + end + choose(c.displayItemVariant, pick(c.displayItemVariant.list, args.variant, "variant")) + applied.variant = true + end + if args.cluster_skill then + if not shown(c.displayItemClusterJewelSkill) then + T.Fail("cluster_skill applies to cluster jewels made with action create.") + end + choose(c.displayItemClusterJewelSkill, pick(c.displayItemClusterJewelSkill.list, args.cluster_skill, "cluster jewel skill")) + applied.clusterSkill = true + end + if args.cluster_passives then + local cluster = itemsTab.displayItem.clusterJewel + if not shown(c.displayItemClusterJewelSkill) or not cluster then + T.Fail("cluster_passives applies to cluster jewels made with action create.") + end + if args.cluster_passives < cluster.minNodes or args.cluster_passives > cluster.maxNodes then + T.Fail("cluster_passives must be %d-%d for this jewel.", cluster.minNodes, cluster.maxNodes) + end + local slider = c.displayItemClusterJewelNodeCount + slider.val = -1 + slider:SetVal((args.cluster_passives - cluster.minNodes) / (cluster.maxNodes - cluster.minNodes)) + applied.clusterPassives = true + end + if args.sockets then + local item = itemsTab.displayItem + local wanted = parseSockets(args.sockets) + local current = #item.sockets - item.abyssalSocketCount + if #wanted > item.selectableSocketCount then + T.Fail("This item can have at most %d sockets.", item.selectableSocketCount) + elseif #wanted < current then + T.Fail("PoB only adds sockets with its controls; to have fewer, change the 'Sockets:' line of the item text.") + end + for _ = current + 1, #wanted do + c.displayItemAddSocket.onClick() + end + for i, socket in ipairs(wanted) do + local drop = c["displayItemSocket" .. i] + for index, entry in ipairs(drop.list) do + if entry.color == socket.color and itemsTab.displayItem.sockets[i].color ~= socket.color then + choose(drop, index) + end + end + if i > 1 then + local link = c["displayItemLink" .. (i - 1)] + local linked = socket.group == wanted[i - 1].group + if (itemsTab.displayItem.sockets[i].group == itemsTab.displayItem.sockets[i - 1].group) ~= linked then + link.state = linked + link.changeFunc(linked) + end + end + end + applied.sockets = true + end + if args.ranges then + local item = itemsTab.displayItem + for _, range in ipairs(args.ranges) do + local list = itemsTab.displayItem.rangeLineList + local index = pick(list, range.line, "range line", function(modLine, want) + return T.Clean(modLine.line):lower() == tostring(want):lower() + end) + if main.showAllItemAffixes and item.rarity == "UNIQUE" then + local slider = c["displayItemStackedRangeSlider" .. index] + slider.val = -1 + slider:SetVal(range.roll) + else + local drop = c.displayItemRangeLine + for d, entry in ipairs(drop.list) do + if entry.modLine == list[index] then + choose(drop, d) + end + end + c.displayItemRangeSlider.val = -1 + c.displayItemRangeSlider:SetVal(range.roll) + end + end + applied.ranges = true + end + if args.remove_modifiers then + for _, want in ipairs(args.remove_modifiers) do + -- The Remove buttons UpdateCustomControls made, in its order. + local item = itemsTab.displayItem + local removable = { } + local lines = copyTable(item.explicitModLines, true) + for _, modLine in ipairs(item.crucibleModLines or { }) do + t_insert(lines, modLine) + end + for _, modLine in ipairs(lines) do + if modLine.custom or modLine.crafted or modLine.crucible then + local text = itemLib.formatModLine(modLine) + if text then + t_insert(removable, { label = T.Clean(text), button = c["displayItemCustomModifierRemove" .. (#removable + 1)] }) + end + end + end + removable[pick(removable, want, "removable (crafted or custom) modifier")].button.onClick() + end + applied.removed = true + end + if not next(applied) then + local item = itemsTab.displayItem + local rangeLines = { } + for _, modLine in ipairs(item.rangeLineList or { }) do + t_insert(rangeLines, { line = T.Clean(modLine.line), roll = T.Round(modLine.range, 3) }) + end + return craftResult(itemsTab, { + quality = item.quality, + sockets = socketString(item), + maxSockets = item.selectableSocketCount > 0 and item.selectableSocketCount or nil, + influenceOptions = shown(c.displayItemInfluence) and c.displayItemInfluence.list or nil, + catalystOptions = shown(c.displayItemCatalyst) and c.displayItemCatalyst.list or nil, + variants = not item.usesVariantGroups and shown(c.displayItemVariant) and item.variantList or nil, + rangeLines = rangeLines[1] and rangeLines or nil, + clusterSkills = shown(c.displayItemClusterJewelSkill) and c.displayItemClusterJewelSkill.list or nil, + }) + end + return craftResult(itemsTab) +end + +T.Tool { + name = "items_craft", + title = "Craft an item", + description = "Builds an item with Path of Building's own crafting controls and returns its text; nothing is added to the build " + .. "(test it with simulate, add it with items_equip). Every action except bases and create takes the item text in 'item' and " + .. "returns the changed text in 'item'; when the choice it needs is left out, it lists the options instead (paged, labels to " + .. "pass back). Actions: 'bases' (base types, or bases of base_type / matching search), 'create' (a new item from 'base', " + .. "rarity default rare, optional name), 'affix' (a crafted magic or rare item's prefix or suffix: modifier by label or mod id, " + .. "tier 1 = best, roll 0-1, or remove), 'modifier' (the 'Add modifier...' dialog: source such as Crafting Bench, Essence, " + .. "Veiled, Fossil, Prefix, Suffix, or custom text), 'implicit' (Searing Exarch, Eater of Worlds, Vestigial or custom " + .. "implicits: group then modifier), 'enchant' (enchant_slot, skill, source, modifier or remove), 'anoint' (a notable by " + .. "name, or search to list), 'corrupt' (implicits by name, or rolls for uniques), 'properties' (influences, quality, " + .. "catalyst, variant, sockets such as 'R-G-B B', ranges of variable lines, remove crafted or custom modifiers, cluster " + .. "jewel skill and passives; with none given it shows the current values and options). sort_by orders option lists by a " + .. "stat PoB computes for this build (slow on long lists). The Items tab's own displayed item and settings are left as they were.", + readOnly = true, + idempotent = true, + usesDialog = true, + input = { + action = { type = "string", enum = { "bases", "create", "affix", "modifier", "implicit", "enchant", "anoint", "corrupt", "properties" }, description = "What to do." }, + item = { type = "string", maxLength = 20000, description = "The item text to change (from create or a previous call, or copied from the game or PoB)." }, + base_type = { type = "string", description = "bases: the base type, for example 'Helmet: Armour' or 'Ring'." }, + search = { type = "string", maxLength = 100, description = "bases: text in the base name or implicit; anoint: notable search." }, + base = { type = "string", description = "create: the base, for example 'Hubris Circlet'." }, + rarity = { type = "string", description = "create: Normal, Magic, Rare (default), Unique or Relic." }, + name = { type = "string", maxLength = 100, description = "create: the name of a rare or unique item." }, + affix_type = { type = "string", enum = { "prefix", "suffix" }, description = "affix: prefix (default) or suffix." }, + affix_index = { type = "integer", minimum = 1, maximum = 6, description = "affix: which prefix or suffix (default: the first empty one)." }, + tier = { type = "integer", minimum = 1, maximum = 30, description = "affix: tier, 1 = best (default 1)." }, + roll = { type = "number", minimum = 0, maximum = 1, description = "affix: roll within the tier, 0 = lowest, 1 = highest (default PoB's affix quality setting)." }, + remove = { type = "boolean", description = "affix, enchant, anoint: remove instead of set." }, + source = { type = "string", description = "modifier, implicit, enchant, corrupt: the dialog's Source choice." }, + modifier = { type = "string", maxLength = 500, description = "affix, modifier, implicit, enchant, anoint: the option to apply, by label (or a unique part of it) or mod id." }, + group = { type = "string", maxLength = 500, description = "implicit: the implicit type." }, + custom = { type = "string", maxLength = 500, description = "modifier, implicit: a custom modifier line to add." }, + enchant_slot = { type = "integer", minimum = 1, maximum = 4, description = "enchant (1-2), anoint (1-4): which slot (default 1)." }, + skill = { type = "string", description = "enchant: the skill whose enchantments to use (helmet enchants)." }, + all_skills = { type = "boolean", description = "enchant: offer skills the build does not use." }, + implicits = { type = "array", items = { type = "string", maxLength = 500 }, maxItems = 5, description = "corrupt: the implicit for each choice in order ('None' to leave one empty; [] to corrupt without implicits)." }, + rolls = { + type = "array", maxItems = 20, description = "corrupt (uniques): corrupted roll range for lines.", + items = { type = "object", properties = { line = { type = "string" }, value = { type = "number", minimum = 0.78, maximum = 1.22 } }, required = { "line", "value" }, additionalProperties = false }, + }, + influences = { type = "array", items = { type = "string" }, maxItems = 2, description = "properties: up to two influences, for example ['Shaper', 'Hunter'] (['None'] clears)." }, + quality = { type = "integer", minimum = 0, maximum = 99, description = "properties: quality." }, + catalyst = { type = "string", description = "properties: catalyst for amulets, rings and belts, for example 'Prismatic'." }, + catalyst_quality = { type = "integer", minimum = 0, maximum = 99, description = "properties: catalyst quality." }, + variant = { type = "string", description = "properties: the variant of a unique with variants." }, + sockets = { type = "string", maxLength = 20, description = "properties: sockets like 'R-R-G B' (only adding sockets is possible)." }, + ranges = { + type = "array", maxItems = 20, description = "properties: rolls of variable lines (for example on uniques), 0-1.", + items = { type = "object", properties = { line = { type = "string" }, roll = { type = "number", minimum = 0, maximum = 1 } }, required = { "line", "roll" }, additionalProperties = false }, + }, + remove_modifiers = { type = "array", items = { type = "string", maxLength = 500 }, maxItems = 10, description = "properties: crafted or custom modifier lines to remove." }, + cluster_skill = { type = "string", description = "properties: a crafted cluster jewel's skill, for example 'Fire Damage'." }, + cluster_passives = { type = "integer", minimum = 2, maximum = 12, description = "properties: a crafted cluster jewel's number of added passives." }, + sort_by = { type = "string", description = "Order option lists by a stat, for example 'FullDPS' or 'Life'." }, + limit = T.PageArgs(50).limit, + offset = T.PageArgs(50).offset, + }, + required = { "action" }, + run = function(args) + local build = T.Build() + local itemsTab = build.itemsTab + local action = args.action + local item + if action ~= "bases" and action ~= "create" then + item = parseCraftText(args.item) + end + local sortIndex + if action == "affix" and args.sort_by then + sortIndex = findSortIndex(itemsTab.controls.craftingSorting.list, args.sort_by) + end + return withDisplayItem(itemsTab, item, sortIndex, function() + return craftActions[action](itemsTab, args, build) + end) + end, +} + +------------------------------------------------------------------------------ +-- trade_query +------------------------------------------------------------------------------ + +-- The trader's listing types, in the order of its dropdown (TradeQuery:PriceItem) +-- and of the ids TradeQueryGenerator:FinishQuery sends. +local TRADE_TYPES = { "instant_buyout", "instant_or_in_person", "in_person_online_in_league", "in_person_online", "any" } + +-- Currencies of the generator's "Max Price" dropdown (TradeQueryGenerator currencyTable). +local CURRENCIES = { "chaos", "divine", "alch", "alt", "chrome", "exalted", "blessed", "chisel", "gcp", "jewellers", "scour", "regret", "fusing", "chance", "regal", "vaal" } + +-- Trade site stat id -> text, from the stat list PoB ships (Data/TradeSiteStats). +local tradeStatText +local function tradeStatLookup() + if not tradeStatText then + tradeStatText = { } + for _, category in ipairs(tradeHelpers.getTradeStats()) do + for _, entry in ipairs(category.entries or { }) do + tradeStatText[entry.id] = entry.text + end + end + end + return tradeStatText +end + +-- The weights the trader's "Adjust search weights" dialog offers (TradeQuery:SetStatWeights). +local function statWeights(list) + local weights = { } + for _, want in ipairs(list) do + local found + for _, stat in ipairs(data.powerStatList) do + if not stat.ignoreForItems and stat.label ~= "Name" and stat.stat + and (stat.stat:lower() == want.stat:lower() or stat.label:lower() == want.stat:lower()) then + found = stat + end + end + if not found then + local names = { } + for _, stat in ipairs(data.powerStatList) do + if not stat.ignoreForItems and stat.stat then + t_insert(names, stat.stat) + end + end + T.Fail("Unknown weight stat '%s'. Stats: %s", want.stat, t_concat(names, ", ")) + end + t_insert(weights, { label = found.label, stat = found.stat, transform = found.transform, weightMult = want.weight }) + end + return weights +end + +local function tradeStatFilters(list, what) + if not list then + return nil + end + local stats = tradeStatLookup() + local filters = { } + for _, entry in ipairs(list) do + if not stats[entry.id] then + T.Fail("'%s' in %s is not a trade site stat id PoB knows (for example 'explicit.stat_3299347043' or 'pseudo.pseudo_total_life').", entry.id, what) + end + t_insert(filters, { tradeId = entry.id, value = entry.min }) + end + return filters +end + +local function statFilterList(description) + return { + type = "array", maxItems = 5, description = description, + items = { type = "object", properties = { id = { type = "string" }, min = { type = "number" } }, required = { "id" }, additionalProperties = false }, + } +end + +T.Tool { + name = "trade_query", + title = "Weighted trade search", + description = "Generates the weighted trade search Path of Building's trader ('Trade for these items', 'Find best') builds for " + .. "an equipment slot or jewel socket of the open build: PoB measures every modifier that can appear on that item type with " + .. "the build's calculator, weights each by how much it improves the chosen stats (default: the build's saved trader weights, " + .. "else Full DPS 1.0 and Effective Hit Pool 0.5), and sets the minimum weighted sum to half the current item's value. Returns " + .. "the query JSON for the pathofexile.com trade API, the weighted stats in readable form, and a trade site URL when a league " + .. "is known (pass league, for example 'Standard' or the current challenge league) and compression is available. Nothing is " + .. "sent to the trade site and nothing is bought; it uses only data PoB ships, and takes a few seconds. Options mirror the " + .. "trader's Query Options dialog.", + readOnly = true, + idempotent = true, + usesDialog = true, + input = { + slot = { type = "string", description = "Slot, for example 'Helmet', 'Ring 1', 'Weapon 1', 'Flask 2' or a jewel socket like 'Socket #1'." }, + league = { type = "string", maxLength = 100, description = "Trade league for the URL (default: the league chosen in PoB's trader, if any)." }, + realm = { type = "string", enum = { "pc", "xbox", "sony" }, description = "Trade realm for the URL (default pc)." }, + trade_type = { type = "string", enum = TRADE_TYPES, description = "Listings to search (default: the trader's choice, else instant_buyout)." }, + weights = { + type = "array", maxItems = 20, description = "Stats to weight, for example [{stat:'FullDPS', weight:1}, {stat:'Life', weight:0.5}].", + items = { type = "object", properties = { stat = { type = "string" }, weight = { type = "number", minimum = 0.01, maximum = 1 } }, required = { "stat", "weight" }, additionalProperties = false }, + }, + include_corrupted = { type = "boolean", description = "Weight corruption implicits (default true)." }, + include_mirrored = { type = "boolean", description = "Allow mirrored items (default true)." }, + include_scourge = { type = "boolean", description = "Weight scourge modifiers (default true in Standard and Hardcore, otherwise not offered)." }, + include_talisman = { type = "boolean", description = "Amulet: weight talisman modifiers (default false)." }, + eldritch = { type = "string", enum = { "Copy Current", "Keep regular", "Keep regular+presence", "Remove" }, description = "Helmet, body armour, gloves, boots, amulet: eldritch implicits ('Keep ...' weights them; default Copy Current)." }, + jewel_type = { type = "string", enum = { "Base", "Abyss" }, description = "Jewel sockets: which jewels to search (default Base)." }, + max_price = { type = "integer", minimum = 1, description = "Maximum price." }, + max_price_currency = { type = "string", enum = CURRENCIES, description = "Currency of max_price (default: chaos orb equivalent)." }, + max_level = { type = "integer", minimum = 1, maximum = 100, description = "Maximum level requirement." }, + sockets = { type = "integer", minimum = 1, maximum = 6, description = "Number of empty sockets." }, + links = { type = "integer", minimum = 1, maximum = 6, description = "Number of links." }, + required_stats = statFilterList("Stats the item must have, by trade site stat id (as in weightedStats), with an optional minimum."), + blocked_stats = statFilterList("Stats the item must not have, by trade site stat id."), + }, + required = { "slot" }, + run = function(args) + local build = T.Build() + local itemsTab = build.itemsTab + itemsTab:UpdateSockets() + local slot = T.FindSlot(build, args.slot) + if slot.inactive then + T.Fail("%s is not in use (an unallocated jewel socket or a missing abyssal socket).", slotLabel(slot)) + end + local tradeQuery = itemsTab.tradeQuery + local league = args.league or tradeQuery.pbLeague + local weights + if args.weights then + weights = statWeights(args.weights) + elseif tradeQuery.statSortSelectionList and tradeQuery.statSortSelectionList[1] then + weights = tradeQuery.statSortSelectionList + else + weights = statWeights({ { stat = "FullDPS", weight = 1 }, { stat = "TotalEHP", weight = 0.5 } }) + end + local isJewel = slot.slotName:find("Jewel") ~= nil + local isAbyssal = slot.slotName:find("Abyssal") ~= nil + -- The Query Options dialog's choices and its defaults (TradeQueryGenerator:RequestQuery). + local options = { + statWeights = weights, + includeCorrupted = args.include_corrupted ~= false, + includeMirrored = args.include_mirrored ~= false, + maxPrice = args.max_price, + maxPriceType = args.max_price and args.max_price_currency or nil, + maxLevel = args.max_level, + sockets = args.sockets, + links = args.links, + requiredMods = tradeStatFilters(args.required_stats, "required_stats"), + blockedMods = tradeStatFilters(args.blocked_stats, "blocked_stats"), + } + if not isJewel and not isAbyssal and (league == "Standard" or league == "Hardcore") then + options.includeScourge = args.include_scourge ~= false + end + if slot.slotName == "Amulet" then + options.includeTalisman = args.include_talisman == true + end + if ({ ["Body Armour"] = true, Helmet = true, Gloves = true, Boots = true, Amulet = true })[slot.slotName] then + options.includeEldritch = args.eldritch or "Copy Current" + end + if isAbyssal then + options.jewelType = "Abyss" + elseif isJewel then + options.jewelType = args.jewel_type or "Base" + end + local tradeTypeIndex = args.trade_type and isValueInArray(TRADE_TYPES, args.trade_type) or tradeQuery.tradeTypeIndex or 1 + + -- A generator of our own, so the trader's remembered choices stay as they are. + local generator = new("TradeQueryGenerator"):TradeQueryGenerator(tradeQuery) + local query, message + generator.requesterContext = { } + generator.requesterCallback = function(_, generated, errMsg) + query, message = generated, errMsg + end + generator.tradeTypeIndex = tradeTypeIndex + generator:StartQuery(slot, options) + local co = generator.calcContext.co + if not co then + T.Fail("Path of Building's trader has no weighted search for %s.", slotLabel(slot)) + end + -- The work TradeQueryGenerator:OnFrame spreads over frames, run to the end here. + while coroutine.status(co) ~= "dead" do + local ok, err = coroutine.resume(co, generator) + if not ok then + T.Fail("Path of Building could not weight the modifiers: %s", tostring(err)) + end + end + generator.calcContext.co = nil + generator:FinishQuery() + if message then + T.Fail("%s", message) + end + if not query then + T.Fail("Path of Building generated no trade query.") + end + local stats = tradeStatLookup() + local weighted = { } + for _, filter in ipairs(query.stats[1].filters) do + t_insert(weighted, { id = filter.id, text = stats[filter.id], weight = T.Round(filter.value.weight) }) + end + local usedWeights = { } + for _, weight in ipairs(weights) do + t_insert(usedWeights, { stat = weight.stat, label = weight.label, weight = T.Round(weight.weightMult) }) + end + local result = { + slot = slot.slotName, + category = generator.calcContext.itemCategoryQueryStr, + weights = usedWeights, + minimumWeightedSum = T.Round(query.stats[1].value.min), + weightedStats = T.Array(weighted), + query = query, + } + -- As the trader composes the link when it is not logged in. + local encoded = league and tradeHelpers.B64GzipEncode(dkjson.encode(query)) + if league and encoded and encoded ~= "" then + local realm = args.realm or (tradeQuery.pbRealm ~= "" and tradeQuery.pbRealm) or "pc" + result.url = tradeQuery.tradeQueryRequests:buildUrl(tradeQuery.hostName .. "trade/search", realm, league) .. "/" .. encoded + result.league = league + elseif not league then + result.note = "Pass league to get a trade site link." + else + result.note = "Path of Building could not compress the query into a trade site link here; use the query with the trade site's search API." + end + return result + end, +} diff --git a/src/Modules/McpTools/Skills.lua b/src/Modules/McpTools/Skills.lua index c3f1f30bfa6..7cb5197c009 100644 --- a/src/Modules/McpTools/Skills.lua +++ b/src/Modules/McpTools/Skills.lua @@ -1,6 +1,1012 @@ -- Path of Building -- -- Module: MCP Tools - Skills +-- The Skills tab: socket groups and their gems, the main skill, the spectre +-- library, skill sets, and support gems ranked by the gem selector's DPS sort. -- local T = ... +local t_insert = table.insert +local t_concat = table.concat + +-- The name dialogs of the set lists (SkillSetListControl/ConfigSetListControl:RenameSet) take at most 100 characters. +local SET_TITLE_MAX = 100 + +-- A gem line of SkillsTab:PasteSocketGroup ("Fireball 20/0 1", "Added Fire Damage 20/20 DISABLED 1"). +local PASTE_GEM_PATTERN = "([ %a']+) (%d+)/(%d+) ?(%a*) (%d+)" + +-- GemSelectControl:OnKeyDown: the gem type buttons set sortGemsBy to these tags. +local GEM_TYPE_TAGS = { support = "support", active = "grants_active_skill" } + +local function grantedEffectOf(gem) + return gem.grantedEffect or (gem.gemData and gem.gemData.grantedEffect) +end + +-- The name the Skills tab shows for a gem (SkillsTab:AddSocketGroupTooltip). +local function gemName(gem) + return T.Clean((gem.grantedEffect and gem.grantedEffect.name) or (gem.gemData and gem.gemData.name) or gem.nameSpec or "?") +end + +-- The name the Skills tab shows for a socket group (CalcSetup sets displayLabel). +local function groupName(group) + if group.displayLabel then + return T.Clean(group.displayLabel) + end + return group.label and group.label:match("%S") and T.Clean(group.label) or "<No active skills>" +end + +-- A dropdown entry's text. +local function dropLabel(entry) + if type(entry) == "table" then + return T.Clean(entry.label or tostring(entry.val)) + end + return T.Clean(tostring(entry)) +end + +--- The socket group a client means: its index in the active skill set, or its label. +local function findGroup(skillsTab, ref) + local list = skillsTab.socketGroupList + if ref == nil then + T.Fail("Give the socket group (its index or label, as skills_get lists them).") + end + if type(ref) == "number" then + if not list[ref] then + T.Fail("There is no socket group %d; the active skill set has %d socket group%s (see skills_get).", ref, #list, #list == 1 and "" or "s") + end + return list[ref], ref + end + local group = T.Find(list, ref, groupName, "socket group") + return group, isValueInArray(list, group) +end + +--- A gem of a socket group: its position in the group, or its name. +local function findGem(group, ref) + if ref == nil then + T.Fail("Give the gem (its position in the group or its name).") + end + if type(ref) == "number" then + if not group.gemList[ref] then + T.Fail("Socket group '%s' has no gem %d; it has %d gem%s.", groupName(group), ref, #group.gemList, #group.gemList == 1 and "" or "s") + end + return group.gemList[ref], ref + end + local gem = T.Find(group.gemList, ref, gemName, "gem in '" .. groupName(group) .. "'") + return gem, isValueInArray(group.gemList, gem) +end + +local function gemSummary(gem, index) + local effect = grantedEffectOf(gem) + local entry = { + index = index, + name = gemName(gem), + level = gem.level, + quality = gem.quality, + enabled = gem.enabled ~= false, + count = gem.count or 1, + type = not effect and "unknown" or effect.support and "support" or "active", + error = gem.errMsg and T.Clean(gem.errMsg) or nil, + } + -- The level and quality the calculation used, when items or supports raise them. + local display = gem.displayEffect + if display and display.level and display.level ~= gem.level then + entry.effectiveLevel = display.level + end + if display and display.quality and display.quality ~= gem.quality then + entry.effectiveQuality = display.quality + end + return entry +end + +-- Where a group PoB adds by itself comes from (SkillsTab's sourceNote). +local function groupSource(group) + if not group.source then + return nil + end + if group.explodeSources then + local names = { } + for _, source in ipairs(group.explodeSources) do + t_insert(names, T.Clean(source.name or source.dn or "?")) + end + return "enemy explosion from " .. t_concat(names, ", ") + end + if group.sourceItem then + return T.Clean(group.sourceItem.name) + elseif group.sourceNode then + return T.Clean(group.sourceNode.name or group.sourceNode.dn) + elseif group.source == "Config" then + return "Custom Modifiers" + end + return T.Clean(tostring(group.source)) +end + +local function groupSummary(build, group, index, details) + local gems = { } + for gemIndex, gem in ipairs(group.gemList) do + t_insert(gems, gemSummary(gem, gemIndex)) + end + local activeSkills = { } + for _, activeSkill in ipairs(group.displaySkillList or { }) do + local effect = activeSkill.activeEffect + if effect and effect.grantedEffect then + t_insert(activeSkills, T.Clean(effect.grantedEffect.name)) + end + end + local summary = { + index = index, + label = groupName(group), + slot = group.slot, + enabled = group.enabled and true or false, + includeInFullDPS = group.includeInFullDPS and true or false, + main = build.mainSocketGroup == index, + activeSkills = T.Array(activeSkills), + gems = T.Array(gems), + grantedBy = groupSource(group), + } + if group.enabled and group.slotEnabled == false then + summary.inactiveWeaponSet = true + end + if details and group.displaySkillList then + -- PoB's own description of the group: active skills, and why other gems are inactive. + local collector = T.LineCollector() + build.skillsTab:AddSocketGroupTooltip(collector, group) + summary.details = T.Array(collector.lines) + end + return summary +end + +local function skillSetList(skillsTab) + local sets = { } + for _, id in ipairs(skillsTab.skillSetOrderList) do + local set = skillsTab.skillSets[id] + t_insert(sets, { id = id, title = T.Clean(set.title or "Default"), active = id == skillsTab.activeSkillSetId, socketGroups = #set.socketGroupList }) + end + return sets +end + +local function spectreList(build) + local list = { } + for _, id in ipairs(build.spectreList) do + local minion = build.data.minions[id] + t_insert(list, { id = id, name = minion and minion.name or id }) + end + return T.Array(list) +end + +-- The sidebar's main skill controls, as PoB fills them every frame. +local function refreshMainSkillControls(build) + build:ProcessBuildFlag() + if build.skillsTab.socketGroupList[build.mainSocketGroup] then + build:RefreshSkillSelectControls(build.controls, build.mainSocketGroup, "") + end +end + +local function mainSkillSummary(build) + refreshMainSkillControls(build) + local controls = build.controls + local group = build.skillsTab.socketGroupList[build.mainSocketGroup] + if not group then + return { note = "There are no socket groups in the active skill set." } + end + local result = { group = build.mainSocketGroup, groupLabel = groupName(group) } + local function options(control) + local list = { } + for _, entry in ipairs(control.list) do + t_insert(list, dropLabel(entry)) + end + return T.Array(list) + end + if controls.mainSkill.shown and controls.mainSkill.list[1] then + result.activeSkill = dropLabel(controls.mainSkill.list[controls.mainSkill.selIndex] or controls.mainSkill.list[1]) + result.activeSkills = options(controls.mainSkill) + else + result.note = "The main socket group has no active skill." + end + if controls.mainSkillPart.shown then + result.skillPart = dropLabel(controls.mainSkillPart.list[controls.mainSkillPart.selIndex] or "") + result.skillParts = options(controls.mainSkillPart) + end + if controls.mainSkillStageCount.shown then + result.stageCount = tonumber(controls.mainSkillStageCount.buf) + end + if controls.mainSkillMineCount.shown then + result.activeMines = tonumber(controls.mainSkillMineCount.buf) + end + if controls.mainSkillMinion.shown then + local selected = controls.mainSkillMinion.list[controls.mainSkillMinion.selIndex] + result.minion = selected and dropLabel(selected) or nil + result.minions = options(controls.mainSkillMinion) + if type(selected) == "table" and selected.itemSetId then + result.minionChosenBy = "item set" + end + if controls.mainSkillMinionLibrary.shown then + result.usesSpectreLibrary = true + end + end + if controls.mainSkillMinionSkill.shown then + result.minionSkill = dropLabel(controls.mainSkillMinionSkill.list[controls.mainSkillMinionSkill.selIndex] or "") + result.minionSkills = options(controls.mainSkillMinionSkill) + end + return result +end + +--- Pick an entry of one of PoB's dropdowns by position or text, as clicking it does. +local function selectDropDown(control, ref, what, idKey) + local index + if type(ref) == "number" then + index = ref + if not control.list[index] then + T.Fail("There is no %s %d; there are %d.", what, ref, #control.list) + end + else + for i, entry in ipairs(control.list) do + if idKey and type(entry) == "table" and entry[idKey] == ref then + index = i + end + end + if not index then + local entries = { } + for i, entry in ipairs(control.list) do + t_insert(entries, { index = i, label = dropLabel(entry) }) + end + index = T.Find(entries, ref, function(entry) return entry.label end, what).index + end + end + if type(control.list[index]) ~= "table" and idKey then + T.Fail("'%s' is not a %s that can be chosen.", dropLabel(control.list[index]), what) + end + if index ~= control.selIndex then + control.selIndex = index + control.selFunc(index, control.list[index]) + return true + end + return false +end + +--- Manage a list of sets (skill sets, config sets) through PoB's own set list +--- control and its dialogs, exactly as the "Manage..." dialog does. +--- opts: control (a SkillSetListControl or ConfigSetListControl), sets (id -> set), +--- order (list of ids), activeId (function), what ("skill set"), action, ref, title +function T.ManageSetList(opts) + local control, sets, order, what = opts.control, opts.sets, opts.order, opts.what + local function setTitle(id) + return sets[id] and (sets[id].title or "Default") or nil + end + local function find() + if opts.ref == nil then + T.Fail("Give the %s to %s: its id or title.", what, opts.action) + end + local id = opts.ref + if type(id) == "number" then + if not isValueInArray(order, id) then + T.Fail("There is no %s with id %d.", what, id) + end + else + id = T.Find(order, opts.ref, setTitle, what) + end + local index = isValueInArray(order, id) + control.selIndex = index + control.selValue = id + return index, id + end + local function newTitle() + if type(opts.title) ~= "string" or not opts.title:match("%S") then + T.Fail("Give a title for the %s.", what) + end + local title = T.Sanitise((opts.title:gsub("[%c]", " "))) + if #title > SET_TITLE_MAX then + T.Fail("The title is too long (at most %d characters).", SET_TITLE_MAX) + end + return title + end + -- Fill PoB's name dialog (RenameSet) and press Save. + local function enterName(title) + local popup = main.popups[1] + if not popup or not popup.controls.edit or not popup.controls.save then + T.Fail("Path of Building did not open the name dialog for the %s.", what) + end + popup.controls.edit:SetText(title, true) + popup.controls.save.onClick() + end + local action = opts.action + if action == "select" then + local index, id = find() + if id == opts.activeId() then + return { id = id, title = T.Clean(setTitle(id)), unchanged = true } + end + control:OnSelClick(index, id, true) + return { id = id, title = T.Clean(setTitle(id)) } + elseif action == "new" then + local title = newTitle() + control.controls.new.onClick() + enterName(title) + local id = order[#order] + return { id = id, title = T.Clean(setTitle(id)) } + elseif action == "copy" then + local title = newTitle() + local _, source = find() + control.controls.copy.onClick() + enterName(title) + local id = order[#order] + return { id = id, title = T.Clean(setTitle(id)), copiedFrom = source } + elseif action == "rename" then + local title = newTitle() + local _, id = find() + control.controls.rename.onClick() + enterName(title) + return { id = id, title = T.Clean(setTitle(id)) } + elseif action == "delete" then + local _, id = find() + if #order <= 1 then + T.Fail("The only %s cannot be deleted.", what) + end + local title = setTitle(id) + control.controls.delete.onClick() + local popup = main.popups[1] + if not popup or not popup.controls.confirm then + T.Fail("Path of Building did not ask to confirm deleting the %s.", what) + end + popup.controls.confirm.onClick() + return { id = id, title = T.Clean(title), deleted = true } + end + T.Fail("Unknown %s action '%s'.", what, tostring(action)) +end + +-- The spectres a reference can mean: an id, or a name (unique, or exact). +local function findSpectre(build, candidates, ref) + for _, id in ipairs(candidates) do + if id == ref then + return id + end + end + local exact = { } + for _, id in ipairs(candidates) do + if build.data.minions[id].name:lower() == ref:lower() then + t_insert(exact, id) + end + end + if #exact > 1 then + T.Fail("Several spectres are named '%s'; give the id instead: %s", ref, t_concat(exact, ", ")) + end + return exact[1] or T.Find(candidates, ref, function(id) return build.data.minions[id].name end, "spectre") +end + +------------------------------------------------------------------------------ + +T.Tool { + name = "skills_get", + title = "Skills tab", + description = "Returns the Skills tab of the open build: every socket group of the active skill set (index, label, item slot, " + .. "enabled, included in Full DPS, whether it is the main group, the active skills PoB found in it, where PoB-added groups come " + .. "from) with its gems (name, level, quality, enabled, count, support or active, the level/quality the calculation actually used " + .. "when items raise them, and PoB's error for unrecognised or unsupported gems); the main skill selection of the side bar (group, " + .. "active skill, skill part, stages, mines, minion and minion skill, with the choices each offers); the skill sets; and the " + .. "spectres in the build. Pass 'group' (index or label) to get only that group with PoB's own explanation of why gems are " + .. "inactive (for example a support that cannot apply). Use the indexes and names it returns with skills_edit.", + readOnly = true, + idempotent = true, + input = { + group = { type = { "integer", "string" }, description = "Only this socket group (index or label), with PoB's details of active and inactive gems." }, + details = { type = "boolean", description = "Include PoB's details (active skills, inactive gems and why) for every group." }, + spectre_search = { type = "string", maxLength = 100, description = "Also search the spectre library (all spectres PoB knows) by name, as its search box does; returns up to 50." }, + }, + run = function(args) + local build = T.Build() + build:ProcessBuildFlag() + local skillsTab = build.skillsTab + local result = { + skillSet = T.Clean(skillsTab.skillSets[skillsTab.activeSkillSetId].title or "Default"), + skillSets = skillSetList(skillsTab), + mainSkill = mainSkillSummary(build), + spectres = spectreList(build), + gemDefaults = { level = skillsTab.defaultGemLevel, quality = skillsTab.defaultGemQuality or 0 }, + } + if args.group ~= nil then + local group, index = findGroup(skillsTab, args.group) + result.groups = T.Array({ groupSummary(build, group, index, true) }) + else + local groups = { } + for index, group in ipairs(skillsTab.socketGroupList) do + t_insert(groups, groupSummary(build, group, index, args.details)) + end + result.groups = T.Array(groups) + end + if args.spectre_search then + local sourceList = { } + for id in pairs(build.data.spectres) do + t_insert(sourceList, id) + end + -- Ordered as buildMode:OpenSpectreLibrary orders the library. + local minions = build.data.minions + table.sort(sourceList, function(a, b) + if minions[a].name == minions[b].name then + return a < b + end + return minions[a].name < minions[b].name + end) + -- The spectre library's own search list filters the names. + local dest = new("MinionListControl"):MinionListControl(nil, { 0, 0, 265, 250 }, build.data, copyTable(build.spectreList)) + local search = new("MinionSearchListControl"):MinionSearchListControl(nil, { 0, 0, 265, 230 }, build.data, sourceList, dest) + search:ListFilterChanged(args.spectre_search, 1) + local found = { } + for _, id in ipairs(search.list) do + if #found < 50 then + t_insert(found, { id = id, name = build.data.minions[id].name, inBuild = isValueInArray(build.spectreList, id) and true or false }) + end + end + result.spectreLibrary = { total = #search.list, results = T.Array(found) } + end + return result + end, +} + +------------------------------------------------------------------------------ + +local EDIT_ACTIONS = { + "add_group", "edit_group", "remove_group", "add_gem", "edit_gem", "remove_gem", "set_main", "set_spectres", + "select_set", "new_set", "copy_set", "rename_set", "delete_set", +} + +-- Paste a socket group in PoB's copy/paste format with SkillsTab:PasteSocketGroup, +-- which uses the given text instead of the clipboard. +local function pasteSocketGroup(skillsTab, text) + skillsTab:PasteSocketGroup(text) +end + +-- The gem a name means, as SkillsTab:FindSkillGem matches pasted names. Support gems are +-- named without the word "Support" there, so a name ending in it is tried without it too. +local function findGemData(skillsTab, name) + local errMsg, gemData = skillsTab:FindSkillGem(name) + if not gemData and name:lower():match("%ssupport$") then + local _, withoutSuffix = skillsTab:FindSkillGem((name:gsub("%s+[Ss]upport$", ""))) + gemData = withoutSuffix + end + return gemData, errMsg and T.Clean(errMsg) +end + +local function checkPasteText(skillsTab, text) + text = T.Sanitise((text:gsub("\r\n", "\n"))) + if not text:match("\n$") then + text = text .. "\n" + end + local unread, unknown, lines = { }, { }, { } + local gems = 0 + for line in text:gmatch("([^\n]*)\n") do + if line:match("%S") and not line:match("^Label: ") and not line:match("^Slot: ") then + local name = line:match("^%s*(.-)%s+%d+/%d+") + if line:match(PASTE_GEM_PATTERN) and name then + gems = gems + 1 + local gemData, errMsg = findGemData(skillsTab, name) + if gemData then + line = line:gsub("^%s*(.-)(%s+%d+/%d+)", function(_, rest) return gemData.name .. rest end) + else + t_insert(unknown, errMsg) + end + else + t_insert(unread, line) + end + end + t_insert(lines, line) + end + text = t_concat(lines, "\n") .. "\n" + if unknown[1] and not unread[1] then + T.Fail("%s. Use gem names as Path of Building shows them.", t_concat(unknown, "; ")) + end + if unread[1] or gems == 0 then + T.Fail("Path of Building cannot read %s. Use its copy/paste format: optional 'Label: <label>' and 'Slot: <slot>' lines, then " + .. "one line per gem: '<gem name> <level>/<quality> <count>', with DISABLED before the count for a disabled gem, for example " + .. "'Slot: Body Armour\\nFireball 20/0 1\\nSpell Echo Support 20/0 1'.", unread[1] and ("'" .. unread[1] .. "'") or "any gem in that text") + end + local slot = text:match("Slot: (%C+)") + if slot then + local valid, names = false, { } + for _, entry in ipairs(skillsTab.controls.groupSlot.list) do + if entry.slotName then + t_insert(names, entry.slotName) + valid = valid or entry.slotName == slot + end + end + if not valid then + T.Fail("'%s' is not a slot a socket group can be in. Slots: %s", slot, t_concat(names, ", ")) + end + end + return text +end + +-- Edits made through the Skills tab's group controls need the group on display. +local function showGroup(skillsTab, group) + if group.source then + T.Fail("Socket group '%s' is added by %s; Path of Building does not let you edit its gems.", groupName(group), groupSource(group)) + end + if skillsTab.displayGroup ~= group then + skillsTab:SetDisplayGroup(group) + end +end + +local function setGemFields(skillsTab, group, index, args) + local gem = group.gemList[index] + local slot = skillsTab.gemSlots[index] + if args.level then + slot.level:SetText(tostring(args.level), true) + end + if args.quality then + slot.quality:SetText(tostring(args.quality), true) + end + if args.count then + slot.count:SetText(tostring(args.count), true) + end + if args.enabled ~= nil and args.enabled ~= gem.enabled then + if gem.gemData then + slot.enabled.state = args.enabled + slot.enabled.changeFunc(args.enabled) + else + -- The checkbox's callback needs gem data, which an unrecognised gem lacks; do the rest of what it does. + gem.enabled = args.enabled + skillsTab:ProcessSocketGroup(group) + skillsTab:AddUndoState() + skillsTab.build.buildFlag = true + end + end +end + +local function editSpectres(build, args) + if not (args.spectres or args.add_spectres or args.remove_spectres) then + T.Fail("Give spectres (the whole list), add_spectres or remove_spectres.") + end + build:OpenSpectreLibrary() + local popup = main.popups[1] + local dest, source = popup.controls.list, popup.controls.source + local removals = args.remove_spectres or { } + if args.spectres then + removals = copyTable(dest.list) + end + local added, removed = { }, { } + for _, ref in ipairs(removals) do + local id = findSpectre(build, dest.list, ref) + dest.selIndex = isValueInArray(dest.list, id) + dest.selValue = id + dest:OnSelDelete(dest.selIndex, id) + t_insert(removed, id) + end + for _, ref in ipairs(args.spectres or args.add_spectres or { }) do + local id = findSpectre(build, source.unfilteredList, ref) + if not isValueInArray(dest.list, id) then + source.selValue = id + source:AddSel() + t_insert(added, id) + end + end + popup.controls.save.onClick() + return added, removed +end + +local function editMainSkill(build, args) + local skillsTab = build.skillsTab + local controls = build.controls + if args.group ~= nil then + local _, index = findGroup(skillsTab, args.group) + refreshMainSkillControls(build) + selectDropDown(controls.mainSocketGroup, index, "socket group") + end + refreshMainSkillControls(build) + if not skillsTab.socketGroupList[build.mainSocketGroup] then + T.Fail("There are no socket groups to choose a main skill from.") + end + local function need(control, what) + if not control.shown then + T.Fail("The main skill has no %s to choose.", what) + end + end + if args.active_skill ~= nil then + need(controls.mainSkill, "active skill") + selectDropDown(controls.mainSkill, args.active_skill, "active skill") + refreshMainSkillControls(build) + end + if args.skill_part ~= nil then + need(controls.mainSkillPart, "skill part") + selectDropDown(controls.mainSkillPart, args.skill_part, "skill part") + refreshMainSkillControls(build) + end + if args.stage_count ~= nil then + need(controls.mainSkillStageCount, "stage count") + controls.mainSkillStageCount:SetText(tostring(args.stage_count), true) + refreshMainSkillControls(build) + end + if args.mine_count ~= nil then + need(controls.mainSkillMineCount, "active mine count") + controls.mainSkillMineCount:SetText(tostring(args.mine_count), true) + refreshMainSkillControls(build) + end + if args.minion ~= nil then + need(controls.mainSkillMinion, "minion") + selectDropDown(controls.mainSkillMinion, args.minion, "minion", "minionId") + refreshMainSkillControls(build) + end + if args.minion_skill ~= nil then + need(controls.mainSkillMinionSkill, "minion skill") + selectDropDown(controls.mainSkillMinionSkill, args.minion_skill, "minion skill") + refreshMainSkillControls(build) + end +end + +T.Tool { + name = "skills_edit", + title = "Edit skills", + description = "Changes the Skills tab of the open build through the same controls the user would use, one action per call. " + .. "add_group: paste a socket group in PoB's copy/paste format ('text'). edit_group: label, slot, enabled, include_in_full_dps. " + .. "remove_group. add_gem: 'gem' is the gem name (PoB matches it as it does pasted gems), optionally with level, quality, enabled, " + .. "count. edit_gem: level, quality, enabled, count of 'gem' (name or position). remove_gem. set_main: the side bar's main skill " + .. "(group, active_skill, skill_part, stage_count, mine_count, minion, minion_skill), as picking them in its dropdowns. " + .. "set_spectres: replace (spectres) or change (add_spectres, remove_spectres) the spectres in the build, as the spectre library does. " + .. "select_set/new_set/copy_set/rename_set/delete_set: skill sets ('set' is an id or title, 'title' the new name). Groups are " + .. "identified by index or label and gems by name or position, as skills_get returns them; groups PoB adds from items or passives " + .. "cannot have their gems edited. Returns the changed group or selection and the side-bar stat changes.", + destructive = true, + modifies = true, + usesDialog = true, + input = { + action = { type = "string", enum = EDIT_ACTIONS, description = "What to change (see the description)." }, + group = { type = { "integer", "string" }, description = "Socket group: its index or label (skills_get)." }, + gem = { type = { "integer", "string" }, description = "Gem: its name, or its position in the group (edit_gem, remove_gem)." }, + text = { type = "string", maxLength = 5000, description = "add_group: the group in PoB's copy/paste format, for example " + .. "'Label: Main\\nSlot: Body Armour\\nFireball 20/0 1\\nSpell Echo Support 20/20 1' (gem lines are '<name> <level>/<quality> <count>', " + .. "with DISABLED before the count for a disabled gem)." }, + level = { type = "integer", minimum = 1, maximum = 99, description = "Gem level (PoB limits it to the levels the gem has)." }, + quality = { type = "integer", minimum = 0, maximum = 99, description = "Gem quality." }, + enabled = { type = "boolean", description = "Enable or disable the gem (add_gem, edit_gem) or the group (edit_group)." }, + count = { type = "integer", minimum = 1, maximum = 99, description = "Gem count: scales the skill's DPS (several totems, minions, projectiles hitting...)." }, + label = { type = "string", maxLength = 50, description = "edit_group: the group's label (empty to let PoB name it after its skills)." }, + slot = { type = "string", description = "edit_group: the item slot the group is socketed in ('None', 'Body Armour', 'Weapon 1', 'Weapon 1 (Swap)', 'Ring 1', ...)." }, + include_in_full_dps = { type = "boolean", description = "edit_group: include the group in Full DPS." }, + active_skill = { type = { "integer", "string" }, description = "set_main: the active skill of the group (name or position)." }, + skill_part = { type = { "integer", "string" }, description = "set_main: the skill part (name or position), for skills with several." }, + stage_count = { type = "integer", minimum = 0, maximum = 9999, description = "set_main: stages, for skills with stages." }, + mine_count = { type = "integer", minimum = 0, maximum = 9999, description = "set_main: active mines, for mine skills." }, + minion = { type = { "integer", "string" }, description = "set_main: the minion (name, id or position; an item set for skills whose minion uses one)." }, + minion_skill = { type = { "integer", "string" }, description = "set_main: the minion's skill (name or position)." }, + spectres = { type = "array", items = { type = "string" }, maxItems = 50, description = "set_spectres: the complete list of spectres (names or ids)." }, + add_spectres = { type = "array", items = { type = "string" }, maxItems = 50, description = "set_spectres: spectres to add (names or ids from the library)." }, + remove_spectres = { type = "array", items = { type = "string" }, maxItems = 50, description = "set_spectres: spectres to remove (names or ids)." }, + set = { type = { "integer", "string" }, description = "Skill set actions: the skill set (id or title)." }, + title = { type = "string", maxLength = SET_TITLE_MAX, description = "new_set, copy_set, rename_set: the set's name." }, + }, + required = { "action" }, + run = function(args, ctx) + local build = T.Build() + build:ProcessBuildFlag() + local skillsTab = build.skillsTab + local action = args.action + local result = { action = action } + + if action:match("_set$") then + local control = new("SkillSetListControl"):SkillSetListControl(nil, { 0, 0, 350, 200 }, skillsTab) + local done = T.ManageSetList({ + control = control, sets = skillsTab.skillSets, order = skillsTab.skillSetOrderList, what = "skill set", + activeId = function() return skillsTab.activeSkillSetId end, + action = action:match("^(%a+)_set$"), ref = args.set, title = args.title, + }) + if not done.unchanged then + ctx:Changed() + end + build:ProcessBuildFlag() + result.skillSet = done + result.skillSets = skillSetList(skillsTab) + return result + end + + if action == "set_spectres" then + local added, removed = editSpectres(build, args) + ctx:Changed() + build:ProcessBuildFlag() + result.added = T.Array(added) + result.removed = T.Array(removed) + result.spectres = spectreList(build) + return result + end + + if action == "set_main" then + editMainSkill(build, args) + ctx:Changed() + result.mainSkill = mainSkillSummary(build) + return result + end + + -- Group and gem edits go through the Skills tab's own controls; put its selection back afterwards. + local shownGroup = skillsTab.displayGroup + local listSel = skillsTab.controls.groupList.selValue + local function restoreSelection() + if shownGroup and isValueInArray(skillsTab.socketGroupList, shownGroup) then + if skillsTab.displayGroup ~= shownGroup then + skillsTab:SetDisplayGroup(shownGroup) + end + local groupList = skillsTab.controls.groupList + groupList.selValue = listSel and isValueInArray(skillsTab.socketGroupList, listSel) and listSel or nil + groupList.selIndex = groupList.selValue and isValueInArray(skillsTab.socketGroupList, groupList.selValue) or nil + end + end + local ok, err = pcall(function() + if action == "add_group" then + if not args.text then + T.Fail("Give the group as 'text' in PoB's copy/paste format.") + end + local text = checkPasteText(skillsTab, args.text) + local before = #skillsTab.socketGroupList + pasteSocketGroup(skillsTab, text) + if #skillsTab.socketGroupList == before then + T.Fail("Path of Building did not add a group from that text.") + end + ctx:Changed() + result.index = #skillsTab.socketGroupList + elseif action == "remove_group" then + local group, index = findGroup(skillsTab, args.group) + if group.source then + T.Fail("Socket group '%s' is added by %s and cannot be deleted; it goes away with its source.", groupName(group), groupSource(group)) + end + local groupList = skillsTab.controls.groupList + groupList.selIndex = index + groupList.selValue = group + result.removed = groupName(group) + groupList:OnSelDelete(index, group) + local popup = main.popups[1] + if popup and popup.controls.confirm then + popup.controls.confirm.onClick() + end + if isValueInArray(skillsTab.socketGroupList, group) then + T.Fail("Path of Building did not delete the group.") + end + ctx:Changed() + elseif action == "edit_group" then + local group, index = findGroup(skillsTab, args.group) + if args.label == nil and args.slot == nil and args.enabled == nil and args.include_in_full_dps == nil then + T.Fail("Give what to change: label, slot, enabled or include_in_full_dps.") + end + skillsTab:SetDisplayGroup(group) + local controls = skillsTab.controls + if args.label ~= nil then + controls.groupLabel:SetText((T.Sanitise((args.label:gsub("%c", " ")))), true) + end + if args.slot ~= nil then + if group.source then + T.Fail("Socket group '%s' is added by %s; its slot cannot be changed.", groupName(group), groupSource(group)) + end + local wanted + for i, entry in ipairs(controls.groupSlot.list) do + if entry.label:lower() == args.slot:lower() or (entry.slotName and entry.slotName:lower() == args.slot:lower()) then + wanted = i + end + end + if not wanted then + local names = { } + for _, entry in ipairs(controls.groupSlot.list) do + t_insert(names, entry.label) + end + T.Fail("'%s' is not a socket group slot. Slots: %s", args.slot, t_concat(names, ", ")) + end + if wanted ~= controls.groupSlot.selIndex then + controls.groupSlot.selIndex = wanted + controls.groupSlot.selFunc(wanted, controls.groupSlot.list[wanted]) + end + end + if args.enabled ~= nil and args.enabled ~= (group.enabled and true or false) then + controls.groupEnabled.state = args.enabled + controls.groupEnabled.changeFunc(args.enabled) + end + if args.include_in_full_dps ~= nil and args.include_in_full_dps ~= (group.includeInFullDPS and true or false) then + controls.includeInFullDPS.state = args.include_in_full_dps + controls.includeInFullDPS.changeFunc(args.include_in_full_dps) + end + ctx:Changed() + result.index = index + elseif action == "add_gem" then + local group, index = findGroup(skillsTab, args.group) + if type(args.gem) ~= "string" then + T.Fail("Give the name of the gem to add as 'gem'.") + end + local gemData, errMsg = findGemData(skillsTab, (T.Sanitise(args.gem))) + if not gemData then + T.Fail("%s. Use the gem's name as Path of Building shows it, for example 'Spell Echo'.", errMsg) + end + if gemData.grantedEffect.unsupported then + T.Fail("Path of Building does not support %s yet.", gemData.name) + end + showGroup(skillsTab, group) + local gemIndex = #group.gemList + 1 + skillsTab:UpdateGemSlots() + local slot = skillsTab.gemSlots[gemIndex] + -- As choosing the gem in the gem slot's dropdown. + slot.nameSpec:SetText(gemData.name) + slot.nameSpec.gemChangeFunc(gemData.id, true, false, true) + if not group.gemList[gemIndex] then + T.Fail("Path of Building did not add %s.", gemData.name) + end + setGemFields(skillsTab, group, gemIndex, args) + ctx:Changed() + result.index = index + result.gem = gemIndex + elseif action == "edit_gem" then + local group, index = findGroup(skillsTab, args.group) + local _, gemIndex = findGem(group, args.gem) + if args.level == nil and args.quality == nil and args.enabled == nil and args.count == nil then + T.Fail("Give what to change: level, quality, enabled or count.") + end + showGroup(skillsTab, group) + setGemFields(skillsTab, group, gemIndex, args) + ctx:Changed() + result.index = index + result.gem = gemIndex + elseif action == "remove_gem" then + local group, index = findGroup(skillsTab, args.group) + local gem, gemIndex = findGem(group, args.gem) + showGroup(skillsTab, group) + result.removed = gemName(gem) + skillsTab.gemSlots[gemIndex].delete.onClick() + ctx:Changed() + result.index = index + end + end) + restoreSelection() + if not ok then + error(err, 0) + end + build:ProcessBuildFlag() + if result.index and skillsTab.socketGroupList[result.index] then + result.group = groupSummary(build, skillsTab.socketGroupList[result.index], result.index, true) + end + result.index = nil + return result + end, +} + +------------------------------------------------------------------------------ + +T.Tool { + name = "skills_rank_supports", + title = "Rank support gems", + description = "Ranks the gems Path of Building's gem selector offers for a socket group by the damage each would give, exactly as " + .. "the selector's 'Sort gems by DPS' does: for every gem that can support the group's skills (or, for active gems, has a " + .. "global effect) PoB calculates the build with that gem added to the group (or replacing the gem at 'gem' position), and " + .. "sorts them. 'stat' is the value it sorts by (default: the Skills tab's 'Sort gems by DPS' choice); for all but Full DPS this " + .. "is the main skill's value, so supports in a group that is not the main skill only matter if they reach it. Gems are added at " + .. "the level the Skills tab's default gem level gives and its default quality. The build is not changed. Calculating every " + .. "candidate can take some seconds; 'search' narrows the list as the selector's search box does (for example 'fire' or ':spell').", + readOnly = true, + idempotent = true, + input = { + group = { type = { "integer", "string" }, description = "Socket group (index or label). Default: the main socket group." }, + gem = { type = "integer", minimum = 1, description = "Gem position to replace instead of adding a new gem." }, + stat = { type = "string", enum = { "FullDPS", "CombinedDPS", "TotalDPS", "AverageDamage", "TotalDot", "BleedDPS", "IgniteDPS", "TotalPoisonDPS", "TotalEHP" }, + description = "What to sort by (the Skills tab's 'Sort gems by DPS' choices)." }, + type = { type = "string", enum = { "support", "active", "all" }, description = "Which gems to rank (default support)." }, + search = { type = "string", maxLength = 100, description = "Filter as the gem selector's search box (names, ':tag' filters)." }, + limit = T.PageArgs(25).limit, + offset = T.PageArgs(25).offset, + }, + run = function(args) + local build = T.Build() + build:ProcessBuildFlag() + local skillsTab = build.skillsTab + local group, groupIndex + if args.group ~= nil then + group, groupIndex = findGroup(skillsTab, args.group) + else + groupIndex = build.mainSocketGroup + group = skillsTab.socketGroupList[groupIndex] + if not group then + T.Fail("There are no socket groups; add one with skills_edit first.") + end + end + if group.source then + T.Fail("Socket group '%s' is added by %s; its gems cannot be changed.", groupName(group), groupSource(group)) + end + local slotIndex = args.gem or (#group.gemList + 1) + if slotIndex > #group.gemList + 1 then + T.Fail("Socket group '%s' has %d gems; 'gem' must be 1-%d.", groupName(group), #group.gemList, #group.gemList) + end + local statField = args.stat or skillsTab.sortGemsByDPSField + local statLabel = statField + for _, entry in ipairs(skillsTab.controls.sortGemsByDPSFieldControl.list) do + if entry.type == statField then + statLabel = entry.label + end + end + local gemType = args.type or "support" + + -- The gem selector calculates by putting each candidate into the group's gem list and + -- putting back only some fields; the calculation also writes choices onto the gems + -- it runs. Keep the group and every gem as they are, and restore them afterwards. + local saved = { } + for _, key in ipairs({ "displayGroup", "sortGemsByDPS", "sortGemsByDPSField" }) do + saved[key] = skillsTab[key] + end + local groupFields = copyTable(group, true) + local gemTables, gemFields = { }, { } + for i, gem in ipairs(group.gemList) do + gemTables[i], gemFields[i] = gem, copyTable(gem, true) + end + local function restoreFields(t, copy) + for k in pairs(t) do + if copy[k] == nil then + t[k] = nil + end + end + for k, v in pairs(copy) do + t[k] = v + end + end + local ok, result = pcall(function() + skillsTab.displayGroup = group + skillsTab.sortGemsByDPS = true + skillsTab.sortGemsByDPSField = statField + local control = new("GemSelectControl"):GemSelectControl(nil, { 0, 0, 300, 20 }, skillsTab, slotIndex, function() end) + control.sortGemsBy = GEM_TYPE_TAGS[gemType] + control:UpdateSortCache() + local search = args.search or "" + control:BuildList(search) + local sortCache = control.sortCache + local listed = { } + for _, gemId in ipairs(control.list) do + listed[gemId] = true + end + local pending, evaluated = { }, { } + for _, gemId in ipairs(sortCache.pendingGems or { }) do + if listed[gemId] then + t_insert(pending, gemId) + evaluated[gemId] = true + end + end + sortCache.pendingGems = pending + -- The open dropdown runs this coroutine over several frames; run it to the end. + local builder = coroutine.create(control.DPSBuilder) + repeat + local resumed, builderErr = coroutine.resume(builder, control) + if not resumed then + error(builderErr, 0) + end + until coroutine.status(builder) == "dead" + control:BuildList(search) + local baseValue = sortCache.baseDPS or 0 + local ranked = { } + for _, gemId in ipairs(control.list) do + local gemData = control.gems[gemId] + if gemData and evaluated[gemId] then + local value = sortCache.dps[gemId] or baseValue + t_insert(ranked, { + name = gemData.name, + value = T.Round(value, 2), + change = T.Round(value - baseValue, 2), + percent = baseValue ~= 0 and T.Round((value - baseValue) / baseValue * 100, 2) or nil, + canSupport = sortCache.canSupport[gemId] == true, + level = skillsTab:ProcessGemLevel(gemData), + }) + end + end + return { baseValue = baseValue, ranked = ranked } + end) + for key, value in pairs(saved) do + skillsTab[key] = value + end + restoreFields(group, groupFields) + for i = #group.gemList, 1, -1 do + group.gemList[i] = nil + end + for i, gem in ipairs(gemTables) do + restoreFields(gem, gemFields[i]) + group.gemList[i] = gem + end + if not ok then + error(result, 0) + end + local page, paging = T.Page(result.ranked, args, 25) + local replaced = group.gemList[slotIndex] + return { + group = groupIndex, + groupLabel = groupName(group), + replaces = replaced and gemName(replaced) or nil, + stat = { field = statField, label = statLabel, current = T.Round(result.baseValue, 2) }, + type = gemType, + defaultGemLevel = skillsTab.defaultGemLevel, + defaultGemQuality = skillsTab.defaultGemQuality or 0, + gems = page, + page = paging, + } + end, +} diff --git a/src/Modules/McpTools/Tree.lua b/src/Modules/McpTools/Tree.lua index 9bd90fa8d15..37c3293e514 100644 --- a/src/Modules/McpTools/Tree.lua +++ b/src/Modules/McpTools/Tree.lua @@ -1,6 +1,1454 @@ -- Path of Building -- -- Module: MCP Tools - Tree +-- The passive tree: reading and searching it, allocating nodes and masteries, +-- managing the tree list, node power, the timeless jewel finder and tattoos. -- local T = ... +local t_insert = table.insert +local t_concat = table.concat +local t_sort = table.sort +local s_format = string.format +local m_min = math.min +local m_max = math.max +local m_floor = math.floor + +-- The node categories the search filters accept; ascendancy nodes form their own category. +local NODE_CATEGORIES = { "normal", "notable", "keystone", "mastery", "socket", "ascendancy" } + +local function nodeCategory(node) + if node.ascendancyName then + return "ascendancy" + end + return node.type:lower() +end + +local function cleanLines(lines) + local out = { } + for _, line in ipairs(lines or { }) do + t_insert(out, T.Clean(line)) + end + return T.Array(out) +end + +local function isStartNode(node) + return node.type == "ClassStart" or node.type == "AscendClassStart" +end + +local function specTitle(spec) + return spec.title or "Default" +end + +local function className(spec) + return spec.curAscendClassId ~= 0 and spec.curAscendClassName or spec.curClassName +end + +-- A failure raised by T.Fail, as a message; other errors are raised again. +local function failureText(err) + if type(err) == "table" and err.mcpFailure then + return err.mcpFailure + end + error(err, 0) +end + +-- Select a dropdown entry as a click does (selIndex, then its selFunc). +local function selectEntry(control, index) + control.selIndex = index + if control.selFunc then + control.selFunc(index, control.list[index]) + end +end + +-- The index of a dropdown entry: by id (numbers), then exact text in one of +-- fields, then a unique partial match of its label. +local function pickEntry(list, query, what, fields) + fields = fields or { "label" } + local wanted = T.Clean(tostring(query)):lower() + for i, entry in ipairs(list) do + if type(query) == "number" and entry.id == query then + return i + end + for _, field in ipairs(fields) do + if entry[field] ~= nil and T.Clean(tostring(entry[field])):lower() == wanted then + return i + end + end + end + local entries = { } + for i, entry in ipairs(list) do + if entry.label then + t_insert(entries, { index = i, label = entry.label }) + end + end + return T.Find(entries, tostring(query), function(entry) return entry.label end, what).index +end + +local function labels(list) + local out = { } + for _, entry in ipairs(list or { }) do + t_insert(out, T.Clean(type(entry) == "table" and entry.label or tostring(entry))) + end + return T.Array(out) +end + +-- Open one of PoB's dialogs, use it, and close whatever it left open. +local function withDialog(open, use, openFailure) + local before = #main.popups + local opened, openErr = pcall(open) + if not opened or #main.popups <= before then + while #main.popups > before do + main:ClosePopup() + end + if not opened and type(openErr) == "table" and openErr.mcpFailure then + error(openErr, 0) + end + T.Fail(openFailure or "Path of Building did not open its dialog%s", opened and "" or (": " .. tostring(openErr))) + end + local ok, result = pcall(use, main.popups[1]) + while #main.popups > before do + main:ClosePopup() + end + if not ok then + error(result, 0) + end + return result +end + +-- The trees in the tree list. +local function specList(treeTab) + local list = { } + for index, spec in ipairs(treeTab.specList) do + local used = spec:CountAllocNodes() + t_insert(list, { + index = index, + title = specTitle(spec), + class = spec.curClassName, + ascendancy = spec.curAscendClassId ~= 0 and spec.curAscendClassName or nil, + points = used, + treeVersion = treeVersions[spec.treeVersion] and treeVersions[spec.treeVersion].display or spec.treeVersion, + current = index == treeTab.activeSpec, + }) + end + return list +end + +-- The PoB tattoo count: tattoos replacing nodes, not counting Runegrafts (TreeTab:ModifyNodePopup). +local function tattooCount(spec) + local count = 0 + for _, override in pairs(spec.hashOverrides) do + if override.isTattoo and not override.dn:find("Runegraft") then + count = count + 1 + end + end + return count +end + +-- The mastery effects a node offers, and whether each can still be chosen +-- there (TreeTab:OpenMasteryPopup leaves out effects chosen on another mastery). +local function masteryEffects(spec, node) + local effects = { } + for _, option in ipairs(node.masteryEffects or { }) do + local assignedNodeId = isValueInTable(spec.masterySelections, option.effect) + local effect = spec.tree.masteryEffects[option.effect] + t_insert(effects, { + id = option.effect, + text = T.Clean(t_concat(effect and effect.sd or option.stats or { }, " / ")), + selected = assignedNodeId == node.id or nil, + available = not assignedNodeId or assignedNodeId == node.id, + }) + end + return effects +end + +------------------------------------------------------------------------------ +-- Reading the tree +------------------------------------------------------------------------------ + +T.Tool { + name = "tree_get", + title = "Read the passive tree", + description = "Returns the passive tree of the open build: class, ascendancy, secondary ascendancy (bloodline), tree version, " + .. "the tree list (every tree with its index, title, class and points; the current one is used for calculations), the top " + .. "bar's point counter and its tooltip (required level, estimated act), allocated keystones, notables, ascendancy notables, " + .. "masteries with their chosen effect, jewel sockets with the jewel in them, tattooed nodes (with PoB's 50-tattoo count) and " + .. "nodes changed by timeless jewels, plus the official tree link. Pass detail 'nodes' to page through every allocated node " + .. "with its id, type and stats. Use tree_search to find nodes that are not allocated.", + readOnly = true, + idempotent = true, + input = { + detail = { type = "string", enum = { "summary", "nodes" }, description = "summary (default), or nodes: every allocated node, paged." }, + limit = T.PageArgs(100).limit, + offset = T.PageArgs(100).offset, + }, + run = function(args) + local build = T.Build() + build:ProcessBuildFlag() + local spec = build.spec + local treeTab = build.treeTab + local tree = spec.tree + local used, ascUsed, secondaryUsed, sockets = spec:CountAllocNodes() + local result = { + class = spec.curClassName, + ascendancy = spec.curAscendClassId ~= 0 and spec.curAscendClassName or nil, + secondaryAscendancy = spec.curSecondaryAscendClassId and spec.curSecondaryAscendClassId ~= 0 and spec.curSecondaryAscendClassName or nil, + treeVersion = treeVersions[spec.treeVersion] and treeVersions[spec.treeVersion].display or spec.treeVersion, + treeVersionOutdated = treeTab.showConvert and true or false, + activeSpec = { index = treeTab.activeSpec, title = specTitle(spec) }, + specs = specList(treeTab), + points = { passives = used, ascendancy = ascUsed, secondaryAscendancy = secondaryUsed, jewelSockets = sockets }, + } + local pointDisplay = build.controls.pointDisplay + if pointDisplay.str then + result.pointCounter = (T.Clean(pointDisplay.str):gsub("^%s+", ""):gsub("%s+$", "")) + end + if pointDisplay.req then + local lines = { } + for line in T.Clean(pointDisplay.req):gmatch("[^\n]+") do + t_insert(lines, (line:gsub("^%s+", ""))) + end + result.pointCounterTooltip = lines + end + + local ids = { } + for id, node in pairs(spec.allocNodes) do + if not isStartNode(node) then + t_insert(ids, id) + end + end + t_sort(ids) + + if args.detail == "nodes" then + local nodes = { } + for _, id in ipairs(ids) do + local node = spec.allocNodes[id] + t_insert(nodes, { id = id, name = node.dn, type = nodeCategory(node), ascendancy = node.ascendancyName, stats = cleanLines(node.sd) }) + end + result.nodes, result.page = T.Page(nodes, args, 100, 200) + return result + end + + local keystones, notables, ascendancyNodes, masteries, jewels, conquered = { }, { }, { }, { }, { }, { } + for _, id in ipairs(ids) do + local node = spec.allocNodes[id] + if node.ascendancyName then + if node.type == "Notable" then + t_insert(ascendancyNodes, node.dn) + end + elseif node.type == "Keystone" then + t_insert(keystones, node.dn) + elseif node.type == "Notable" then + t_insert(notables, node.dn) + elseif node.type == "Mastery" then + t_insert(masteries, { id = id, name = node.dn, effectId = spec.masterySelections[id], effect = T.Clean(t_concat(node.sd or { }, " / ")) }) + end + if node.type == "Socket" then + local itemId = spec.jewels[id] + local item = itemId and build.itemsTab.items[itemId] + t_insert(jewels, { id = id, socket = node.dn, jewel = item and item.name or nil }) + end + if node.conqueredBy and tree.nodes[id] then + t_insert(conquered, { id = id, original = tree.nodes[id].dn, name = node.dn, stats = cleanLines(node.sd) }) + end + end + local tattoos = { } + for id, override in pairs(spec.hashOverrides) do + local base = tree.nodes[id] + t_insert(tattoos, { + id = id, + node = base and base.dn, + tattoo = override.dn, + stats = cleanLines(override.sd), + allocated = spec.nodes[id] and spec.nodes[id].alloc or false, + }) + end + t_sort(tattoos, function(a, b) return a.id < b.id end) + + result.keystones = T.Array(keystones) + result.notables = T.Array(notables) + result.ascendancyNotables = T.Array(ascendancyNodes) + result.masteries = T.Array(masteries) + result.jewelSockets = T.Array(jewels) + result.tattoos = T.Array(tattoos) + result.tattooCount = tattooCount(spec) + result.tattooLimit = 50 + result.conqueredNodes = T.Array(conquered) + local version = treeVersions[spec.treeVersion] + if version and version.url then + local ok, url = pcall(spec.EncodeURL, spec, version.url) + if ok then + result.url = url + end + end + return result + end, +} + +T.Tool { + name = "tree_search", + title = "Search the passive tree", + description = "Finds passive nodes with the Tree tab's own search: the words must all appear in a node's name, stats, modifier " + .. "names or type (Lua patterns work; \"quoted text\" is one word; start with 'oil:' to search anoint recipes). Filter by " + .. "allocation and by node type. Each node comes with its id, name, type, stats, whether it is allocated, the points needed " + .. "to reach it (null when it cannot be reached from the allocated tree), its ascendancy, and for masteries the effects it " + .. "offers (with ids, and whether each is still available). Without a query it lists every node passing the filters. Pass " + .. "the ids to tree_edit or simulate.", + readOnly = true, + idempotent = true, + input = { + query = { type = "string", maxLength = 100, description = "Search text, as typed in the Tree tab's search box, for example 'life regeneration' or 'oil:amber'." }, + allocated = { type = "string", enum = { "any", "allocated", "unallocated" }, description = "Which nodes to include (default any)." }, + types = { type = "array", items = { type = "string", enum = NODE_CATEGORIES }, maxItems = 6, + description = "Node types to include (default all). 'ascendancy' covers every ascendancy node; the other types then only match nodes outside ascendancies." }, + limit = T.PageArgs(25).limit, + offset = T.PageArgs(25).offset, + }, + run = function(args) + local build = T.Build() + local spec = build.spec + local viewer = build.treeTab.viewer + local words = viewer:ParseSearchString(args.query or "") + local proxy = { searchParams = words } + local types + if args.types and args.types[1] then + types = { } + for _, name in ipairs(args.types) do + types[name] = true + end + end + local matches = { } + for _, node in pairs(spec.nodes) do + local include = node.dn and not isStartNode(node) and not node.isProxy and not (node.group and node.group.isProxy) + and not (node.type == "Mastery" and not node.masteryEffects) + if include and args.allocated == "allocated" then + include = node.alloc + elseif include and args.allocated == "unallocated" then + include = not node.alloc + end + if include and types then + include = types[nodeCategory(node)] + end + if include and words[1] then + include = viewer.DoesNodeMatchSearchParams(proxy, node) + end + if include then + t_insert(matches, node) + end + end + t_sort(matches, function(a, b) + if (a.alloc and true or false) ~= (b.alloc and true or false) then + return a.alloc and true or false + end + local da, db = a.path and #a.path or 100000, b.path and #b.path or 100000 + if da ~= db then + return da < db + end + if a.dn ~= b.dn then + return a.dn < b.dn + end + return a.id < b.id + end) + local nodes = { } + for _, node in ipairs(matches) do + local entry = { + id = node.id, + name = node.dn, + type = nodeCategory(node), + ascendancy = node.ascendancyName, + allocated = node.alloc and true or false, + pointsNeeded = not node.alloc and node.path and #node.path or nil, + } + if node.type == "Mastery" and node.masteryEffects then + entry.effects = masteryEffects(spec, node) + if node.alloc then + entry.stats = cleanLines(node.sd) + end + else + entry.stats = cleanLines(node.sd) + end + t_insert(nodes, entry) + end + local page, paging = T.Page(nodes, args, 25) + return { query = args.query, words = T.Array(words), nodes = page, page = paging } + end, +} + +------------------------------------------------------------------------------ +-- Changing the tree +------------------------------------------------------------------------------ + +-- Switch to the ascendancy (or bloodline) of an ascendancy node, as a left +-- click on it does in PassiveTreeView. Returns a description of the switch. +local function switchAscendancyFor(build, node, resetTree) + local spec = build.spec + if node.isBloodline and spec.tree.alternate_ascendancies then + if not spec.curSecondaryAscendClass or node.ascendancyName ~= spec.curSecondaryAscendClass.id then + for bloodlineId, bloodline in pairs(spec.tree.alternate_ascendancies) do + if bloodline.id == node.ascendancyName then + spec:SelectSecondaryAscendClass(bloodlineId) + spec:AddUndoState() + spec:SetWindowTitleWithBuildClass() + build.buildFlag = true + return "secondary ascendancy " .. bloodline.name + end + end + end + return + end + if spec.curAscendClassId ~= 0 and node.ascendancyName == spec.curAscendClassBaseName then + return + end + if spec.curSecondaryAscendClass and node.ascendancyName == spec.curSecondaryAscendClass.id then + return + end + for ascendClassId, ascendClass in pairs(spec.curClass.classes) do + if ascendClass.id == node.ascendancyName then + spec:SelectAscendClass(ascendClassId) + spec:AddUndoState() + spec:SetWindowTitleWithBuildClass() + build.buildFlag = true + return "ascendancy " .. ascendClass.name + end + end + for _, class in pairs(spec.tree.classes) do + for _, ascendClass in pairs(class.classes) do + if ascendClass.id == node.ascendancyName then + T.SelectClass(build, class.name, ascendClass.name, resetTree) + return "class " .. class.name .. ", ascendancy " .. ascendClass.name + end + end + end +end + +-- Choose a mastery effect through PoB's mastery dialog (TreeTab:OpenMasteryPopup, +-- then a click on the effect, which calls TreeTab:SaveMasteryPopup). +local function chooseMastery(build, node, wanted) + local spec = build.spec + if node.type ~= "Mastery" or not node.masteryEffects then + T.Fail("%s (%d) is not a mastery.", node.dn, node.id) + end + local effects = masteryEffects(spec, node) + local effect + local wantedId = tonumber(wanted) + if wantedId then + for _, entry in ipairs(effects) do + if entry.id == wantedId then + effect = entry + end + end + if not effect then + T.Fail("%s has no effect with id %d; its effects are listed by tree_search.", node.dn, wantedId) + end + else + effect = T.Find(effects, wanted, function(entry) return entry.text end, node.dn .. " effect") + end + if spec.masterySelections[node.id] == effect.id and node.alloc then + return false + end + if not effect.available then + local otherId = isValueInTable(spec.masterySelections, effect.id) + T.Fail("'%s' is already chosen on another mastery (%s, id %d); a mastery effect can only be taken once.", effect.text, spec.nodes[otherId] and spec.nodes[otherId].dn or "?", otherId) + end + if not node.alloc and not node.path then + T.Fail("%s (%d) cannot be reached from the allocated tree.", node.dn, node.id) + end + withDialog(function() + build.treeTab:OpenMasteryPopup(node) + end, function(popup) + local list = popup.controls.effect + for index, entry in ipairs(list.list) do + if entry.id == effect.id then + list.selIndex = index + list.selValue = entry + list:OnSelClick(index, entry, false) + return + end + end + T.Fail("Path of Building does not offer '%s' on %s.", effect.text, node.dn) + end, "Path of Building offers no effect for this mastery%s") + return true +end + +T.Tool { + name = "tree_edit", + title = "Edit the passive tree", + description = "Changes the current tree of the open build the way clicks on the Tree tab do: allocate nodes (with the shortest " + .. "path to them; an ascendancy node of another ascendancy switches to it, as a click does), remove nodes (with every node " + .. "that depends on them), choose mastery effects (allocating the mastery if needed), and change the class, ascendancy or " + .. "secondary ascendancy (bloodline). Steps run in that order: class, secondary ascendancy, remove, allocate, masteries. " + .. "Nodes are given by id or exact name (find them with tree_search). It reports the nodes actually added and removed and " + .. "every request that failed (unreachable, unknown, mastery effect taken elsewhere) without stopping the others. Measure " + .. "first with simulate; changes are unsaved until build_save.", + idempotent = true, + modifies = true, + input = { + class = { type = "string", description = "Change the class, for example 'Witch'. Keeps the tree when it reaches the new class's start; otherwise needs reset_tree." }, + ascendancy = { type = "string", description = "Change the ascendancy (of the class after 'class'), for example 'Necromancer'." }, + reset_tree = { type = "boolean", description = "Allow a class change that resets the tree (only if the user agreed)." }, + secondary_ascendancy = { type = "string", description = "Choose the secondary ascendancy (bloodline) by name, or 'None' to remove it." }, + allocate = { type = "array", items = { type = { "string", "integer" } }, maxItems = 100, description = "Nodes to allocate, by id or name." }, + deallocate = { type = "array", items = { type = { "string", "integer" } }, maxItems = 100, description = "Allocated nodes to remove, by id or name; nodes that depend on them are removed too." }, + masteries = { + type = "array", maxItems = 50, + items = { + type = "object", + properties = { + node = { type = { "string", "integer" }, description = "Mastery node id (names are shared by several masteries)." }, + effect = { type = { "string", "integer" }, description = "Effect id, or its text (exact or a unique part)." }, + }, + required = { "node", "effect" }, + additionalProperties = false, + }, + description = "Mastery effects to choose: [{node, effect}].", + }, + }, + run = function(args, ctx) + local build = T.Build() + local spec = build.spec + local before = { } + for id, node in pairs(spec.allocNodes) do + before[id] = node.dn + end + local failed, deallocated, masteries, switched = { }, { }, { }, { } + local changed = false + local classBefore = { spec.curClassId, spec.curAscendClassId, spec.curSecondaryAscendClassId } + + if args.class or args.ascendancy then + T.SelectClass(build, args.class, args.ascendancy, args.reset_tree) + spec = build.spec + end + if args.secondary_ascendancy then + build:UpdateSecondaryAscendancyDropdown(true) + local drop = build.controls.secondaryAscendDrop + if #drop.list <= 1 and args.secondary_ascendancy:lower() ~= "none" then + T.Fail("This tree version has no secondary ascendancies.") + end + local index = pickEntry(drop.list, args.secondary_ascendancy, "secondary ascendancy") + if drop.list[index].ascendClassId ~= (spec.curSecondaryAscendClassId or 0) then + selectEntry(drop, index) + end + end + + for _, ref in ipairs(args.deallocate or { }) do + local ok, err = pcall(function() + local node = T.FindNode(spec, ref) + if isStartNode(node) then + T.Fail("%s is a class start; change the class instead.", node.dn) + end + if not node.alloc then + T.Fail("%s (%d) is not allocated.", node.dn, node.id) + end + local dependents = { } + for _, depNode in ipairs(node.depends) do + if depNode ~= node then + t_insert(dependents, depNode.dn) + end + end + spec:DeallocNode(node) + spec:AddUndoState() + build.buildFlag = true + changed = true + t_insert(deallocated, { id = node.id, name = node.dn, alsoRemoved = T.Array(dependents) }) + end) + if not ok then + t_insert(failed, { node = ref, action = "deallocate", reason = failureText(err) }) + end + end + + for _, ref in ipairs(args.allocate or { }) do + local ok, err = pcall(function() + local node = T.FindNode(spec, ref) + if isStartNode(node) then + T.Fail("%s is a class start; change the class instead.", node.dn) + end + if node.alloc then + return + end + if node.ascendancyName then + local switch = switchAscendancyFor(build, node, args.reset_tree) + if switch then + changed = true + t_insert(switched, switch) + end + end + if node.type == "Mastery" and node.masteryEffects then + T.Fail("%s (%d) is a mastery: choose its effect with masteries [{node, effect}].", node.dn, node.id) + end + if not node.path then + T.Fail("%s (%d) cannot be reached from the allocated tree.", node.dn, node.id) + end + spec:AllocNode(node) + spec:AddUndoState() + build.buildFlag = true + changed = true + end) + if not ok then + t_insert(failed, { node = ref, action = "allocate", reason = failureText(err) }) + end + end + + for _, entry in ipairs(args.masteries or { }) do + local ok, err = pcall(function() + local node = T.FindNode(spec, entry.node) + if chooseMastery(build, node, entry.effect) then + changed = true + t_insert(masteries, { id = node.id, name = node.dn, effect = T.Clean(t_concat(node.sd, " / ")) }) + end + end) + if not ok then + t_insert(failed, { node = entry.node, action = "mastery", reason = failureText(err) }) + end + end + + if classBefore[1] ~= spec.curClassId or classBefore[2] ~= spec.curAscendClassId or classBefore[3] ~= spec.curSecondaryAscendClassId then + changed = true + end + if changed then + ctx:Changed() + end + local added, removed = { }, { } + for id, node in pairs(spec.allocNodes) do + if not before[id] and not isStartNode(node) then + t_insert(added, { id = id, name = node.dn }) + end + end + for id, name in pairs(before) do + local node = spec.nodes[id] + if not spec.allocNodes[id] and not (node and isStartNode(node)) then + t_insert(removed, { id = id, name = name }) + end + end + t_sort(added, function(a, b) return a.id < b.id end) + t_sort(removed, function(a, b) return a.id < b.id end) + local used, ascUsed = spec:CountAllocNodes() + return { + class = spec.curClassName, + ascendancy = spec.curAscendClassId ~= 0 and spec.curAscendClassName or nil, + secondaryAscendancy = spec.curSecondaryAscendClassId and spec.curSecondaryAscendClassId ~= 0 and spec.curSecondaryAscendClassName or nil, + switched = switched[1] and switched or nil, + added = T.Array(added), + removed = T.Array(removed), + deallocated = deallocated[1] and deallocated or nil, + masteries = masteries[1] and masteries or nil, + failed = T.Array(failed), + points = { passives = used, ascendancy = ascUsed }, + } + end, +} + +------------------------------------------------------------------------------ +-- The tree list +------------------------------------------------------------------------------ + +-- A tree in the list, by 1-based index or title. +local function findSpec(treeTab, ref) + if ref == nil then + T.Fail("Give the tree with 'spec' (its index or title); tree_get lists them.") + end + local index = tonumber(ref) + if index then + if not treeTab.specList[index] then + T.Fail("There is no tree %d; the build has %d.", index, #treeTab.specList) + end + return index + end + local entries = { } + for i, spec in ipairs(treeTab.specList) do + t_insert(entries, { index = i, title = specTitle(spec) }) + end + return T.Find(entries, tostring(ref), function(entry) return entry.title end, "tree").index +end + +-- Fill in and save the tree name dialog PassiveSpecListControl:RenameSpec opened. +local function saveSpecName(popup, title) + local controls = popup.controls + if title then + controls.edit:SetText((T.Sanitise(title)), true) + else + controls.edit:SetText(controls.edit.buf, true) + end + if not controls.save.enabled then + T.Fail("Give the tree a title with 'title'.") + end + controls.save.onClick() +end + +T.Tool { + name = "tree_specs", + title = "Manage the tree list", + description = "Manages the build's list of passive trees (the Tree tab's 'Manage trees...' list): list them, select the one " + .. "used for calculations, add a new empty tree (same class and ascendancy), copy a tree, rename one, or delete one (PoB " + .. "asks for confirmation; this call confirms, so only delete when the user asked). Trees are identified by their 1-based " + .. "index or title, as listed. New and copied trees go to the end of the list and are not selected; select them to edit " + .. "them with tree_edit. The last remaining tree cannot be deleted.", + destructive = true, + modifies = true, + input = { + action = { type = "string", enum = { "list", "select", "new", "copy", "rename", "delete" }, description = "What to do." }, + spec = { type = { "integer", "string" }, description = "The tree to select, copy, rename or delete: index (1-based) or title." }, + title = { type = "string", maxLength = 100, description = "Title for a new, copied or renamed tree (a copy keeps the original's title by default)." }, + }, + required = { "action" }, + run = function(args, ctx) + local build = T.Build() + local treeTab = build.treeTab + local action = args.action + local result = { action = action } + if action == "select" then + local index = findSpec(treeTab, args.spec) + if index ~= treeTab.activeSpec then + -- The tree dropdown's own steps. + build.modFlag = true + treeTab:SetActiveSpec(index) + ctx:Changed() + end + elseif action ~= "list" then + local listControl = new("PassiveSpecListControl"):PassiveSpecListControl(nil, { 0, 0, 350, 200 }, treeTab) + local function selectSpec() + local index = findSpec(treeTab, args.spec) + listControl.selIndex = index + listControl.selValue = treeTab.specList[index] + return index + end + if action == "new" then + if not args.title then + T.Fail("Give the new tree a title with 'title'.") + end + withDialog(listControl.controls.new.onClick, function(popup) + saveSpecName(popup, args.title) + end) + result.index = #treeTab.specList + elseif action == "copy" then + selectSpec() + withDialog(listControl.controls.copy.onClick, function(popup) + saveSpecName(popup, args.title) + end) + result.index = #treeTab.specList + elseif action == "rename" then + if not args.title then + T.Fail("Give the new title with 'title'.") + end + result.index = selectSpec() + withDialog(listControl.controls.rename.onClick, function(popup) + saveSpecName(popup, args.title) + end) + elseif action == "delete" then + local index = selectSpec() + if #treeTab.specList <= 1 then + T.Fail("The build has only one tree, and the last tree cannot be deleted.") + end + result.deleted = specTitle(treeTab.specList[index]) + withDialog(listControl.controls.delete.onClick, function(popup) + popup.controls.confirm.onClick() + end) + end + ctx:Changed() + end + result.specs = specList(treeTab) + result.activeSpec = treeTab.activeSpec + return result + end, +} + +------------------------------------------------------------------------------ +-- Node power +------------------------------------------------------------------------------ + +-- The stats the Tree tab's "Show Node Power" offers (TreeTab.powerStatList). +local function nodePowerStats() + local list = { } + for _, stat in ipairs(data.powerStatList) do + if not stat.ignoreForNodes then + t_insert(list, stat) + end + end + return list +end + +-- Run CalcsTab:PowerBuilder to completion for one stat. PoB resumes it as a +-- coroutine over several frames (CalcsTab:BuildPower); here it is resumed +-- until it finishes, with the Tree tab's own stat and depth put back after. +local function runPowerBuilder(build, stat, maxDepth) + local calcsTab = build.calcsTab + local savedStat, savedDepth, savedProgress = calcsTab.powerStat, calcsTab.nodePowerMaxDepth, build.powerBuilderProgressCallback + calcsTab.powerStat = stat + calcsTab.nodePowerMaxDepth = maxDepth + -- The progress callback only drives the Tree tab's toast. + build.powerBuilderProgressCallback = nil + local co = coroutine.create(calcsTab.PowerBuilder) + local ok, err = true, nil + while coroutine.status(co) ~= "dead" do + local resumed, message = coroutine.resume(co, calcsTab) + if not resumed then + ok, err = false, message + break + end + end + calcsTab.powerStat, calcsTab.nodePowerMaxDepth = savedStat, savedDepth + build.powerBuilderProgressCallback = savedProgress + -- The node power now holds this stat; a heat map shown in the Tree tab rebuilds with its own. + calcsTab.powerBuildFlag = true + if not ok then + T.Fail("Path of Building could not calculate node power: %s", tostring(err)) + end +end + +local POWER_SORT_COLUMNS = { type = 1, power = 3, points = 4, per_point = 5 } + +T.Tool { + name = "tree_node_power", + title = "Node power report", + description = "Runs the Tree tab's 'Show Node Power' calculation for one stat and returns its Power Report: for every node, " + .. "how much the stat changes by allocating it (or, with filter 'allocated', by removing it), the change per point spent on " + .. "the path to it, and the points needed ('Cluster' for cluster jewel notables). Percentage stats are scaled by 100 as PoB " + .. "shows them. It calculates every node, which can take a while on large trees; max_depth limits it to nodes within that " + .. "many points. Use it to find the best passives to take or the weakest to drop, then confirm with simulate.", + readOnly = true, + input = { + stat = { type = "string", description = "Stat key or label from the Tree tab's node power list, for example 'CombinedDPS', 'Full DPS', 'Life', 'TotalEHP' (default CombinedDPS)." }, + filter = { type = "string", enum = { "unallocated", "unallocated_and_clusters", "allocated" }, description = "Which nodes to report (default unallocated)." }, + sort = { type = "string", enum = { "power", "per_point", "points", "type" }, description = "Sort order, as the report's columns (default power)." }, + types = { type = "array", items = { type = "string", enum = { "normal", "notable", "keystone", "mastery" } }, maxItems = 4, description = "Node types to include (default all)." }, + show_masteries = { type = "boolean", description = "Include mastery effects (default true)." }, + max_depth = { type = "integer", minimum = 1, maximum = 100, description = "Only calculate nodes within this many points (PoB's node power depth limit); default all." }, + limit = T.PageArgs(25).limit, + offset = T.PageArgs(25).offset, + }, + run = function(args) + local build = T.Build() + build:ProcessBuildFlag() + local wanted = (args.stat or "CombinedDPS"):lower() + local stat + local choices = { } + for _, entry in ipairs(nodePowerStats()) do + if entry.stat then + t_insert(choices, entry.stat .. " (" .. entry.label .. ")") + end + if (entry.stat and entry.stat:lower() == wanted) or entry.label:lower() == wanted then + stat = entry + end + end + if not stat then + T.Fail("Unknown node power stat '%s'. Choices: %s", args.stat, t_concat(choices, ", ")) + end + if not stat.stat then + T.Fail("'%s' only colours the heat map and has no power report; choose a specific stat: %s", stat.label, t_concat(choices, ", ")) + end + local filter = args.filter or "unallocated" + local sort = args.sort or "power" + runPowerBuilder(build, stat, args.max_depth) + + local report = build.treeTab:BuildPowerReportList(stat) + local list = new("PowerReportListControl"):PowerReportListControl(nil, { 0, 0, 700, 170 }, nil) + list:SetReport(stat, report) + list.showClusters = filter == "unallocated_and_clusters" + list.allocated = filter == "allocated" + list.showMasteries = args.show_masteries ~= false + list:ReList() + list:ReSort(POWER_SORT_COLUMNS[sort]) + + local types + if args.types and args.types[1] then + types = { } + for _, name in ipairs(args.types) do + types[name] = true + end + end + local entries = { } + for _, entry in ipairs(list.list) do + if not types or types[tostring(entry.type):lower()] then + t_insert(entries, { + id = entry.id, + name = T.Clean(entry.name), + type = entry.type, + power = T.Round(entry.power), + perPoint = T.Round(entry.pathPower), + points = entry.pathDist == 1000 and "Anoint" or entry.pathDist, + allocated = entry.allocated and true or false, + stats = cleanLines(entry.sd), + }) + end + end + local displayStat + for _, ds in ipairs(build.displayStats) do + if ds.stat == stat.stat then + displayStat = ds + break + end + end + local _, calcBase = build.calcsTab:GetMiscCalculator() + local page, paging = T.Page(entries, args, 25) + return { + stat = stat.stat, + label = stat.label, + current = T.Round(data.powerStatList.GetFromOutput(calcBase, stat)), + percentScaled = displayStat and (displayStat.pc or displayStat.mod) and true or false, + lowerIsBetter = displayStat and displayStat.lowerIsBetter or false, + filter = filter, + sort = sort, + maxDepth = args.max_depth, + nodes = page, + page = paging, + } + end, +} + +------------------------------------------------------------------------------ +-- Timeless jewels +------------------------------------------------------------------------------ + +local TRADE_TYPES = { securable = 1, available = 2, onlineleague = 3, online = 4, any = 5 } +local REALMS = { pc = 1, sony = 2, xbox = 3 } + +-- Run fn with OpenURL and Copy capturing the trade link instead of opening a +-- browser, and without the league list download the finder starts. +local function withTradeStubs(fn) + local requests = common.classes.TradeQueryRequests + if not requests then + LoadModule("Classes/TradeQueryRequests") + requests = common.classes.TradeQueryRequests + end + local savedOpen, savedCopy, savedFetch = OpenURL, Copy, requests.FetchLeagues + local captured = { } + OpenURL = function(url) + t_insert(captured, url) + end + Copy = function() end + requests.FetchLeagues = function() end + local ok, result = pcall(fn, captured) + OpenURL, Copy, requests.FetchLeagues = savedOpen, savedCopy, savedFetch + if not ok then + error(result, 0) + end + return result +end + +-- The finder keeps its settings and results in build.timelessData (saved +-- with the build) and some choices on the Tree tab; a query puts them back. +local TREE_TAB_TIMELESS_FIELDS = { "tradeTypeIndex", "selectedRealmIndex", "timelessJewelLeagueSelect", "lastSearchMore", "allocatedNodesInRadiusCount", "tradeQueryRequests" } + +local function withTimelessStateRestored(build, fn) + local treeTab = build.treeTab + local timelessData = build.timelessData + local savedData = { } + for key, value in pairs(timelessData) do + savedData[key] = { value = value, contents = type(value) == "table" and copyTable(value, true) or nil } + end + local savedTab = { } + for _, key in ipairs(TREE_TAB_TIMELESS_FIELDS) do + savedTab[key] = treeTab[key] + end + local savedLeagues = copyTable(treeTab.tradeLeaguesList, true) + local savedModFlag, savedTreeModFlag = build.modFlag, treeTab.modFlag + local ok, result = pcall(fn) + for key in pairs(timelessData) do + if not savedData[key] then + timelessData[key] = nil + end + end + for key, saved in pairs(savedData) do + if saved.contents then + wipeTable(saved.value) + for k, v in pairs(saved.contents) do + saved.value[k] = v + end + end + timelessData[key] = saved.value + end + for _, key in ipairs(TREE_TAB_TIMELESS_FIELDS) do + treeTab[key] = savedTab[key] + end + wipeTable(treeTab.tradeLeaguesList) + for k, v in pairs(savedLeagues) do + treeTab.tradeLeaguesList[k] = v + end + build.modFlag, treeTab.modFlag = savedModFlag, savedTreeModFlag + if not ok then + error(result, 0) + end + return result +end + +-- "Search for Node" entries are labelled "<name> <first stat line>". +local function timelessModName(entry) + local label = T.Clean(entry.label or "") + return (label:match("^(.-)%s%s%s") or label) +end + +local function timelessMods(controls) + local mods = { } + for _, entry in ipairs(controls.nodeSelect.list) do + if entry.id then + t_insert(mods, { id = entry.id, name = timelessModName(entry), stats = cleanLines(entry.descriptions), total = entry.totalMod or nil }) + end + end + return mods +end + +local function timelessSockets(controls) + local sockets = { } + for _, entry in ipairs(controls.socketSelect.list) do + local label = T.Clean(entry.label) + t_insert(sockets, { + id = entry.id == -1 and "all" or entry.id, + label = (label:gsub("^# ", "")), + allocated = entry.id ~= -1 and label:sub(1, 2) == "# " or nil, + }) + end + return sockets +end + +-- The protect checkboxes the finder shows for the chosen socket. +local function protectBoxes(controls) + local boxes = { } + local i = 1 + while controls["protectAllocatedBox" .. i] do + t_insert(boxes, controls["protectAllocatedBox" .. i]) + i = i + 1 + end + return boxes +end + +local function findTimelessMod(controls, ref, jewelLabel) + local list = controls.nodeSelect.list + local wanted = T.Clean(tostring(ref)):lower() + for _, entry in ipairs(list) do + if entry.id and entry.id:lower() == wanted then + return entry + end + end + local exact, partial = { }, { } + for _, entry in ipairs(list) do + if entry.id then + local name = timelessModName(entry):lower() + if name == wanted then + t_insert(exact, entry) + elseif name:find(wanted, 1, true) or t_concat(entry.descriptions or { }, " "):lower():find(wanted, 1, true) then + t_insert(partial, entry) + end + end + end + local hits = exact[1] and exact or partial + if #hits == 1 then + return hits[1] + elseif #hits > 1 then + local names = { } + for i = 1, m_min(#hits, 15) do + t_insert(names, hits[i].id .. " (" .. timelessModName(hits[i]) .. ")") + end + T.Fail("'%s' matches several %s modifiers: %s. Pass the id.", tostring(ref), jewelLabel, t_concat(names, "; ")) + end + T.Fail("'%s' is not a %s modifier; list them with action 'options'.", tostring(ref), jewelLabel) +end + +local function timelessOptions(controls, timelessData, args) + local jewelType = timelessData.jewelType + local options = { + jewelTypes = { }, + jewelType = { id = jewelType.id, label = jewelType.label }, + conquerors = labels(controls.conquerorSelect.list), + sockets = timelessSockets(controls), + fallbackModes = { }, + } + for _, entry in ipairs(controls.jewelSelect.list) do + t_insert(options.jewelTypes, { id = entry.id, label = entry.label }) + end + for _, entry in ipairs(controls.fallbackWeightsList.list) do + t_insert(options.fallbackModes, { stat = entry.stat, label = entry.label }) + end + if controls.devotionSelectLabel.shown then + options.devotionModifiers = labels(controls.devotionSelect1.list) + end + if controls.abyssAscendancyLabel.shown then + options.ascendancyOutcomes = { } + for _, entry in ipairs(controls.abyssAscendancySelect.list) do + if entry.id then + t_insert(options.ascendancyOutcomes, { id = entry.id, label = entry.label }) + end + end + end + if controls.protectAllocatedLabel.shown() then + local names = { } + for _, box in ipairs(protectBoxes(controls)) do + t_insert(names, box.label) + end + options.protectableNodes = T.Array(names) + end + options.mods, options.modsPage = T.Page(timelessMods(controls), args, 100, 300) + return options +end + +local function timelessSearch(build, controls, captured, args) + local timelessData = build.timelessData + local jewelLabel = timelessData.jewelType.label + -- Conqueror (default the first entry, "Any" where there is a choice). + selectEntry(controls.conquerorSelect, args.conqueror and pickEntry(controls.conquerorSelect.list, args.conqueror, "conqueror") or 1) + -- Devotion modifiers (Militant Faith). + local devotion = args.devotion or { } + if devotion[1] and not controls.devotionSelectLabel.shown then + T.Fail("devotion applies to Militant Faith only.") + end + selectEntry(controls.devotionSelect1, devotion[1] and pickEntry(controls.devotionSelect1.list, devotion[1], "devotion modifier") or 1) + selectEntry(controls.devotionSelect2, devotion[2] and pickEntry(controls.devotionSelect2.list, devotion[2], "devotion modifier") or 1) + + if not (args.desired and args.desired[1]) and not args.fallback and not args.ascendancy_outcome then + T.Fail("Give desired nodes, a fallback mode or (for Reclaimed Malevolence) an ascendancy_outcome to search for.") + end + -- Desired nodes: lines of "id, weight, secondary weight, minimum weight". + local lines = { } + for _, want in ipairs(args.desired or { }) do + local entry = findTimelessMod(controls, want.node, jewelLabel) + local minimum = want.required and "required" or tostring(want.min_weight or 0) + t_insert(lines, s_format("%s, %s, %s, %s", entry.id, tostring(want.weight or 1), tostring(want.weight2 or 1), minimum)) + end + controls.searchList:SetText(t_concat(lines, "\n"), true) + controls.searchListFallback:SetText("", true) + if args.fallback then + local index = pickEntry(controls.fallbackWeightsList.list, args.fallback, "fallback mode", { "stat", "label" }) + selectEntry(controls.fallbackWeightsList, index) + controls.fallbackWeightsButton.onClick() + end + controls.totalMinimumWeight:SetText(args.total_minimum_weight and tostring(m_floor(args.total_minimum_weight)) or "", true) + if args.ascendancy_outcome then + if not controls.abyssAscendancyLabel.shown then + T.Fail("ascendancy_outcome applies to Reclaimed Malevolence only.") + end + selectEntry(controls.abyssAscendancySelect, pickEntry(controls.abyssAscendancySelect.list, args.ascendancy_outcome, "ascendancy outcome", { "label", "id" })) + end + for _, name in ipairs(args.protect or { }) do + if not controls.protectAllocatedLabel.shown() then + T.Fail("protect needs filter_nodes, a single socket, and Militant Faith or Reclaimed Malevolence (as in Path of Building).") + end + local box = T.Find(protectBoxes(controls), name, function(candidate) return candidate.label end, "protectable node") + box.state = true + box.changeFunc(true) + end + + -- Path of Building leaves earlier results when it finds nothing to search. + wipeTable(timelessData.searchResults) + wipeTable(timelessData.sharedResults) + local started = os.clock() + controls.searchButton.onClick() + local seconds = os.clock() - started + + local results = timelessData.searchResults + local shared = timelessData.sharedResults + local desired = { } + for legionId, node in pairs(shared.desiredNodes or { }) do + t_insert(desired, { id = legionId, name = T.Clean(node.displayName), index = node.desiredIdx, weight = node.nodeWeight, weight2 = node.nodeWeight2 }) + end + t_sort(desired, function(a, b) return a.index < b.index end) + local rows = { } + for rank, row in ipairs(results) do + local gives = { } + for _, wantedNode in ipairs(desired) do + local hit = row[wantedNode.id] + if hit then + t_insert(gives, { id = wantedNode.id, name = wantedNode.name, nodes = hit.targetNodeNames }) + end + end + t_insert(rows, { + rank = rank, + seed = row.seed, + total = T.Round(row.total, 3), + socket = row.socketId or (shared.socket and shared.socket.id), + socketLabel = row.socketLabel and T.Clean(row.socketLabel) or nil, + gives = T.Array(gives), + }) + end + local page, paging = T.Page(rows, { limit = args.max_results, offset = args.offset }, 20, 500) + for _, entry in ipairs(desired) do + entry.index = nil + end + local result = { + jewelType = jewelLabel, + conqueror = T.Clean(timelessData.conquerorType.label or ""), + socket = timelessData.jewelSocket.id == -1 and "all" or timelessData.jewelSocket.id, + searchList = timelessData.searchList, + desired = T.Array(desired), + resultCount = #results, + seconds = T.Round(seconds, 2), + results = page, + page = paging, + } + + if args.trade and results[1] then + local trade = args.trade + -- Realm and league are set without their selFuncs, which would fetch league lists; the link reads both from the dropdowns. + controls.realmSelection.selIndex = REALMS[trade.realm or "pc"] + controls.searchTradeLeagueSelect.list = { T.Sanitise(trade.league) } + controls.searchTradeLeagueSelect.selIndex = 1 + selectEntry(controls.tradeTypeSelection, TRADE_TYPES[trade.trade_type or "securable"]) + controls.searchMore.state = trade.search_more == true + if trade.start_rank then + controls.searchResults.selIndex = m_min(trade.start_rank, #results) + end + local links = { } + for _ = 1, trade.pages or 1 do + local before = #captured + controls.searchTradeButton.onClick() + if #captured == before then + break + end + local first = controls.searchResults.selIndex + local last = m_min(controls.searchResults.highlightIndex or first, #results) + local seeds = { } + for r = first, last do + t_insert(seeds, results[r].seed) + end + t_insert(links, { url = captured[#captured], fromRank = first, toRank = last, seeds = seeds }) + end + result.trade = { league = trade.league, realm = trade.realm or "pc", tradeType = trade.trade_type or "securable", links = links } + end + return result +end + +T.Tool { + name = "tree_timeless_jewel", + title = "Find a timeless jewel", + description = "Uses Path of Building's 'Find a Timeless Jewel' finder (Tree tab). Action 'options' lists the jewel types, the " + .. "conquerors of a type, the jewel sockets (with whether each is allocated), the modifiers the type can give (ids and stats, " + .. "to use as desired nodes), fallback weight modes, devotion modifiers (Militant Faith), ascendancy outcomes (Reclaimed " + .. "Malevolence) and, for a socket with filter_nodes, the allocated notables that can be protected. Action 'search' scores " + .. "every seed of the jewel type in one socket (or all sockets) by the desired modifiers' weights and returns the best seeds " + .. "with which nodes give what; 'trade' adds pathofexile.com trade search links for them (returned only, never opened). The " + .. "finder's saved settings and results in the build are left as they were. Searching can take a while, longest for all sockets.", + readOnly = true, + usesDialog = true, + input = { + action = { type = "string", enum = { "options", "search" }, description = "options: what can be chosen; search: find seeds." }, + jewel_type = { type = { "string", "integer" }, description = "Jewel type: name ('Glorious Vanity', 'Militant Faith', ...), its id (1-11) or internal name ('vaal'). Required for search." }, + conqueror = { type = "string", description = "Conqueror, for example 'Avarius' (default Any)." }, + socket = { type = { "integer", "string" }, description = "Jewel socket node id, or 'all' for every socket. Required for search." }, + desired = { + type = "array", maxItems = 100, + items = { + type = "object", + properties = { + node = { type = "string", description = "Modifier id or name, from options." }, + weight = { type = "number", minimum = 0, description = "Weight of the first stat (default 1)." }, + weight2 = { type = "number", minimum = 0, description = "Weight of the second stat, for modifiers with two (default 1)." }, + min_weight = { type = "number", minimum = 0, description = "Seeds where this modifier scores less are left out (default 0)." }, + required = { type = "boolean", description = "Leave out seeds without this modifier." }, + }, + required = { "node" }, + additionalProperties = false, + }, + description = "The modifiers to look for, with their weights.", + }, + fallback = { type = "string", description = "Fill the fallback list with PoB's 'Generate' weights for this stat (key or label, for example 'FullDPS' or 'Life'); used for modifiers not in desired." }, + filter_nodes = { type = "boolean", description = "Only score nodes allocated on the tree (PoB's 'Filter Nodes')." }, + filter_distance = { type = "integer", minimum = 0, maximum = 10, description = "With filter_nodes: also score unallocated nodes this many points away." }, + devotion = { type = "array", items = { type = "string" }, maxItems = 2, description = "Militant Faith: up to two devotion modifiers the jewel must have." }, + total_minimum_weight = { type = "number", minimum = 0, description = "Leave out seeds whose total weight is lower." }, + protect = { type = "array", items = { type = "string" }, maxItems = 30, description = "Allocated notables that must not be replaced (Militant Faith or Reclaimed Malevolence, with filter_nodes)." }, + ascendancy_outcome = { type = "string", description = "Reclaimed Malevolence: the ascendancy notable the seed must give." }, + max_results = { type = "integer", minimum = 1, maximum = 500, description = "How many seeds to return (default 20)." }, + offset = { type = "integer", minimum = 0, description = "Skip this many seeds (search), or modifiers (options)." }, + limit = { type = "integer", minimum = 1, maximum = 300, description = "options: how many modifiers to list (default 100)." }, + trade = { + type = "object", + properties = { + league = { type = "string", description = "Trade league, for example 'Standard'." }, + realm = { type = "string", enum = { "pc", "sony", "xbox" }, description = "Default pc." }, + trade_type = { type = "string", enum = { "securable", "available", "onlineleague", "online", "any" }, description = "Listing status filter (default securable: instant buyout)." }, + search_more = { type = "boolean", description = "Put up to 180 seeds in one link instead of a few (loses the ranking order)." }, + pages = { type = "integer", minimum = 1, maximum = 10, description = "How many links, each covering the next seeds (default 1)." }, + start_rank = { type = "integer", minimum = 1, description = "Rank of the first seed in the first link (default 1)." }, + }, + required = { "league" }, + additionalProperties = false, + description = "Also return trade search links for the found seeds.", + }, + }, + required = { "action" }, + run = function(args) + local build = T.Build() + build:ProcessBuildFlag() + if args.action == "search" and (args.jewel_type == nil or args.socket == nil) then + T.Fail("search needs jewel_type and socket (a socket id or 'all'); action 'options' lists them.") + end + return withTimelessStateRestored(build, function() + return withTradeStubs(function(captured) + return withDialog(function() + build.treeTab:FindTimelessJewel() + end, function(popup) + local controls = popup.controls + local timelessData = build.timelessData + if args.jewel_type ~= nil then + local index = pickEntry(controls.jewelSelect.list, args.jewel_type, "jewel type", { "label", "name" }) + selectEntry(controls.jewelSelect, index) + end + if args.socket ~= nil then + local socket = args.socket + local index + if socket == "all" or socket == -1 then + index = 1 + elseif tonumber(socket) then + for i, entry in ipairs(controls.socketSelect.list) do + if entry.id == tonumber(socket) then + index = i + end + end + if not index then + T.Fail("%s is not a jewel socket the finder offers; action 'options' lists them.", tostring(socket)) + end + else + index = pickEntry(controls.socketSelect.list, socket, "jewel socket") + end + selectEntry(controls.socketSelect, index) + end + local filter = args.filter_nodes == true or (args.action == "options" and args.socket ~= nil) + controls.socketFilter.state = filter + controls.socketFilter.changeFunc(filter) + if filter then + local distance = args.filter_distance or 0 + controls.socketFilterAdditionalDistance:SetVal(distance / 10) + timelessData.socketFilterDistance = distance + end + if args.action == "options" then + return timelessOptions(controls, timelessData, args) + end + return timelessSearch(build, controls, captured, args) + end) + end) + end) + end, +} + +------------------------------------------------------------------------------ +-- Tattoos +------------------------------------------------------------------------------ + +-- The nodes a right click opens the tattoo dialog on (PassiveTreeView). +local function tattooable(node) + if node.expansionSkill then + return false + end + if node.isTattoo or node.type == "Keystone" + or (node.type == "Normal" and (node.dn == "Strength" or node.dn == "Dexterity" or node.dn == "Intelligence")) + or (node.type == "Notable" and #node.sd > 0 and (node.sd[1]:match("+30 to Dexterity") or node.sd[1]:match("+30 to Strength") or node.sd[1]:match("+30 to Intelligence"))) then + return true + end + -- Runegrafts go on unallocated masteries through the same dialog. + return node.type == "Mastery" and not node.alloc and node.masteryEffects ~= nil +end + +local function currentTattoo(spec, node) + local override = spec.hashOverrides[node.id] + if override then + return { name = override.dn, stats = cleanLines(override.sd) } + end +end + +-- Open PoB's tattoo dialog (TreeTab:ModifyNodePopup) on a node and use it. +-- The dialog remembers the last choice per node name (defaultTattoo) and the +-- legacy checkbox on the Tree tab; both are put back afterwards. It opens +-- without a remembered choice, since one from the longer legacy list can +-- point past the end of the normal list. +local function withTattooDialog(build, node, includeLegacy, use) + local treeTab = build.treeTab + local nodeName = build.spec.tree.nodes[node.id].dn + local savedLegacy, savedDefault = treeTab.showLegacyTattoo, treeTab.defaultTattoo[nodeName] + treeTab.showLegacyTattoo = false + treeTab.defaultTattoo[nodeName] = nil + local ok, result = pcall(withDialog, function() + treeTab:ModifyNodePopup(node) + end, function(popup) + local controls = popup.controls + if includeLegacy then + controls.showLegacyTattoo.state = true + controls.showLegacyTattoo.changeFunc(true) + end + return use(controls) + end, "Path of Building offers no tattoo for this node%s") + treeTab.showLegacyTattoo, treeTab.defaultTattoo[nodeName] = savedLegacy, savedDefault + if not ok then + error(result, 0) + end + return result +end + +local function tattooOptions(build, controls) + local tattooNodes = build.spec.tree.tattoo.nodes + local options = { } + for _, entry in ipairs(controls.modSelect.list) do + local tattoo = tattooNodes[entry.id] + t_insert(options, { + id = entry.id, + name = tattoo and tattoo.dn or timelessModName(entry), + stats = cleanLines(entry.descriptions), + legacy = tattoo and tattoo.legacy or nil, + }) + end + return options +end + +T.Tool { + name = "tree_tattoos", + title = "Tattoos and runegrafts", + description = "Uses the Tree tab's tattoo dialog (right click on a node): 'list' shows the tattoos Path of Building offers for a " + .. "node, 'apply' replaces the node with one (its 'Add' button), 'reset' removes the tattoo from a node ('Reset Node'). " + .. "Tattoos go on small attribute nodes, +30 attribute notables and keystones; runegrafts on unallocated masteries. Tattoos " + .. "are given by id or name as listed; include_legacy also lists legacy tattoos. Results include PoB's tattoo count: the game " + .. "allows at most 50 tattoos, which PoB counts but does not enforce. simulate cannot preview tattoos; after apply or reset, " + .. "statChanges lists what changed. Changes are unsaved until build_save.", + modifies = true, + usesDialog = true, + input = { + action = { type = "string", enum = { "list", "apply", "reset" }, description = "What to do." }, + node = { type = { "integer", "string" }, description = "The node, by id or name (find it with tree_search)." }, + tattoo = { type = "string", description = "For apply: the tattoo's id or name from list." }, + include_legacy = { type = "boolean", description = "Include legacy tattoos." }, + }, + required = { "action", "node" }, + run = function(args, ctx) + local build = T.Build() + local spec = build.spec + local node = T.FindNode(spec, args.node) + if not tattooable(node) then + T.Fail("%s (%s) cannot be tattooed: tattoos replace small attribute nodes, +30 attribute notables and keystones; runegrafts go on unallocated masteries.", node.dn, node.type) + end + local baseName = spec.tree.nodes[node.id].dn + local result = { id = node.id, node = baseName, allocated = node.alloc and true or false, tattooLimit = 50 } + if args.action == "list" then + result.options = withTattooDialog(build, node, args.include_legacy, function(controls) + return tattooOptions(build, controls) + end) + result.current = currentTattoo(spec, node) + elseif args.action == "apply" then + if not args.tattoo then + T.Fail("Give the tattoo with 'tattoo'; action 'list' shows them.") + end + result.replaced = currentTattoo(spec, node) + withTattooDialog(build, node, args.include_legacy, function(controls) + local options = tattooOptions(build, controls) + local index + for i, option in ipairs(options) do + option.index = i + if option.id == args.tattoo then + index = i + end + end + if not index then + index = T.Find(options, args.tattoo, function(option) return option.name end, "tattoo for " .. baseName).index + end + selectEntry(controls.modSelect, index) + controls.save.onClick() + end) + result.applied = currentTattoo(spec, spec.nodes[node.id]) + ctx:Changed() + else + if not spec.hashOverrides[node.id] then + T.Fail("%s (%d) has no tattoo.", baseName, node.id) + end + result.removed = currentTattoo(spec, node) + withTattooDialog(build, node, true, function(controls) + controls.reset.onClick() + end) + ctx:Changed() + end + result.tattooCount = tattooCount(spec) + return result + end, +} From 7a5b6cb782c6d51c386582baca1a53a9ec2e1938 Mon Sep 17 00:00:00 2001 From: Filipe Cavalcante <filipecavalc@gmail.com> Date: Mon, 16 Nov 2026 14:34:08 -0300 Subject: [PATCH 4/7] MCP server: fixes from review - Replacing the open build only sets abortSave right before the switch, so a failed build_open or import no longer closes the build on the next frame outside Dev Mode; build XML is validated before anything is replaced, and a new build's class and ascendancy before it opens. - Deferred calls answer exactly once, never apply a result that arrives after their timeout, refuse to change the build while the user has a dialog open, and close only the dialogs they opened themselves. A tool that fails after changing something still marks the build unsaved and says so. - Malformed chunked bodies are answered with 400 instead of raising, the bytes buffered per connection are capped, and unexpected errors while handling a request are answered with 500. - Poll runs at the start of main:OnFrame, before input is handled, so typing or using a dialog counts as using the window. - build_save refuses while a dialog is open, never runs a pending save action, and restores the build's name and file when writing fails. - config_set checks the custom modifier group before changing options. - Host and Origin must carry this server's port. - Comparison and import callbacks detect another build opening by its tabs. - Editing tools that remove or overwrite are marked destructive. --- spec/System/TestMcpServer_spec.lua | 34 +++++++ src/Modules/Main.lua | 7 +- src/Modules/McpHttp.lua | 9 +- src/Modules/McpProtocol.lua | 14 ++- src/Modules/McpServer.lua | 22 ++++- src/Modules/McpTools.lua | 141 ++++++++++++++++++++--------- src/Modules/McpTools/Build.lua | 42 ++++++++- src/Modules/McpTools/Compare.lua | 13 ++- src/Modules/McpTools/Config.lua | 34 ++++--- src/Modules/McpTools/Tree.lua | 2 + 10 files changed, 241 insertions(+), 77 deletions(-) diff --git a/spec/System/TestMcpServer_spec.lua b/spec/System/TestMcpServer_spec.lua index 6e4eb9c2263..81841e440de 100644 --- a/spec/System/TestMcpServer_spec.lua +++ b/spec/System/TestMcpServer_spec.lua @@ -118,6 +118,14 @@ describe("MCP server", function() assert.is_truthy(response:find("Content-Length: 2\r\n", 1, true)) assert.are.equals("{}", response:match("\r\n\r\n(.*)$")) end) + it("answers malformed chunked bodies with an error status instead of failing", function() + local req, status = McpHttp.ParseRequest("POST /mcp HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\nzz\r\n") + assert.is_nil(req) + assert.are.equals(400, status) + req, status = McpHttp.ParseRequest("POST /mcp HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n" .. string.rep("1", 100)) + assert.is_nil(req) + assert.are.equals(400, status) + end) it("refuses a POST without a length and oversized bodies", function() local _, status = McpHttp.ParseRequest("POST /mcp HTTP/1.1\r\nHost: x\r\n\r\n") assert.are.equals(411, status) @@ -132,6 +140,9 @@ describe("MCP server", function() assert.are.equals(403, (request("tools/list", nil, { origin = "https://evil.example" }))) assert.are.equals(401, (request("tools/list", nil, { authorization = "Bearer wrong" }))) assert.are.equals(200, (request("tools/list", nil, { origin = "http://localhost:" .. PORT }))) + -- Without a port, a host or origin means port 80, not this server. + assert.are.equals(403, (request("tools/list", nil, { host = "localhost" }))) + assert.are.equals(403, (request("tools/list", nil, { origin = "http://localhost" }))) end) it("only serves POST on /mcp", function() assert.are.equals(405, (request("tools/list", nil, { httpMethod = "GET" }))) @@ -294,6 +305,29 @@ describe("MCP server", function() assert.are.equals("Necromancer", opened.opened.ascendancy) end) + it("leaves the open build alone when replacing it fails", function() + callTool("build_edit", { level = 55 }) + local message = toolError("build_open", { path = "No Such Build", discard_unsaved = true }) + assert.is_truthy(message:find("No build file", 1, true)) + -- Outside Dev Mode, abortSave would close the build on the next frame. + assert.is_falsy(build.abortSave) + message = toolError("build_open", { code = "<x/>", discard_unsaved = true }) + assert.is_truthy(message:find("not a Path of Building build", 1, true)) + message = toolError("build_open", { new = true, class = "Wizard", discard_unsaved = true }) + assert.is_truthy(message:find("Unknown class", 1, true)) + assert.is_falsy(build.abortSave) + assert.are.equals(55, build.characterLevel) + assert.is_true(build:HasUnsavedChanges()) + end) + + it("does not save while a dialog is open", function() + main:OpenMessagePopup("Test", "A dialog the user has open") + local message = toolError("build_save", { name = "Anything" }) + assert.is_truthy(message:find("dialog is open", 1, true)) + assert.are.equals("Test", main.popups[1].title) + main:ClosePopup() + end) + it("edits the level and notes and marks the build unsaved", function() build:ResetModFlags() local result = callTool("build_edit", { level = 72, notes = "Hello" }) diff --git a/src/Modules/Main.lua b/src/Modules/Main.lua index 22405380a9d..6fdfebbc134 100644 --- a/src/Modules/Main.lua +++ b/src/Modules/Main.lua @@ -406,6 +406,10 @@ function main:OnFrame() end self:ProcessModeChange() + -- Answer MCP requests before this frame's input is handled: the server reads that input + -- to tell whether someone is using the window, and its changes are drawn in this frame + self.mcpServer:Poll(self.inputEvents) + self.viewPort = { x = 0, y = 0, width = self.screenW, height = self.screenH } if self.popups[1] then @@ -493,9 +497,6 @@ function main:OnFrame() end itemLib.wiki.triggered = false - -- Answer MCP requests between frames; it looks at this frame's input to tell whether the window is in use - self.mcpServer:Poll(self.inputEvents) - wipeTable(self.inputEvents) -- TODO: this pattern may pose memory management issues for classes that don't exist for the lifetime of the program diff --git a/src/Modules/McpHttp.lua b/src/Modules/McpHttp.lua index 71475d4b929..11dfd7d10f3 100644 --- a/src/Modules/McpHttp.lua +++ b/src/Modules/McpHttp.lua @@ -42,9 +42,13 @@ local function decodeChunked(data) while true do local lineEnd = data:find("\r\n", pos, true) if not lineEnd then + if #data - pos > 64 then + return false, "invalid chunk size" + end return nil end - local chunkSize = tonumber(data:sub(pos, lineEnd - 1):match("^%s*(%x+)"), 16) + local hex = data:sub(pos, lineEnd - 1):match("^%s*(%x+)") + local chunkSize = hex and #hex <= 8 and tonumber(hex, 16) if not chunkSize then return false, "invalid chunk size" end @@ -54,6 +58,9 @@ local function decodeChunked(data) while true do local trailerEnd = data:find("\r\n", pos, true) if not trailerEnd then + if #data - pos > M.MAX_HEADER_BYTES then + return false, "trailer too large" + end return nil end local isEmpty = trailerEnd == pos diff --git a/src/Modules/McpProtocol.lua b/src/Modules/McpProtocol.lua index 03fbf26b781..f5926799957 100644 --- a/src/Modules/McpProtocol.lua +++ b/src/Modules/McpProtocol.lua @@ -242,7 +242,7 @@ Server.__index = Server --- port number: the port the server listens on (for Host and Origin checks) --- getToken function: returns the bearer token clients must send --- serverInfo table: { name, title, version } ---- instructions string: guidance for the client's model +--- instructions string: usage guidance for clients --- tools table: { list = function() -> defs, call = function(def, args, finish) } --- finish(result) with a JSON-able table, or finish(nil, message) for an error --- prompts table|nil: { list = function() -> defs, get = function(name, args) -> result | nil, message } @@ -309,25 +309,23 @@ function Server:OriginAllowed(origin) if origin == nil then return true end - local host, port = origin:lower():match("^https?://([^/:]+):?(%d*)/?$") - if not host then - return false - end + -- Without a port an origin means port 80 or 443, a different origin from this server. + local host, port = origin:lower():match("^https?://([^/:]+):(%d+)/?$") if host ~= "127.0.0.1" and host ~= "localhost" then return false end - return port == "" or tonumber(port) == self.options.port + return tonumber(port) == self.options.port end function Server:HostAllowed(hostHeader) if not hostHeader then return false end - local host, port = hostHeader:lower():match("^([^:]+):?(%d*)$") + local host, port = hostHeader:lower():match("^([^:]+):(%d+)$") if host ~= "127.0.0.1" and host ~= "localhost" then return false end - return port == "" or tonumber(port) == self.options.port + return tonumber(port) == self.options.port end function Server:Authorized(authorization) diff --git a/src/Modules/McpServer.lua b/src/Modules/McpServer.lua index c46fedd9a0f..eb35c9e1549 100644 --- a/src/Modules/McpServer.lua +++ b/src/Modules/McpServer.lua @@ -159,6 +159,9 @@ function server:Start() end self.listener = listener self.protocol = protocol + -- Treat the window as in use when the server starts, so hovering it right away stays smooth. + self.lastInput = GetTime() + self.lastInputEvent = self.lastInput -- SimpleGraphic skips OnFrame for a window that is unfocused, not under the -- cursor and has no suspended coroutine (ui_main.cpp, ui_main_c::Frame), so -- requests would wait until someone touches the window. A coroutine kept @@ -283,7 +286,7 @@ function server:HandleRequest(connection, request) connection.busy = true local keepAlive = McpHttp.KeepAlive(request) local answered = false - self.protocol:HandleHttp(request, function(response) + local function respond(response) if answered then return end @@ -297,7 +300,14 @@ function server:HandleRequest(connection, request) if not keepAlive then connection.closeAfterFlush = true end - end) + end + -- Tool errors are handled inside the protocol; this catches anything else so it never reaches PoB's frame. + local ok, err = pcall(self.protocol.HandleHttp, self.protocol, request, respond) + if not ok then + ConPrintf("MCP server: %s", tostring(err)) + keepAlive = false + respond({ status = 500, headers = { ["Content-Type"] = "text/plain" }, body = "internal error" }) + end end --- Called once per frame from main:OnFrame. @@ -353,7 +363,13 @@ function server:Poll(inputEvents) end end if keep and not connection.busy and connection.buffer ~= "" and not connection.closeAfterFlush then - local request, rest, message = McpHttp.ParseRequest(connection.buffer) + local parsed, request, rest, message = pcall(McpHttp.ParseRequest, connection.buffer) + if not parsed then + request, rest, message = nil, 400, "malformed request" + elseif not request and not rest and #connection.buffer > McpHttp.MAX_HEADER_BYTES + McpHttp.MAX_BODY_BYTES + 4096 then + -- Nothing complete in far more bytes than any request may have. + rest, message = 413, "request too large" + end if request then connection.buffer = rest self:HandleRequest(connection, request) diff --git a/src/Modules/McpTools.lua b/src/Modules/McpTools.lua index e46420859f9..c06e5f3701e 100644 --- a/src/Modules/McpTools.lua +++ b/src/Modules/McpTools.lua @@ -17,6 +17,7 @@ local McpProtocol = LoadModule("Modules/McpProtocol") local t_insert = table.insert +local t_remove = table.remove local t_concat = table.concat local s_format = string.format local m_min = math.min @@ -117,26 +118,45 @@ function T.CheckCanReplaceBuild(args) end if main.mode == "BUILD" then local build = main.modes["BUILD"] - if build.targetVersion and build.spec and build:HasUnsavedChanges() then - if not args.discard_unsaved then - T.Fail("The build open in Path of Building (%s) has unsaved changes (%s). Save it with build_save, or ask the user; " - .. "pass discard_unsaved: true only if the user agreed to lose them.", build.buildName or "?", t_concat(T.UnsavedParts(build), ", ")) - end - -- Dev Mode saves a closing build to its file; do not write changes the user chose to discard. - build.abortSave = true + if build.targetVersion and build.spec and build:HasUnsavedChanges() and not args.discard_unsaved then + T.Fail("The build open in Path of Building (%s) has unsaved changes (%s). Save it with build_save, or ask the user; " + .. "pass discard_unsaved: true only if the user agreed to lose them.", build.buildName or "?", t_concat(T.UnsavedParts(build), ", ")) + end + end +end + +--- Fail unless text is build XML Path of Building can load, before anything is replaced +--- (a load that fails shows PoB's full-screen error instead). +function T.CheckBuildXML(xml) + local parsed = type(xml) == "string" and common.xml.ParseXML(xml) + if not parsed or type(parsed[1]) ~= "table" or parsed[1].elem ~= "PathOfBuilding" then + T.Fail("That is not a Path of Building build (no PathOfBuilding root element).") + end + for _, node in ipairs(parsed[1]) do + if type(node) == "table" and node.elem == "Build" then + return xml end end + T.Fail("That is not a Path of Building build (no Build section).") end --- Switch PoB to a build now (main:SetMode, then the switch PoB would do on ---- the next frame), and check that it opened. +--- the next frame), and check that it opened. Call it only after everything +--- the switch depends on was checked, including T.CheckCanReplaceBuild. function T.SwitchToBuild(...) + if main.mode == "BUILD" and main.modes["BUILD"].targetVersion then + -- Dev Mode saves a closing build to its file; the caller already decided this one may be + -- replaced, so do not write changes the user chose to discard. (Shutdown clears the flag.) + main.modes["BUILD"].abortSave = true + end main:SetMode("BUILD", ...) main:ProcessModeChange() local build = main.modes["BUILD"] - if main.mode == "BUILD" and build.spec and not build.targetVersion then - -- PoB asks whether to convert a build made for an older game version. - main:ClosePopup() + if main.mode == "BUILD" and not build.targetVersion then + -- PoB asks whether to convert a build made for an older game version (buildMode:OpenConversionPopup). + if main.popups[1] and main.popups[1].title == "Game Version" then + main:ClosePopup() + end build:CloseBuild() main:ProcessModeChange() T.Fail("This build was made for an older version of Path of Exile and has to be converted; open it in Path of Building to choose.") @@ -210,8 +230,38 @@ function T.PageArgs(defaultLimit, maxLimit) } end +local function failureMessage(err) + if type(err) == "table" and err.mcpFailure then + return err.mcpFailure + end + return "Path of Building raised an error: " .. tostring(err) +end + +local DIALOG_OPEN = "A dialog is open in Path of Building; ask the user to finish or close it first, then try again." + +-- The dialogs open now, to close later only those a tool opened itself. +local function openPopups() + local set = { } + for _, popup in ipairs(main.popups) do + set[popup] = true + end + return set +end + +local function closePopupsOpenedSince(before) + for i = #main.popups, 1, -1 do + if not before[main.popups[i]] then + t_remove(main.popups, i) + end + end +end + +-- The resolve functions handed to deferred tools, with their pending call. +local resolverEntries = setmetatable({ }, { __mode = "k" }) + --- A tool result that arrives later (a download PoB runs, for example). ---- starter(resolve) must eventually call resolve(result) or resolve(nil, message). +--- starter(resolve) must eventually call resolve(result) or resolve(nil, message); +--- do the work in the callback through T.Settle. function T.Defer(starter, timeoutSeconds) return { mcpDeferred = starter, timeout = timeoutSeconds or 60 } end @@ -219,12 +269,23 @@ end --- Run fn(...) and pass its result, or its failure message, to a deferred --- tool's resolve. Use it for work done in a callback PoB calls later (a --- download finishing), where a T.Fail would otherwise escape into PoB. +--- Nothing runs once the call has already been answered (timed out), and a +--- tool that changes the build does not run while the user has a dialog open. function T.Settle(resolve, fn, ...) + local entry = resolverEntries[resolve] + if entry and entry.done then + return + end + if entry and (entry.def.modifies or entry.def.replacesBuild) and main.popups[1] then + return resolve(nil, DIALOG_OPEN) + end + local before = openPopups() local ok, result = pcall(fn, ...) + closePopupsOpenedSince(before) if ok then return resolve(result) end - resolve(nil, type(result) == "table" and result.mcpFailure or ("Path of Building raised an error: " .. tostring(result))) + resolve(nil, failureMessage(result)) end --- A PoB tooltip stand-in that records its lines, for PoB functions that @@ -279,13 +340,6 @@ T.discardUnsavedArg = { description = "Replace the open build even though it has unsaved changes, losing them. Only pass true when the user has agreed.", } -local function failureMessage(err) - if type(err) == "table" and err.mcpFailure then - return err.mcpFailure - end - return "Path of Building raised an error: " .. tostring(err) -end - -- Run a tool with the shared guards, then report through finish. local function callTool(def, args, finish) if def.needsBuild ~= false then @@ -295,26 +349,26 @@ local function callTool(def, args, finish) end end if (def.modifies or def.replacesBuild or def.usesDialog) and main.popups[1] then - return finish(nil, "A dialog is open in Path of Building; ask the user to finish or close it first, then try again.") + return finish(nil, DIALOG_OPEN) end local ctx = { changed = false } function ctx:Changed() self.changed = true end - local popupsBefore = #main.popups -- The output before a change, to report what the change did as the side bar would. local outputBefore = def.modifies and main.mode == "BUILD" and main.modes["BUILD"].calcsTab and main.modes["BUILD"].calcsTab.mainOutput local function complete(ok, result, message) - -- Close any dialog the tool opened and left behind. - while #main.popups > popupsBefore do - main:ClosePopup() - end - if ok and ctx.changed and main.mode == "BUILD" then + if ctx.changed and main.mode == "BUILD" and main.modes["BUILD"].targetVersion then local build = main.modes["BUILD"] -- Edits made here bypass the controls that would set a tab's flag. build.modFlag = true build:ProcessBuildFlag() + if not ok or result == nil then + -- The change stays (and shows as unsaved), so say so. + message = (ok and (message or "the tool returned no result") or failureMessage(result)) .. " (Some changes were already made before this error; they show in Path of Building as unsaved.)" + return finish(nil, message) + end if outputBefore and type(result) == "table" and result.statChanges == nil then local collector = T.LineCollector() build:AddStatComparesToTooltip(collector, outputBefore, build.calcsTab.mainOutput, "Changes:") @@ -335,9 +389,13 @@ local function callTool(def, args, finish) return finish(result) end + local popupsBefore = openPopups() local ok, result, message = pcall(def.run, args, ctx) + -- Close any dialog the tool opened and left behind (never one the user opened). + closePopupsOpenedSince(popupsBefore) if ok and type(result) == "table" and result.mcpDeferred then - local entry = { deadline = os.clock() + result.timeout, timeout = result.timeout } + local entry = { def = def, deadline = os.clock() + result.timeout, timeout = result.timeout } + -- Answers exactly once, whatever happens while answering. entry.resolve = function(value, err) if entry.done then return @@ -345,26 +403,23 @@ local function callTool(def, args, finish) entry.done = true for i, other in ipairs(pending) do if other == entry then - table.remove(pending, i) + t_remove(pending, i) break end end - local resolvedOk, resolved, resolvedMessage = true, value, err - if type(err) == "table" then - resolvedOk, resolved = false, err + local completed, completeErr = pcall(complete, true, value, err) + if not completed then + pcall(finish, nil, failureMessage(completeErr)) end - complete(resolvedOk, resolved, resolvedMessage) end + local resolver = function(value, err) + entry.resolve(value, err) + end + resolverEntries[resolver] = entry t_insert(pending, entry) - local started, startErr = pcall(result.mcpDeferred, function(value, err) - -- Resolvers may themselves fail with T.Fail; report that as the result. - local resolveOk, resolveErr = pcall(entry.resolve, value, err) - if not resolveOk then - entry.resolve(nil, { mcpFailure = failureMessage(resolveErr) }) - end - end) + local started, startErr = pcall(result.mcpDeferred, resolver) if not started then - entry.resolve(nil, { mcpFailure = failureMessage(startErr) }) + entry.resolve(nil, failureMessage(startErr)) end return end @@ -376,8 +431,8 @@ function M.OnFrame() local now = os.clock() for i = #pending, 1, -1 do local entry = pending[i] - if now > entry.deadline then - entry.resolve(nil, { mcpFailure = s_format("No answer within %d seconds; try again later.", entry.timeout) }) + if entry and now > entry.deadline then + pcall(entry.resolve, nil, s_format("No answer within %d seconds; try again later.", entry.timeout)) end end end diff --git a/src/Modules/McpTools/Build.lua b/src/Modules/McpTools/Build.lua index 6898840186d..462de27d47a 100644 --- a/src/Modules/McpTools/Build.lua +++ b/src/Modules/McpTools/Build.lua @@ -76,13 +76,13 @@ end function T.DecodeBuildCode(code) code = code:gsub("^%s+", ""):gsub("%s+$", "") if code:sub(1, 1) == "<" then - return code + return T.CheckBuildXML(code) end local xml = Inflate(common.base64.decode((code:gsub("-", "+"):gsub("_", "/")))) if not xml or not xml:match("<PathOfBuilding") then T.Fail("That is not a Path of Building build code (or the code is incomplete).") end - return xml + return T.CheckBuildXML(xml) end function T.EncodeBuildCode(xml) @@ -263,6 +263,32 @@ T.Tool { end) end, 60) else + if args.class or args.ascendancy then + -- Check the names on the tree a new build gets before replacing the open build. + local tree = main:LoadTree(latestTreeVersion) + local class = tree.classes[0] + local classNames, ascendancyNames = { }, { } + for _, candidate in pairs(tree.classes) do + t_insert(classNames, candidate.name) + if args.class and candidate.name:lower() == args.class:lower() then + class = candidate + end + end + if args.class and class.name:lower() ~= args.class:lower() then + table.sort(classNames) + T.Fail("Unknown class '%s'. Classes: %s", args.class, t_concat(classNames, ", ")) + end + if args.ascendancy then + local found = false + for _, ascendClass in pairs(class.classes) do + t_insert(ascendancyNames, ascendClass.name) + found = found or ascendClass.name:lower() == args.ascendancy:lower() + end + if not found then + T.Fail("%s has no ascendancy '%s'. Ascendancies: %s", class.name, args.ascendancy, t_concat(ascendancyNames, ", ")) + end + end + end local build = T.SwitchToBuild(false, name or "Unnamed build") if args.class or args.ascendancy then T.SelectClass(build, args.class, args.ascendancy, false) @@ -343,6 +369,11 @@ T.Tool { }, run = function(args) local build = T.Build() + if main.popups[1] then + -- e.g. "Save changes before exiting?": its Save As would then exit, update or close the build. + T.Fail("A dialog is open in Path of Building; ask the user to finish or close it first, then try again.") + end + local previousFile, previousName, previousSubPath = build.dbFileName, build.buildName, build.dbFileSubPath if args.name then local name = T.Sanitise(args.name):gsub("[\\/:%*%?\"<>|%c]", "-") if not name:match("%S") then @@ -369,8 +400,12 @@ T.Tool { elseif not build.dbFileName then T.Fail("This build has no file yet (it was opened from a code, a link or as new). Give a name to save it.") end + -- A save started here never carries out an action the user chose in a dialog. + build.actionOnSave = nil if build:SaveDBFile() then - T.Fail("Path of Building could not write %s; check the folder exists and is writable.", build.dbFileName) + local failedFile = build.dbFileName + build.dbFileName, build.buildName, build.dbFileSubPath = previousFile, previousName, previousSubPath + T.Fail("Path of Building could not write %s; check the folder exists and is writable.", failedFile) end build.spec:SetWindowTitleWithBuildClass() return { saved = (build.dbFileSubPath or "") .. build.buildName .. ".xml", build = T.BuildSummary(build) } @@ -488,6 +523,7 @@ T.Tool { .. "the build's notes (Notes tab). The change shows in the window and marks the build unsaved. Class and ascendancy are " .. "changed with tree_edit; bandit and pantheon are Config options (config_set).", idempotent = true, + destructive = true, modifies = true, input = { level = { type = "integer", minimum = 1, maximum = 100, description = "Character level." }, diff --git a/src/Modules/McpTools/Compare.lua b/src/Modules/McpTools/Compare.lua index efd4cfbd186..e5a158cf892 100644 --- a/src/Modules/McpTools/Compare.lua +++ b/src/Modules/McpTools/Compare.lua @@ -1225,6 +1225,7 @@ T.Tool { .. "build's socket groups listed in socket_groups as new groups, as the Skills tab's copy and paste do (gem name, level, quality, " .. "enabled, count, label and slot; groups granted by items come with the item and are skipped). The build is marked unsaved and " .. "statChanges lists what changed.", + destructive = true, modifies = true, input = { what = { type = "string", enum = { "tree", "item", "config", "skills" }, description = "What to copy." }, @@ -1475,6 +1476,7 @@ T.Tool { .. "Effects'); 'rebuild' parses all the text again ('Rebuild All'); 'export_support' turns the Import/Export tab's 'Export " .. "Support' on or off for the open build, so its own export can be imported into another build's Party tab (the result " .. "lists the sections it exports). Changes mark the build unsaved and statChanges shows their effect.", + destructive = true, modifies = true, openWorld = true, input = { @@ -1507,6 +1509,8 @@ T.Tool { end local link = args.link:gsub("^%s+", ""):gsub("%s+$", "") local site = findLinkSite(link) + -- main.modes.BUILD is reused for every build; its tabs are recreated whenever another build opens. + local openedTree = build.treeTab return T.Defer(function(resolve) buildSites.DownloadBuild(link, site, function(isSuccess, data) if not isSuccess then @@ -1514,7 +1518,7 @@ T.Tool { end T.Settle(resolve, function() local current = T.Build() - if current ~= build then + if current.treeTab ~= openedTree then T.Fail("The open build changed while the download ran; nothing was imported.") end local sections = partyImport(build, T.DecodeBuildCode(data), args) @@ -1746,9 +1750,10 @@ T.Tool { local mode = args.mode or "new_build" local withItems = mode == "new_build" or args.parts ~= "tree" local withTree = mode == "new_build" or args.parts ~= "items_skills" - local target + -- main.modes.BUILD is reused for every build; its tabs are recreated whenever another build opens. + local targetTree if mode == "update" then - target = T.Build() + targetTree = T.Build().treeTab else T.CheckCanReplaceBuild(args) end @@ -1765,7 +1770,7 @@ T.Tool { local build if mode == "update" then build = T.Build() - if build ~= target then + if build.treeTab ~= targetTree then T.Fail("The open build changed while the download ran; nothing was imported.") end local result = importCharacterInto(build, char, realmCode, args, withItems, withTree) diff --git a/src/Modules/McpTools/Config.lua b/src/Modules/McpTools/Config.lua index c44029c6765..96138ccfda4 100644 --- a/src/Modules/McpTools/Config.lua +++ b/src/Modules/McpTools/Config.lua @@ -287,31 +287,36 @@ local function cleanModText(text) return (T.Sanitise(text)) end -local function editCustomMods(configTab, args, result) +-- The existing custom modifier group args.custom_mods_group names (default the first); fails when there is none. +local function findCustomModsGroup(configTab, args) if not configTab.customSection then T.Fail("This version of Path of Building has no custom modifiers section.") end local list = configTab.configSets[configTab.activeConfigSetId].customModsList + local ref = args.custom_mods_group + if ref == nil then + return 1 + elseif type(ref) == "number" then + if not list[ref] then + T.Fail("There is no custom modifier group %d; there are %d.", ref, #list) + end + return ref + end + return isValueInArray(list, T.Find(list, ref, function(block) return block.title or "Default" end, "custom modifier group")) +end + +local function editCustomMods(configTab, args, result) local index if args.new_custom_mods_group then + findCustomModsGroup(configTab, { }) configTab.controls.customModsAddBlock.onClick() index = #configTab.configSets[configTab.activeConfigSetId].customModsList local title = T.Sanitise((args.new_custom_mods_group:gsub("%c", " "))) if title:match("%S") then configTab.customModsBlockControls[index].controls.titleEdit:SetText(title, true) end - elseif args.custom_mods_group ~= nil then - local ref = args.custom_mods_group - if type(ref) == "number" then - if not list[ref] then - T.Fail("There is no custom modifier group %d; there are %d.", ref, #list) - end - index = ref - else - index = isValueInArray(list, T.Find(list, ref, function(block) return block.title or "Default" end, "custom modifier group")) - end else - index = 1 + index = findCustomModsGroup(configTab, args) end local blockControl = configTab.customModsBlockControls[index] local block = configTab.configSets[configTab.activeConfigSetId].customModsList[index] @@ -387,6 +392,11 @@ T.Tool { result.configSetChange = done end + -- Check the custom modifier group before changing any option, so a wrong group changes nothing more. + if (args.custom_mods or args.custom_mods_enabled ~= nil) and not args.new_custom_mods_group then + findCustomModsGroup(configTab, args) + end + local applied, rejected = { }, { } local function reject(key, reason, option) local entry = { option = tostring(key), reason = reason } diff --git a/src/Modules/McpTools/Tree.lua b/src/Modules/McpTools/Tree.lua index 37c3293e514..267b11112fd 100644 --- a/src/Modules/McpTools/Tree.lua +++ b/src/Modules/McpTools/Tree.lua @@ -480,6 +480,7 @@ T.Tool { .. "every request that failed (unreachable, unknown, mastery effect taken elsewhere) without stopping the others. Measure " .. "first with simulate; changes are unsaved until build_save.", idempotent = true, + destructive = true, modifies = true, input = { class = { type = "string", description = "Change the class, for example 'Witch'. Keeps the tree when it reaches the new class's start; otherwise needs reset_tree." }, @@ -1393,6 +1394,7 @@ T.Tool { .. "are given by id or name as listed; include_legacy also lists legacy tattoos. Results include PoB's tattoo count: the game " .. "allows at most 50 tattoos, which PoB counts but does not enforce. simulate cannot preview tattoos; after apply or reset, " .. "statChanges lists what changed. Changes are unsaved until build_save.", + destructive = true, modifies = true, usesDialog = true, input = { From a8f1d16dc78c95453efe5f7c7128d9cf60568749 Mon Sep 17 00:00:00 2001 From: Filipe Cavalcante <filipecavalc@gmail.com> Date: Mon, 16 Nov 2026 17:14:25 -0300 Subject: [PATCH 5/7] items_craft: explain when Exarch and Eater implicits need the influence first --- spec/System/TestMcpItems_spec.lua | 10 ++++++++++ src/Modules/McpTools/Items.lua | 18 ++++++++++++++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/spec/System/TestMcpItems_spec.lua b/spec/System/TestMcpItems_spec.lua index fac762b2b5d..dbfa5095523 100644 --- a/spec/System/TestMcpItems_spec.lua +++ b/spec/System/TestMcpItems_spec.lua @@ -259,6 +259,16 @@ describe("MCP items tools", function() local custom = callTool("items_craft", { action = "modifier", item = withLife.item, custom = "+10% to Cold Resistance" }) assert.is_truthy(table.concat(custom.mods, "\n"):find("+10% to Cold Resistance", 1, true)) + -- Exarch and Eater implicits need the influence first, as in AddImplicitPopup. + local noInfluence = callTool("items_craft", { action = "implicit", item = custom.item }) + assert.are.same({ "Custom" }, noInfluence.sources) + assert.is_truthy(noInfluence.note:find("Searing Exarch and Eater of Worlds implicits are offered only once", 1, true)) + local exarchItem = callTool("items_craft", { action = "properties", item = custom.item, influences = { "Searing Exarch" } }) + local exarch = callTool("items_craft", { action = "implicit", item = exarchItem.item }) + assert.are.same({ "Searing Exarch", "Custom" }, exarch.sources) + assert.is_truthy(#exarch.options > 0) + assert.is_truthy(exarch.note:find("Eater of Worlds implicits are offered only once", 1, true)) + local quality = callTool("items_craft", { action = "properties", item = custom.item, quality = 20, influences = { "Shaper" } }) assert.is_truthy(quality.item:find("Shaper Item", 1, true)) assert.is_truthy(quality.item:find("Quality: 20", 1, true)) diff --git a/src/Modules/McpTools/Items.lua b/src/Modules/McpTools/Items.lua index 43a1415008e..8899ccf3fbd 100644 --- a/src/Modules/McpTools/Items.lua +++ b/src/Modules/McpTools/Items.lua @@ -1009,9 +1009,23 @@ function craftActions.implicit(itemsTab, args, build) for _, entry in ipairs(sources) do t_insert(sourceLabels, entry.label) end + -- AddImplicitPopup offers Searing Exarch and Eater of Worlds implicits only on + -- non-unique helmets, body armours, gloves and boots that have that influence. + local item = itemsTab.displayItem + local missing = { } + if item.rarity ~= "UNIQUE" and item.rarity ~= "RELIC" + and (item.type == "Helmet" or item.type == "Body Armour" or item.type == "Gloves" or item.type == "Boots") then + if not item.cleansing then + t_insert(missing, "Searing Exarch") + end + if not item.tangle then + t_insert(missing, "Eater of Worlds") + end + end + local influenceHint = #missing > 0 and s_format(" %s implicits are offered only once the item has that influence: add it first with action 'properties' and influences.", table.concat(missing, " and ")) or "" if source.sourceId == "CUSTOM" then if not args.custom then - return { sources = sourceLabels, source = source.label, note = "Pass custom with the implicit line to add." } + return { sources = sourceLabels, source = source.label, note = "Pass custom with the implicit line to add." .. influenceHint } end p.custom:SetText((T.Sanitise(args.custom))) p.save.onClick() @@ -1022,7 +1036,7 @@ function craftActions.implicit(itemsTab, args, build) local listing = listOptions(p.modGroupSelect.list, args) listing.sources = sourceLabels listing.source = source.label - listing.note = "These are implicit types: pass one as group" .. (p.modSelect:GetProperty("shown") and ", then a modifier of that type." or ".") + listing.note = "These are implicit types: pass one as group" .. (p.modSelect:GetProperty("shown") and ", then a modifier of that type." or ".") .. influenceHint return listing end choose(p.modGroupSelect, pick(p.modGroupSelect.list, args.group, "implicit type")) From ee242679b4596222a13b8f044d3ed35f1f07c254 Mon Sep 17 00:00:00 2001 From: Filipe Cavalcante <filipecavalc@gmail.com> Date: Mon, 16 Nov 2026 18:11:54 -0300 Subject: [PATCH 6/7] Add trade_search: run the trader's search and measure listings on the build Also offer the trader's Megalomaniac, Watcher's Eye and Pearl of Tsoatha rows and its enchant/anoint behaviour, and split the trader's evaluation, sorting, result preparation and listing link out of its row code so they can be reused. --- docs/mcp.md | 9 +- spec/System/TestMcpTrade_spec.lua | 212 +++++++++++ src/Classes/TradeQuery.lua | 221 +++++++---- src/Modules/McpTools.lua | 8 +- src/Modules/McpTools/Items.lua | 226 +---------- src/Modules/McpTools/Trade.lua | 608 ++++++++++++++++++++++++++++++ 6 files changed, 972 insertions(+), 312 deletions(-) create mode 100644 spec/System/TestMcpTrade_spec.lua create mode 100644 src/Modules/McpTools/Trade.lua diff --git a/docs/mcp.md b/docs/mcp.md index 8b0807289cd..7e1c572c220 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -43,8 +43,10 @@ so you can see what a client did. existing file unless told to. - Tools that use one of Path of Building's dialogs to do their work (timeless jewel finder, tattoos, crafting) close it and put back what they changed in it. -- `import_character` uses the Path of Exile login you set up in *Import/Export*; the token never leaves Path of Building. - Build links are downloaded by Path of Building itself. Nothing is uploaded. +- `import_character` and `trade_search` use the Path of Exile login you set up in *Import/Export*; the token never leaves + Path of Building. `trade_search` runs the trader's searches through Path of Building's own request queue and rate limits + and only reads listings: nothing is bought or sent to sellers. Build links are downloaded by Path of Building itself. + Nothing is uploaded. ## Tools @@ -73,7 +75,8 @@ Tools are grouped by the part of the window they work on. Read-only tools are ma | | `items_sets` | Item sets: list, select, new, copy, rename, delete | | | `items_db_search` | PoB's unique and rare databases, sortable by a stat | | | `items_craft` | Build an item with PoB's crafting and return its text | -| | `trade_query` | The weighted trade search PoB generates for a slot | +| Trade | `trade_query` | The weighted trade search PoB's trader generates for a slot or unique row, as a link | +| | `trade_search` | Runs that search (or a trade link) and returns listings with prices, measured on the build | | Skills | `skills_get` | Socket groups, gems, main skill, skill sets | | | `skills_edit` | Add or change gems and groups, main skill, skill sets | | | `skills_rank_supports` | Support gems ranked by damage for a group | diff --git a/spec/System/TestMcpTrade_spec.lua b/spec/System/TestMcpTrade_spec.lua new file mode 100644 index 00000000000..46e30e69c13 --- /dev/null +++ b/spec/System/TestMcpTrade_spec.lua @@ -0,0 +1,212 @@ +local McpProtocol = LoadModule("Modules/McpProtocol") +local dkjson = require("dkjson") + +local PORT = 49290 +local TOKEN = "0123456789abcdef0123456789abcdef" + +local protocol + +local function frameFuncKeys() + local keys = { } + for key in pairs(main.onFrameFuncs) do + if key:match("^McpTradeSearch") then + table.insert(keys, key) + end + end + return keys +end + +-- Calls a tool, running its trade search frames until it answers. +local function callTool(name, args, allowError) + local response + protocol:HandleHttp({ + method = "POST", + path = "/mcp", + version = "1.1", + headers = { + host = "127.0.0.1:" .. PORT, + authorization = "Bearer " .. TOKEN, + ["content-type"] = "application/json", + }, + body = McpProtocol.Encode({ jsonrpc = "2.0", id = 1, method = "tools/call", params = { name = name, arguments = args or McpProtocol.Object() } }), + }, function(r) + response = r + end) + for _ = 1, 50 do + if response then + break + end + for _, key in ipairs(frameFuncKeys()) do + main.onFrameFuncs[key]() + end + end + assert.is_truthy(response, "no response") + assert.are.equals(200, response.status) + local body = McpProtocol.Decode(response.body) + assert.is_nil(body.error) + if body.result.isError and not allowError then + error(name .. " failed: " .. tostring(body.result.content[1].text), 2) + end + return body.result.structuredContent, body.result +end + +local function toolError(name, args) + local _, result = callTool(name, args, true) + assert.is_true(result.isError, "expected an error from " .. name) + return result.content[1].text +end + +local HELMET = "Rarity: RARE\nTest Hat\nIron Hat\nQuality: 0\n+80 to maximum Life\n" + +-- A listing as the trade site's fetch API returns it. +local function listing(id, name, typeLine, mods, amount, currency, priceType, whisper) + return { + id = id, + item = { rarity = "Rare", name = name, typeLine = typeLine, ilvl = 80, explicitMods = { { description = mods[1] } }, pseudoMods = { "Sum: 42" } }, + listing = { price = { amount = amount, currency = currency, type = priceType }, whisper = whisper, account = { name = "seller" .. id } }, + } +end + +describe("MCP trade tools", function() + local api, savedToken, savedDownload, requests + + before_each(function() + main.mcpServer.token = TOKEN + protocol = main.mcpServer:NewProtocol(PORT) + build.abortSave = true + while main.popups[1] do + main:ClosePopup() + end + newBuild() + api = main.api + savedToken = api.authToken + savedDownload = launch.DownloadPage + requests = { } + local listings = { + listing("a", "Fine Hat", "Iron Hat", { "+90 to maximum Life" }, 2, "divine", "~price", "@seller hi"), + listing("b", "Weak Hat", "Iron Hat", { "+50 to maximum Life" }, 1, "chaos", "~b/o"), + listing("c", "Wrong Boots", "Rawhide Boots", { "+99 to maximum Life" }, 1, "chaos", "~b/o"), + } + -- The trade site: a search, then one fetch; the currency rates are not available. + launch.DownloadPage = function(_, url, callback, params) + table.insert(requests, { url = url, params = params }) + if url:find("api/trade/search/", 1, true) then + callback({ header = "HTTP/1.1 200 OK", body = dkjson.encode({ id = "query1", total = 10, result = { "a", "b", "c" } }) }) + elseif url:find("api/trade/fetch/", 1, true) then + callback({ header = "HTTP/1.1 200 OK", body = dkjson.encode({ result = listings }) }) + else + callback(nil, "offline") + end + end + end) + + after_each(function() + api.authToken = savedToken + launch.DownloadPage = savedDownload + build.abortSave = true + local popup = main.popups[1] + while main.popups[1] do + main:ClosePopup() + end + assert.is_nil(popup, popup and ("dialog left open: " .. tostring(popup.title))) + end) + + it("needs Path of Building's Path of Exile login", function() + api.authToken = nil + local message = toolError("trade_search", { slot = "Helmet", league = "Standard" }) + assert.is_truthy(message:find("not logged in", 1, true)) + assert.are.equals(0, #requests) + end) + + it("searches as the trader does and measures every listing on the build", function() + api.authToken = "test-token" + callTool("items_equip", { action = "equip", slot = "Helmet", item = HELMET }) + build:ResetModFlags() + local result = callTool("trade_search", { slot = "Helmet", league = "Standard", pages = 1, weights = { { stat = "Life", weight = 1 } } }) + + local search = requests[1] + for _, request in ipairs(requests) do + if request.url:find("api/trade/search/", 1, true) then + search = request + end + end + assert.are.equals("https://www.pathofexile.com/api/trade/search/Standard", search.url) + local sent = dkjson.decode(search.params.body) + assert.are.same({ ["statgroup.0"] = "desc" }, sent.sort) + assert.are.equals("weight", sent.query.stats[1].type) + assert.is_truthy(search.params.header:find("Bearer test-token", 1, true)) + + -- The boots do not fit the slot; the better helmet comes first. + assert.are.equals(2, result.found) + assert.are.equals("Fine Hat, Iron Hat", result.listings[1].name) + assert.are.equals("Weak Hat, Iron Hat", result.listings[2].name) + assert.is_true(result.listings[1].statValue > result.listings[2].statValue) + assert.are.same({ amount = 2, currency = "divine", type = "~price" }, result.listings[1].price) + assert.are.equals("@seller hi", result.listings[1].whisper) + assert.is_truthy(result.listings[2].listingUrl:find("^https://www%.pathofexile%.com/trade/search/Standard/")) + assert.is_truthy(table.concat(result.listings[1].changes, "\n"):find("Life", 1, true)) + assert.is_truthy(result.listings[1].item:find("+90 to maximum Life", 1, true)) + assert.are.equals("https://www.pathofexile.com/trade/search/Standard/query1", result.searchUrl) + assert.are.equals("stat_value", result.sortedBy) + + -- Nothing changed in the build, and the search left nothing running. + assert.is_false(build.modFlag) + assert.are.same({ }, frameFuncKeys()) + + -- Without currency rates the price sort falls back to stat value, as the trader does. + result = callTool("trade_search", { slot = "Helmet", league = "Standard", pages = 1, sort_by = "price" }) + assert.are.equals("stat_value", result.sortedBy) + assert.is_truthy(result.notes[1]:find("Currency rates", 1, true)) + end) + + it("reports a search that finds nothing, and rejects links from elsewhere", function() + api.authToken = "test-token" + launch.DownloadPage = function(_, url, callback) + if url:find("api/trade/search/", 1, true) then + callback({ header = "HTTP/1.1 200 OK", body = dkjson.encode({ id = "none", total = 0, result = { } }) }) + else + callback(nil, "offline") + end + end + callTool("items_equip", { action = "equip", slot = "Helmet", item = HELMET }) + local message = toolError("trade_search", { slot = "Helmet", league = "Standard", max_price = 1 }) + assert.is_truthy(message:find("no listings", 1, true)) + assert.are.same({ }, frameFuncKeys()) + message = toolError("trade_search", { slot = "Helmet", url = "https://example.com/trade/search/Standard/abc" }) + assert.is_truthy(message:find("trade search link", 1, true)) + end) + + it("generates searches for the trader's unique rows", function() + -- The unique jewels need an allocated jewel socket, as in the trader. + local message = toolError("trade_query", { slot = "Megalomaniac" }) + assert.is_truthy(message:find("jewel socket", 1, true)) + local nearest + for _, node in pairs(build.spec.nodes) do + if node.type == "Socket" and not node.containJewelSocket and not node.expansionJewel and node.path + and (not nearest or #node.path < #nearest.path) then + nearest = node + end + end + build.spec:AllocNode(nearest) + build.buildFlag = true + runCallback("OnFrame") + build.itemsTab:UpdateSockets() + local socketLabel = build.itemsTab.sockets[nearest.id].label + + local result = callTool("trade_query", { slot = "Megalomaniac", league = "Standard" }) + assert.are.equals("Megalomaniac", result.slot) + assert.are.equals(socketLabel, result.measuredIn) + assert.are.equals("Megalomaniac", result.query.name) + assert.is_truthy(#result.weightedStats > 0) + message = toolError("trade_query", { slot = "Megalomaniac", jewel_socket = "No Such Socket" }) + assert.is_truthy(message:find("jewel socket", 1, true)) + + -- A Pearl's supports count only for gems in the ring, so PoB has nothing to weight here. + message = toolError("trade_query", { slot = "Pearl of Tsoatha", ring_slot = "Ring 2" }) + assert.is_truthy(message:find("found no mods", 1, true)) + message = toolError("trade_query", { slot = "Pearl of Tsoatha", ring_slot = "Ring 3" }) + assert.is_truthy(message:find("ring slot", 1, true)) + message = toolError("trade_query", { slot = "Helmet", ring_slot = "Ring 1" }) + assert.is_truthy(message:find("unique rows", 1, true)) + end) +end) diff --git a/src/Classes/TradeQuery.lua b/src/Classes/TradeQuery.lua index 1d0efbbeb80..9a590742eb8 100644 --- a/src/Classes/TradeQuery.lua +++ b/src/Classes/TradeQuery.lua @@ -57,6 +57,12 @@ function TradeQueryClass:TradeQuery(itemsTab) ["Xbox"] = "xbox", ["Sony"] = "sony" } + self.sortModes = { + StatValue = "(Highest) Stat Value", + StatValuePrice = "Stat Value / Price", + Price = "(Lowest) Price", + Weight = "(Highest) Weighted Sum", + } --- @type integer? self.backoffFinish = nil -- last query for each row @@ -109,9 +115,12 @@ end --- @param currencyId string --- @param amount integer +--- @param realm string? defaults to the realm selected in the trader +--- @param league string? defaults to the league selected in the trader --- @return number? -function TradeQueryClass:ConvertCurrencyToDivs(currencyId, amount) - local map = self.pbCurrencyConversion[self.pbRealm] and self.pbCurrencyConversion[self.pbRealm][self.pbLeague] +function TradeQueryClass:ConvertCurrencyToDivs(currencyId, amount, realm, league) + realm, league = realm or self.pbRealm, league or self.pbLeague + local map = self.pbCurrencyConversion[realm] and self.pbCurrencyConversion[realm][league] if map and map[currencyId] then return amount * map[currencyId] end @@ -123,8 +132,9 @@ local generalCurrencies = { } -- Method to pull down and interpret the Currency Exchange JSON endpoint data -function TradeQueryClass:PullCXData() - local realm = self.pbRealm +--- @param realm string? defaults to the realm selected in the trader +function TradeQueryClass:PullCXData(realm) + realm = realm or self.pbRealm if realm == "" then return end @@ -430,12 +440,6 @@ on trade site to work on other leagues and realms)]] tooltip:AddLine(16, s_format("%s: %.2f", stat.label, stat.weightMult)) end end - self.sortModes = { - StatValue = "(Highest) Stat Value", - StatValuePrice = "Stat Value / Price", - Price = "(Lowest) Price", - Weight = "(Highest) Weighted Sum", - } -- Item sort dropdown self.itemSortSelectionList = { self.sortModes.StatValue, @@ -796,6 +800,10 @@ end -- Method to set the notice message in upper right of PoB Trader pane function TradeQueryClass:SetNotice(notice_control, msg) + -- The pane's controls exist only once the trader has been opened. + if not notice_control then + return + end if msg:find("No Matching Results") then msg = colorCodes.WARNING .. msg elseif msg:find("Error") then @@ -805,9 +813,10 @@ function TradeQueryClass:SetNotice(notice_control, msg) end -- Method to reduce the full output to only the values that were 'weighted' -function TradeQueryClass:ReduceOutput(output) +--- @param statWeights table? defaults to the trader's search weights +function TradeQueryClass:ReduceOutput(output, statWeights) local smallOutput = {} - for _, statTable in ipairs(self.statSortSelectionList) do + for _, statTable in ipairs(statWeights or self.statSortSelectionList) do smallOutput[statTable.stat] = data.powerStatList.GetFromOutput(output, statTable, true) if statTable.stat == "FullDPS" and not output.FullDPS then smallOutput.TotalDPS = data.powerStatList.GetFromOutput(output, { stat = "TotalDPS" }) @@ -837,47 +846,67 @@ function TradeQueryClass:GetResultEvaluation(row_idx, result_index, calcFunc, ba self.onlyWeightedBaseOutput[row_idx][result_index] = onlyWeightedBaseOutput self.lastComparedWeightList[row_idx][result_index] = self.statSortSelectionList end - local slotTbl = self.slotTables[row_idx] + result.evaluation = self:EvaluateItem(self.slotTables[row_idx], result.item_string, calcFunc, baseOutput) + return result.evaluation +end + +-- Method to get the slot a row's items are evaluated in +--- @param slotTbl TradeQuerySlotTable +--- @return string +function TradeQueryClass:GetEvaluationSlotName(slotTbl) local jewelNodeId = slotTbl.nodeId or slotTbl.selectedJewelNodeId + if slotTbl.slotName == "Pearl of Tsoatha" and not slotTbl.selectedSlotName then + for index = 1, 3 do + local ringSlot = self.itemsTab.slots["Ring " .. index] + if ringSlot and ringSlot.shown() then + slotTbl.selectedSlotName = ringSlot.slotName + break + end + end + end + return jewelNodeId and "Jewel " .. tostring(jewelNodeId) or slotTbl.selectedSlotName or slotTbl.slotName +end + +-- Method to evaluate an item for a row: its weighted output and weight +--- @param slotTbl TradeQuerySlotTable +--- @param itemString string +--- @param statWeights table? defaults to the trader's search weights +function TradeQueryClass:EvaluateItem(slotTbl, itemString, calcFunc, baseOutput, statWeights) + statWeights = statWeights or self.statSortSelectionList + -- A static function of the generator class, which may not be loaded yet. + if not common.classes.TradeQueryGenerator then + LoadModule("Classes/TradeQueryGenerator") + end + local WeightedRatioOutputs = common.classes.TradeQueryGenerator.WeightedRatioOutputs if slotTbl.slotName == "Megalomaniac" then local addedNodes = {} - for nodeName in (result.item_string.."\r\n"):gmatch("1 Added Passive Skill is (.-)\r?\n") do + for nodeName in (itemString.."\r\n"):gmatch("1 Added Passive Skill is (.-)\r?\n") do t_insert(addedNodes, self.itemsTab.build.spec.tree.clusterNodeMap[nodeName]) end - local output12 = self:ReduceOutput(calcFunc({ addNodes = { [addedNodes[1]] = true, [addedNodes[2]] = true } })) - local output13 = self:ReduceOutput(calcFunc({ addNodes = { [addedNodes[1]] = true, [addedNodes[3]] = true } })) - local output23 = self:ReduceOutput(calcFunc({ addNodes = { [addedNodes[2]] = true, [addedNodes[3]] = true } })) - local output123 = self:ReduceOutput(calcFunc({ addNodes = { [addedNodes[1]] = true, [addedNodes[2]] = true, [addedNodes[3]] = true } })) + local output12 = self:ReduceOutput(calcFunc({ addNodes = { [addedNodes[1]] = true, [addedNodes[2]] = true } }), statWeights) + local output13 = self:ReduceOutput(calcFunc({ addNodes = { [addedNodes[1]] = true, [addedNodes[3]] = true } }), statWeights) + local output23 = self:ReduceOutput(calcFunc({ addNodes = { [addedNodes[2]] = true, [addedNodes[3]] = true } }), statWeights) + local output123 = self:ReduceOutput(calcFunc({ addNodes = { [addedNodes[1]] = true, [addedNodes[2]] = true, [addedNodes[3]] = true } }), statWeights) -- Sometimes the third node is as powerful as a wet noodle, so use weight per point spent, including the jewel socket - local weight12 = self.tradeQueryGenerator.WeightedRatioOutputs(baseOutput, output12, self.statSortSelectionList) / 4 - local weight13 = self.tradeQueryGenerator.WeightedRatioOutputs(baseOutput, output13, self.statSortSelectionList) / 4 - local weight23 = self.tradeQueryGenerator.WeightedRatioOutputs(baseOutput, output23, self.statSortSelectionList) / 4 - local weight123 = self.tradeQueryGenerator.WeightedRatioOutputs(baseOutput, output123, self.statSortSelectionList) / 5 - result.evaluation = { + local weight12 = WeightedRatioOutputs(baseOutput, output12, statWeights) / 4 + local weight13 = WeightedRatioOutputs(baseOutput, output13, statWeights) / 4 + local weight23 = WeightedRatioOutputs(baseOutput, output23, statWeights) / 4 + local weight123 = WeightedRatioOutputs(baseOutput, output123, statWeights) / 5 + local evaluation = { { output = output12, weight = weight12, DNs = { addedNodes[1].dn, addedNodes[2].dn } }, { output = output13, weight = weight13, DNs = { addedNodes[1].dn, addedNodes[3].dn } }, { output = output23, weight = weight23, DNs = { addedNodes[2].dn, addedNodes[3].dn } }, { output = output123, weight = weight123, DNs = { addedNodes[1].dn, addedNodes[2].dn, addedNodes[3].dn } }, } - table.sort(result.evaluation, function(a, b) return a.weight > b.weight end) - else - if slotTbl.slotName == "Pearl of Tsoatha" and not slotTbl.selectedSlotName then - for index = 1, 3 do - local ringSlot = self.itemsTab.slots["Ring " .. index] - if ringSlot and ringSlot.shown() then - slotTbl.selectedSlotName = ringSlot.slotName - break - end - end - end - local slotName = jewelNodeId and "Jewel " .. tostring(jewelNodeId) or slotTbl.selectedSlotName or slotTbl.slotName - local item = new("Item"):Item(result.item_string) - - local output = self:ReduceOutput(calcFunc({ repSlotName = slotName, repItem = item })) - local weight = self.tradeQueryGenerator.WeightedRatioOutputs(baseOutput, output, self.statSortSelectionList) - result.evaluation = {{ output = output, weight = weight }} + table.sort(evaluation, function(a, b) return a.weight > b.weight end) + return evaluation end - return result.evaluation + local slotName = self:GetEvaluationSlotName(slotTbl) + local item = new("Item"):Item(itemString) + + local output = self:ReduceOutput(calcFunc({ repSlotName = slotName, repItem = item }), statWeights) + local weight = WeightedRatioOutputs(baseOutput, output, statWeights) + return {{ output = output, weight = weight }} end -- Method to update controls after a search is completed @@ -959,13 +988,22 @@ function TradeQueryClass:SortFetchResults(row_idx, mode) end return sum end + return self:SortResults(self.resultTbl[row_idx], mode, getResultWeight) +end + +-- Method to sort search results by a sort mode +--- @param results table the fetched results +--- @param getResultWeight fun(result_index: integer): number +--- @param realm string? for currency conversion, defaults to the realm selected in the trader +--- @param league string? for currency conversion, defaults to the league selected in the trader +function TradeQueryClass:SortResults(results, mode, getResultWeight, realm, league) --- @return table<integer, number>? local function getPriceTable() --- @type table<integer, number> local divPrices = {} - for idx, item in ipairs(self.resultTbl[row_idx]) do + for idx, item in ipairs(results) do if item.currency and item.amount then - local divs = self:ConvertCurrencyToDivs(item.currency, item.amount) + local divs = self:ConvertCurrencyToDivs(item.currency, item.amount, realm, league) if not divs then return nil end @@ -976,12 +1014,12 @@ function TradeQueryClass:SortFetchResults(row_idx, mode) end local newTbl = {} if mode == self.sortModes.Weight then - for index, _ in pairs(self.resultTbl[row_idx]) do + for index, _ in pairs(results) do t_insert(newTbl, { outputAttr = index, index = index }) end return newTbl elseif mode == self.sortModes.StatValue then - for result_index = 1, #self.resultTbl[row_idx] do + for result_index = 1, #results do t_insert(newTbl, { outputAttr = getResultWeight(result_index), index = result_index }) end table.sort(newTbl, function(a,b) return a.outputAttr > b.outputAttr end) @@ -990,7 +1028,7 @@ function TradeQueryClass:SortFetchResults(row_idx, mode) if priceTable == nil then return nil, "MissingConversionRates" end - for result_index = 1, #self.resultTbl[row_idx] do + for result_index = 1, #results do -- generally, because we are filtering our results to only the top -- contenders, we will end up with a small spread of result weights. -- this is however not true for prices as *decent* items might start @@ -1036,6 +1074,59 @@ function TradeQueryClass:FilterToSafeItems(itemEntries, slotName) end return itemsSafe end + +-- Method to build a trade site link that shows one listing of a search's results +---@param lastQuery string the search's query JSON, as sent +---@param itemResult table the fetched result +---@param realm string? defaults to the realm selected in the trader +---@param league string? defaults to the league selected in the trader +function TradeQueryClass:BuildListingSearchUrl(lastQuery, itemResult, realm, league) + local exactQuery = dkjson.decode(lastQuery) + -- use trade sum to get the specific item. both min and max + -- weight on site uses floats but only shows integer in the api + -- e.g. weight of 172.3 shows up as 172 in the api + if exactQuery.query.stats[1].type == "weight" then + exactQuery.query.stats[1].value = { min = floor(itemResult.weight, 1) - 1, max = round(itemResult.weight, 1) + 1 } + end + -- also apply trader name. this should make false positives + -- extremely unlikely. this doesn't seem to take up a filter slot + exactQuery.query.filters = exactQuery.query.filters or { } + exactQuery.query.filters.trade_filters = exactQuery.query.filters.trade_filters or { filters = { } } + exactQuery.query.filters.trade_filters.filters = exactQuery.query.filters.trade_filters.filters or { } + exactQuery.query.filters.trade_filters.filters.account = { input = itemResult.trader } + + return self.tradeQueryRequests:buildUrl(self.hostName .. "trade/search", realm or self.pbRealm, league or self.pbLeague, + tradeHelpers.B64GzipEncode(dkjson.encode(exactQuery.query))) +end + +-- Method to prepare the results of a generated search: drop items that do not +-- parse or fit, and apply the query options' eldritch and enchant choices +---@param items table the fetched results +---@param filterSlotName string? the slot the items must fit +---@param slotName string the row's slot, whose anoints and eldritch implicits are copied +---@param includeEldritch string? the Eldritch Mods choice +---@param copyEnchantMode string? the Enchant/Anoint Behaviour choice +function TradeQueryClass:PrepareGeneratedResults(items, filterSlotName, slotName, includeEldritch, copyEnchantMode) + local itemsSafe = self:FilterToSafeItems(items, filterSlotName) + -- replace eldritch mods or enchants if the user requested + -- so in TradeQueryGenerator + for i, _ in ipairs(itemsSafe) do + local item = new("Item"):Item(itemsSafe[i].item_string) + -- assume the user will add quality if they buy the item + item:NormaliseQuality() + if includeEldritch == "Copy Current" or copyEnchantMode == "Copy Current" then + self.itemsTab:CopyAnointsAndEldritchImplicits(item, true, true, slotName) + elseif includeEldritch == "Remove" then + if item.tangle or item.cleansing then + item.implicitModLines = {} + end + elseif copyEnchantMode == "Remove" then + item.enchantModLines = {} + end + itemsSafe[i].item_string = item:BuildRaw() + end + return itemsSafe +end -- Method to generate pane elements for each item slot function TradeQueryClass:PriceItemRowDisplay(row_idx, top_pane_alignment_ref, row_vertical_padding, row_height) local controls = self.controls @@ -1086,25 +1177,8 @@ function TradeQueryClass:PriceItemRowDisplay(row_idx, top_pane_alignment_ref, ro self.lastQueries[row_idx] = finalQuery local selectedSlot = getSelectedSlot() - local itemsSafe = self:FilterToSafeItems(items, selectedSlot and selectedSlot.slotName) - -- replace eldritch mods or enchants if the user requested - -- so in TradeQueryGenerator - for i, _ in ipairs(itemsSafe) do - local item = new("Item"):Item(itemsSafe[i].item_string) - -- assume the user will add quality if they buy the item - item:NormaliseQuality() - if self.tradeQueryGenerator.lastIncludeEldritch == "Copy Current" or - self.tradeQueryGenerator.lastCopyEnchantMode == "Copy Current" then - self.itemsTab:CopyAnointsAndEldritchImplicits(item, true, true, context.slotTbl.slotName) - elseif self.tradeQueryGenerator.lastIncludeEldritch == "Remove" then - if item.tangle or item.cleansing then - item.implicitModLines = {} - end - elseif self.tradeQueryGenerator.lastCopyEnchantMode == "Remove" then - item.enchantModLines = {} - end - itemsSafe[i].item_string = item:BuildRaw() - end + local itemsSafe = self:PrepareGeneratedResults(items, selectedSlot and selectedSlot.slotName, context.slotTbl.slotName, + self.tradeQueryGenerator.lastIncludeEldritch, self.tradeQueryGenerator.lastCopyEnchantMode) self.resultTbl[context.row_idx] = itemsSafe self:UpdateControlsWithItems(context.row_idx) @@ -1305,22 +1379,7 @@ you can add them, copy the link here, and press "Price Item" to evaluate the ite if itemResult.whisper and (itemResult.priceType ~= "~b/o") then Copy(itemResult.whisper) else - local exactQuery = dkjson.decode(self.lastQueries[row_idx]) - -- use trade sum to get the specific item. both min and max - -- weight on site uses floats but only shows integer in the api - -- e.g. weight of 172.3 shows up as 172 in the api - if exactQuery.query.stats[1].type == "weight" then - exactQuery.query.stats[1].value = { min = floor(itemResult.weight, 1) - 1, max = round(itemResult.weight, 1) + 1 } - end - -- also apply trader name. this should make false positives - -- extremely unlikely. this doesn't seem to take up a filter slot - exactQuery.query.filters = exactQuery.query.filters or { } - exactQuery.query.filters.trade_filters = exactQuery.query.filters.trade_filters or { filters = { } } - exactQuery.query.filters.trade_filters.filters = exactQuery.query.filters.trade_filters.filters or { } - exactQuery.query.filters.trade_filters.filters.account = { input = itemResult.trader } - - local encodedUrl = self.tradeQueryRequests:buildUrl(self.hostName .. "trade/search", self.pbRealm, self.pbLeague, - tradeHelpers.B64GzipEncode(dkjson.encode(exactQuery.query))) + local encodedUrl = self:BuildListingSearchUrl(self.lastQueries[row_idx], itemResult) Copy(encodedUrl) OpenURL(encodedUrl) diff --git a/src/Modules/McpTools.lua b/src/Modules/McpTools.lua index c06e5f3701e..83abee3621a 100644 --- a/src/Modules/McpTools.lua +++ b/src/Modules/McpTools.lua @@ -526,9 +526,9 @@ local promptDefs = { return "Find the best upgrade for the " .. tostring(args.slot) .. " slot of the build open in Path of Building" .. (args.goal and args.goal ~= "" and (", aiming for " .. args.goal) or "") .. ".\n" .. "1. Read the current item with items_get and the build's needs with build_stats (resistances, attributes, warnings).\n" - .. "2. Find candidates with items_db_search (uniques and PoB's rare templates) and, if useful, items_craft; trade_query gives a weighted trade search the user can open.\n" - .. "3. Measure every candidate with simulate in that slot and rank them by the measured change, mentioning unmet requirements.\n" - .. "4. Only equip one with items_equip if the user asks." + .. "2. Find candidates with items_db_search (uniques and PoB's rare templates) and, if useful, items_craft; trade_search finds listings on the trade site with their prices, already measured on the build (it needs PoB's Path of Exile login; otherwise trade_query gives a link the user can open).\n" + .. "3. Measure every candidate with simulate in that slot and rank them by the measured change, mentioning unmet requirements and prices.\n" + .. "4. Only equip one with items_equip if the user asks; nothing is bought." end, }, { @@ -578,7 +578,7 @@ M.instructions = table.concat({ -- Tool files, one per area of the UI. -- One failing file must not take the others down. -for _, name in ipairs({ "Build", "Tree", "Items", "Skills", "Config", "Calcs", "Compare" }) do +for _, name in ipairs({ "Build", "Tree", "Items", "Trade", "Skills", "Config", "Calcs", "Compare" }) do local ok, err = pcall(LoadModule, "Modules/McpTools/" .. name, T) if not ok then ConPrintf("MCP server: could not load the %s tools: %s", name, tostring(err)) diff --git a/src/Modules/McpTools/Items.lua b/src/Modules/McpTools/Items.lua index 8899ccf3fbd..b4fb2402a5e 100644 --- a/src/Modules/McpTools/Items.lua +++ b/src/Modules/McpTools/Items.lua @@ -2,8 +2,8 @@ -- -- Module: MCP Tools - Items -- The Items tab: equipped items and item sets, the unique and rare template --- databases, crafting with the tab's own controls and dialogs, and the --- weighted trade search of PoB's trader. +-- databases, and crafting with the tab's own controls and dialogs. The +-- trader is in McpTools/Trade.lua. -- local T = ... @@ -13,9 +13,6 @@ local s_format = string.format local m_min = math.min local m_max = math.max -local dkjson = require("dkjson") -local tradeHelpers = require("Classes.TradeHelpers") - ------------------------------------------------------------------------------ -- Shared helpers ------------------------------------------------------------------------------ @@ -1516,222 +1513,3 @@ T.Tool { end) end, } - ------------------------------------------------------------------------------- --- trade_query ------------------------------------------------------------------------------- - --- The trader's listing types, in the order of its dropdown (TradeQuery:PriceItem) --- and of the ids TradeQueryGenerator:FinishQuery sends. -local TRADE_TYPES = { "instant_buyout", "instant_or_in_person", "in_person_online_in_league", "in_person_online", "any" } - --- Currencies of the generator's "Max Price" dropdown (TradeQueryGenerator currencyTable). -local CURRENCIES = { "chaos", "divine", "alch", "alt", "chrome", "exalted", "blessed", "chisel", "gcp", "jewellers", "scour", "regret", "fusing", "chance", "regal", "vaal" } - --- Trade site stat id -> text, from the stat list PoB ships (Data/TradeSiteStats). -local tradeStatText -local function tradeStatLookup() - if not tradeStatText then - tradeStatText = { } - for _, category in ipairs(tradeHelpers.getTradeStats()) do - for _, entry in ipairs(category.entries or { }) do - tradeStatText[entry.id] = entry.text - end - end - end - return tradeStatText -end - --- The weights the trader's "Adjust search weights" dialog offers (TradeQuery:SetStatWeights). -local function statWeights(list) - local weights = { } - for _, want in ipairs(list) do - local found - for _, stat in ipairs(data.powerStatList) do - if not stat.ignoreForItems and stat.label ~= "Name" and stat.stat - and (stat.stat:lower() == want.stat:lower() or stat.label:lower() == want.stat:lower()) then - found = stat - end - end - if not found then - local names = { } - for _, stat in ipairs(data.powerStatList) do - if not stat.ignoreForItems and stat.stat then - t_insert(names, stat.stat) - end - end - T.Fail("Unknown weight stat '%s'. Stats: %s", want.stat, t_concat(names, ", ")) - end - t_insert(weights, { label = found.label, stat = found.stat, transform = found.transform, weightMult = want.weight }) - end - return weights -end - -local function tradeStatFilters(list, what) - if not list then - return nil - end - local stats = tradeStatLookup() - local filters = { } - for _, entry in ipairs(list) do - if not stats[entry.id] then - T.Fail("'%s' in %s is not a trade site stat id PoB knows (for example 'explicit.stat_3299347043' or 'pseudo.pseudo_total_life').", entry.id, what) - end - t_insert(filters, { tradeId = entry.id, value = entry.min }) - end - return filters -end - -local function statFilterList(description) - return { - type = "array", maxItems = 5, description = description, - items = { type = "object", properties = { id = { type = "string" }, min = { type = "number" } }, required = { "id" }, additionalProperties = false }, - } -end - -T.Tool { - name = "trade_query", - title = "Weighted trade search", - description = "Generates the weighted trade search Path of Building's trader ('Trade for these items', 'Find best') builds for " - .. "an equipment slot or jewel socket of the open build: PoB measures every modifier that can appear on that item type with " - .. "the build's calculator, weights each by how much it improves the chosen stats (default: the build's saved trader weights, " - .. "else Full DPS 1.0 and Effective Hit Pool 0.5), and sets the minimum weighted sum to half the current item's value. Returns " - .. "the query JSON for the pathofexile.com trade API, the weighted stats in readable form, and a trade site URL when a league " - .. "is known (pass league, for example 'Standard' or the current challenge league) and compression is available. Nothing is " - .. "sent to the trade site and nothing is bought; it uses only data PoB ships, and takes a few seconds. Options mirror the " - .. "trader's Query Options dialog.", - readOnly = true, - idempotent = true, - usesDialog = true, - input = { - slot = { type = "string", description = "Slot, for example 'Helmet', 'Ring 1', 'Weapon 1', 'Flask 2' or a jewel socket like 'Socket #1'." }, - league = { type = "string", maxLength = 100, description = "Trade league for the URL (default: the league chosen in PoB's trader, if any)." }, - realm = { type = "string", enum = { "pc", "xbox", "sony" }, description = "Trade realm for the URL (default pc)." }, - trade_type = { type = "string", enum = TRADE_TYPES, description = "Listings to search (default: the trader's choice, else instant_buyout)." }, - weights = { - type = "array", maxItems = 20, description = "Stats to weight, for example [{stat:'FullDPS', weight:1}, {stat:'Life', weight:0.5}].", - items = { type = "object", properties = { stat = { type = "string" }, weight = { type = "number", minimum = 0.01, maximum = 1 } }, required = { "stat", "weight" }, additionalProperties = false }, - }, - include_corrupted = { type = "boolean", description = "Weight corruption implicits (default true)." }, - include_mirrored = { type = "boolean", description = "Allow mirrored items (default true)." }, - include_scourge = { type = "boolean", description = "Weight scourge modifiers (default true in Standard and Hardcore, otherwise not offered)." }, - include_talisman = { type = "boolean", description = "Amulet: weight talisman modifiers (default false)." }, - eldritch = { type = "string", enum = { "Copy Current", "Keep regular", "Keep regular+presence", "Remove" }, description = "Helmet, body armour, gloves, boots, amulet: eldritch implicits ('Keep ...' weights them; default Copy Current)." }, - jewel_type = { type = "string", enum = { "Base", "Abyss" }, description = "Jewel sockets: which jewels to search (default Base)." }, - max_price = { type = "integer", minimum = 1, description = "Maximum price." }, - max_price_currency = { type = "string", enum = CURRENCIES, description = "Currency of max_price (default: chaos orb equivalent)." }, - max_level = { type = "integer", minimum = 1, maximum = 100, description = "Maximum level requirement." }, - sockets = { type = "integer", minimum = 1, maximum = 6, description = "Number of empty sockets." }, - links = { type = "integer", minimum = 1, maximum = 6, description = "Number of links." }, - required_stats = statFilterList("Stats the item must have, by trade site stat id (as in weightedStats), with an optional minimum."), - blocked_stats = statFilterList("Stats the item must not have, by trade site stat id."), - }, - required = { "slot" }, - run = function(args) - local build = T.Build() - local itemsTab = build.itemsTab - itemsTab:UpdateSockets() - local slot = T.FindSlot(build, args.slot) - if slot.inactive then - T.Fail("%s is not in use (an unallocated jewel socket or a missing abyssal socket).", slotLabel(slot)) - end - local tradeQuery = itemsTab.tradeQuery - local league = args.league or tradeQuery.pbLeague - local weights - if args.weights then - weights = statWeights(args.weights) - elseif tradeQuery.statSortSelectionList and tradeQuery.statSortSelectionList[1] then - weights = tradeQuery.statSortSelectionList - else - weights = statWeights({ { stat = "FullDPS", weight = 1 }, { stat = "TotalEHP", weight = 0.5 } }) - end - local isJewel = slot.slotName:find("Jewel") ~= nil - local isAbyssal = slot.slotName:find("Abyssal") ~= nil - -- The Query Options dialog's choices and its defaults (TradeQueryGenerator:RequestQuery). - local options = { - statWeights = weights, - includeCorrupted = args.include_corrupted ~= false, - includeMirrored = args.include_mirrored ~= false, - maxPrice = args.max_price, - maxPriceType = args.max_price and args.max_price_currency or nil, - maxLevel = args.max_level, - sockets = args.sockets, - links = args.links, - requiredMods = tradeStatFilters(args.required_stats, "required_stats"), - blockedMods = tradeStatFilters(args.blocked_stats, "blocked_stats"), - } - if not isJewel and not isAbyssal and (league == "Standard" or league == "Hardcore") then - options.includeScourge = args.include_scourge ~= false - end - if slot.slotName == "Amulet" then - options.includeTalisman = args.include_talisman == true - end - if ({ ["Body Armour"] = true, Helmet = true, Gloves = true, Boots = true, Amulet = true })[slot.slotName] then - options.includeEldritch = args.eldritch or "Copy Current" - end - if isAbyssal then - options.jewelType = "Abyss" - elseif isJewel then - options.jewelType = args.jewel_type or "Base" - end - local tradeTypeIndex = args.trade_type and isValueInArray(TRADE_TYPES, args.trade_type) or tradeQuery.tradeTypeIndex or 1 - - -- A generator of our own, so the trader's remembered choices stay as they are. - local generator = new("TradeQueryGenerator"):TradeQueryGenerator(tradeQuery) - local query, message - generator.requesterContext = { } - generator.requesterCallback = function(_, generated, errMsg) - query, message = generated, errMsg - end - generator.tradeTypeIndex = tradeTypeIndex - generator:StartQuery(slot, options) - local co = generator.calcContext.co - if not co then - T.Fail("Path of Building's trader has no weighted search for %s.", slotLabel(slot)) - end - -- The work TradeQueryGenerator:OnFrame spreads over frames, run to the end here. - while coroutine.status(co) ~= "dead" do - local ok, err = coroutine.resume(co, generator) - if not ok then - T.Fail("Path of Building could not weight the modifiers: %s", tostring(err)) - end - end - generator.calcContext.co = nil - generator:FinishQuery() - if message then - T.Fail("%s", message) - end - if not query then - T.Fail("Path of Building generated no trade query.") - end - local stats = tradeStatLookup() - local weighted = { } - for _, filter in ipairs(query.stats[1].filters) do - t_insert(weighted, { id = filter.id, text = stats[filter.id], weight = T.Round(filter.value.weight) }) - end - local usedWeights = { } - for _, weight in ipairs(weights) do - t_insert(usedWeights, { stat = weight.stat, label = weight.label, weight = T.Round(weight.weightMult) }) - end - local result = { - slot = slot.slotName, - category = generator.calcContext.itemCategoryQueryStr, - weights = usedWeights, - minimumWeightedSum = T.Round(query.stats[1].value.min), - weightedStats = T.Array(weighted), - query = query, - } - -- As the trader composes the link when it is not logged in. - local encoded = league and tradeHelpers.B64GzipEncode(dkjson.encode(query)) - if league and encoded and encoded ~= "" then - local realm = args.realm or (tradeQuery.pbRealm ~= "" and tradeQuery.pbRealm) or "pc" - result.url = tradeQuery.tradeQueryRequests:buildUrl(tradeQuery.hostName .. "trade/search", realm, league) .. "/" .. encoded - result.league = league - elseif not league then - result.note = "Pass league to get a trade site link." - else - result.note = "Path of Building could not compress the query into a trade site link here; use the query with the trade site's search API." - end - return result - end, -} diff --git a/src/Modules/McpTools/Trade.lua b/src/Modules/McpTools/Trade.lua new file mode 100644 index 00000000000..270eb38f3f6 --- /dev/null +++ b/src/Modules/McpTools/Trade.lua @@ -0,0 +1,608 @@ +-- Path of Building +-- +-- Module: MCP Tools - Trade +-- The Items tab's trader: the weighted search it generates for a slot ("Find +-- best"), and the search it runs on the trade site with every result measured +-- on the build ("Price Item"). +-- +local T = ... + +local t_insert = table.insert +local t_concat = table.concat +local s_format = string.format + +local dkjson = require("dkjson") +local tradeHelpers = require("Classes.TradeHelpers") + +-- The trader's listing types, in the order of its dropdown (TradeQuery:PriceItem) +-- and of the ids TradeQueryGenerator:FinishQuery sends. +local TRADE_TYPES = { "instant_buyout", "instant_or_in_person", "in_person_online_in_league", "in_person_online", "any" } + +-- Currencies of the generator's "Max Price" dropdown (TradeQueryGenerator currencyTable). +local CURRENCIES = { "chaos", "divine", "alch", "alt", "chrome", "exalted", "blessed", "chisel", "gcp", "jewellers", "scour", "regret", "fusing", "chance", "regal", "vaal" } + +-- The trader's "Other trades" rows (TradeQuery:PriceItem). +local UNIQUE_ROWS = { "Megalomaniac", "Watcher's Eye", "Pearl of Tsoatha" } + +-- Slots whose eldritch implicits the Query Options dialog offers to handle (TradeQueryGenerator eldritchModSlots). +local ELDRITCH_SLOTS = { ["Body Armour"] = true, Helmet = true, Gloves = true, Boots = true, Amulet = true } + +-- The trader's "Sort By" choices (TradeQuery sortModes). +local SORT_MODES = { stat_value = "StatValue", stat_value_per_price = "StatValuePrice", price = "Price", weighted_sum = "Weight" } + +-- Trade site stat id -> text, from the stat list PoB ships (Data/TradeSiteStats). +local tradeStatText +local function tradeStatLookup() + if not tradeStatText then + tradeStatText = { } + for _, category in ipairs(tradeHelpers.getTradeStats()) do + for _, entry in ipairs(category.entries or { }) do + tradeStatText[entry.id] = entry.text + end + end + end + return tradeStatText +end + +-- The weights the trader's "Adjust search weights" dialog offers (TradeQuery:SetStatWeights). +local function statWeights(list) + local weights = { } + for _, want in ipairs(list) do + local found + for _, stat in ipairs(data.powerStatList) do + if not stat.ignoreForItems and stat.label ~= "Name" and stat.stat + and (stat.stat:lower() == want.stat:lower() or stat.label:lower() == want.stat:lower()) then + found = stat + end + end + if not found then + local names = { } + for _, stat in ipairs(data.powerStatList) do + if not stat.ignoreForItems and stat.stat then + t_insert(names, stat.stat) + end + end + T.Fail("Unknown weight stat '%s'. Stats: %s", want.stat, t_concat(names, ", ")) + end + t_insert(weights, { label = found.label, stat = found.stat, transform = found.transform, weightMult = want.weight }) + end + return weights +end + +-- The weights to use: given ones, else the build's saved trader weights, else the trader's defaults. +local function chosenWeights(args, tradeQuery) + if args.weights then + return statWeights(args.weights) + elseif tradeQuery.statSortSelectionList and tradeQuery.statSortSelectionList[1] then + return tradeQuery.statSortSelectionList + end + return statWeights({ { stat = "FullDPS", weight = 1 }, { stat = "TotalEHP", weight = 0.5 } }) +end + +local function tradeStatFilters(list, what) + if not list then + return nil + end + local stats = tradeStatLookup() + local filters = { } + for _, entry in ipairs(list) do + if not stats[entry.id] then + T.Fail("'%s' in %s is not a trade site stat id PoB knows (for example 'explicit.stat_3299347043' or 'pseudo.pseudo_total_life').", entry.id, what) + end + t_insert(filters, { tradeId = entry.id, value = entry.min }) + end + return filters +end + +local function statFilterList(description) + return { + type = "array", maxItems = 5, description = description, + items = { type = "object", properties = { id = { type = "string" }, min = { type = "number" } }, required = { "id" }, additionalProperties = false }, + } +end + +local function slotLabel(slot) + return slot.label or slot.slotName +end + +-- Active jewel sockets that are not cluster jewel sockets, as the trader lists +-- them for its unique jewel rows, and the one it preselects (the lowest node id). +local function uniqueJewelSockets(build) + local itemsTab = build.itemsTab + local list = { } + for nodeId, socket in pairs(itemsTab.sockets) do + if not socket.inactive and not build.spec.nodes[nodeId].containJewelSocket then + t_insert(list, socket) + end + end + table.sort(list, function(a, b) return a.nodeId < b.nodeId end) + return list +end + +-- The trader row for the slot asked for (TradeQuery:PriceItem's slotTables), and +-- the slot the Query Options dialog passes to the generator (RequestQuery). +local function tradeRow(build, args) + local itemsTab = build.itemsTab + itemsTab:UpdateSockets() + local unique + for _, name in ipairs(UNIQUE_ROWS) do + if name:lower() == tostring(args.slot):lower() then + unique = name + end + end + if not unique then + if args.jewel_socket or args.ring_slot then + T.Fail("jewel_socket and ring_slot are for the unique rows: %s.", t_concat(UNIQUE_ROWS, ", ")) + end + local slot = T.FindSlot(build, args.slot) + if slot.inactive then + T.Fail("%s is not in use (an unallocated jewel socket or a missing abyssal socket).", slotLabel(slot)) + end + return { slotName = slot.slotName, nodeId = slot.nodeId }, slot + end + local row = { slotName = unique, unique = true, alreadyCorrupted = unique == "Megalomaniac" or nil } + if unique == "Pearl of Tsoatha" then + if args.jewel_socket then + T.Fail("jewel_socket is for Megalomaniac and Watcher's Eye.") + end + local rings = { } + for index = 1, 3 do + local ring = itemsTab.slots["Ring " .. index] + if ring and ring.shown() then + t_insert(rings, ring) + end + end + local ring = args.ring_slot and T.Find(rings, args.ring_slot, function(candidate) return candidate.slotName end, "ring slot") or rings[1] + row.selectedSlotName = ring.slotName + return row, ring + end + if args.ring_slot then + T.Fail("ring_slot is for Pearl of Tsoatha.") + end + local sockets = uniqueJewelSockets(build) + if not sockets[1] then + T.Fail("%s needs an allocated jewel socket that is not a cluster jewel socket, as in the trader.", unique) + end + local socket = sockets[1] + if args.jewel_socket then + socket = T.Find(sockets, args.jewel_socket, function(candidate) + return candidate.label + end, "jewel socket") + end + row.selectedJewelNodeId = socket.nodeId + return row, socket +end + +local function checkLeague(league) + if league ~= nil and (type(league) ~= "string" or not league:match("^[%w '%-%(%)]+$")) then + T.Fail("league must be a league name, for example 'Standard'.") + end + return league +end + +-- The search PoB's trader generates for a row: the Query Options dialog's +-- choices with its defaults (TradeQueryGenerator:RequestQuery), then the +-- generator's own work, run to the end here. +local function generateQuery(build, args) + local itemsTab = build.itemsTab + local tradeQuery = itemsTab.tradeQuery + local row, slot = tradeRow(build, args) + local league = checkLeague(args.league or tradeQuery.pbLeague) + local weights = chosenWeights(args, tradeQuery) + local isJewel = slot.slotName:find("Jewel") ~= nil + local isAbyssal = slot.slotName:find("Abyssal") ~= nil + local options = { + statWeights = weights, + includeCorrupted = not row.alreadyCorrupted and args.include_corrupted ~= false, + maxPrice = args.max_price, + maxPriceType = args.max_price and args.max_price_currency or nil, + maxLevel = args.max_level, + sockets = args.sockets, + links = args.links, + requiredMods = tradeStatFilters(args.required_stats, "required_stats"), + blockedMods = tradeStatFilters(args.blocked_stats, "blocked_stats"), + } + if row.unique then + options.special = { itemName = row.slotName } + else + -- These unique items cannot be mirrored, so the dialog offers it only for other rows. + options.includeMirrored = args.include_mirrored ~= false + end + if not isJewel and not isAbyssal and (league == "Standard" or league == "Hardcore") then + options.includeScourge = args.include_scourge ~= false + end + if slot.slotName == "Amulet" then + options.includeTalisman = args.include_talisman == true + end + if ELDRITCH_SLOTS[slot.slotName] then + options.includeEldritch = args.eldritch or "Copy Current" + end + if isAbyssal then + options.jewelType = "Abyss" + elseif isJewel and not row.unique then + options.jewelType = args.jewel_type or "Base" + end + if row.slotName == "Watcher's Eye" then + options.includeAllWEMods = args.include_all_watchers_eye_mods == true + end + local copyEnchantMode + if slot.slotName == "Amulet" or slot.slotName == "Belt" or slot.slotName == "Weapon 1" or slot.slotName == "Weapon 2" then + copyEnchantMode = args.enchant_mode or "Keep" + end + local tradeTypeIndex = args.trade_type and isValueInArray(TRADE_TYPES, args.trade_type) or tradeQuery.tradeTypeIndex or 1 + + -- A generator of our own, so the trader's remembered choices stay as they are. + local generator = new("TradeQueryGenerator"):TradeQueryGenerator(tradeQuery) + local query, message + generator.requesterContext = { } + generator.requesterCallback = function(_, generated, errMsg) + query, message = generated, errMsg + end + generator.tradeTypeIndex = tradeTypeIndex + generator:StartQuery(slot, options) + local co = generator.calcContext.co + if not co then + T.Fail("Path of Building's trader has no weighted search for %s.", slotLabel(slot)) + end + -- The work TradeQueryGenerator:OnFrame spreads over frames, run to the end here. + while coroutine.status(co) ~= "dead" do + local ok, err = coroutine.resume(co, generator) + if not ok then + T.Fail("Path of Building could not weight the modifiers: %s", tostring(err)) + end + end + generator.calcContext.co = nil + generator:FinishQuery() + if message then + T.Fail("%s", message) + end + if not query then + T.Fail("Path of Building generated no trade query.") + end + return { + row = row, + slot = slot, + league = league, + weights = weights, + query = query, + includeEldritch = options.includeEldritch, + copyEnchantMode = copyEnchantMode, + generator = generator, + } +end + +local function usedWeights(weights) + local list = { } + for _, weight in ipairs(weights) do + t_insert(list, { stat = weight.stat, label = weight.label, weight = T.Round(weight.weightMult) }) + end + return list +end + +-- Options shared by both tools: those of the trader's Query Options dialog. +local QUERY_INPUT = { + slot = { type = "string", description = "Slot, for example 'Helmet', 'Ring 1', 'Weapon 1', 'Flask 2' or a jewel socket like 'Socket #1', or one of the trader's 'Other trades' rows: 'Megalomaniac', 'Watcher\'s Eye', 'Pearl of Tsoatha'." }, + league = { type = "string", maxLength = 100, description = "Trade league (default: the league chosen in PoB's trader, if any), for example 'Standard'." }, + realm = { type = "string", enum = { "pc", "xbox", "sony" }, description = "Trade realm (default: the trader's, else pc)." }, + trade_type = { type = "string", enum = TRADE_TYPES, description = "Listings to search (default: the trader's choice, else instant_buyout)." }, + weights = { + type = "array", maxItems = 20, description = "Stats to weight, as the trader's 'Adjust search weights', for example [{stat:'FullDPS', weight:1}, {stat:'Life', weight:0.5}] (default: the build's saved trader weights, else Full DPS 1 and Effective Hit Pool 0.5).", + items = { type = "object", properties = { stat = { type = "string" }, weight = { type = "number", minimum = 0.01, maximum = 1 } }, required = { "stat", "weight" }, additionalProperties = false }, + }, + include_corrupted = { type = "boolean", description = "Weight corruption implicits (default true; Megalomaniac always false)." }, + include_mirrored = { type = "boolean", description = "Allow mirrored items (default true; not offered for the unique rows)." }, + include_scourge = { type = "boolean", description = "Weight scourge modifiers (default true in Standard and Hardcore, otherwise not offered)." }, + include_talisman = { type = "boolean", description = "Amulet: weight talisman modifiers (default false)." }, + eldritch = { type = "string", enum = { "Copy Current", "Keep regular", "Keep regular+presence", "Remove" }, description = "Helmet, body armour, gloves, boots, amulet: eldritch implicits ('Keep ...' weights them; default Copy Current)." }, + jewel_type = { type = "string", enum = { "Base", "Abyss" }, description = "Jewel sockets: which jewels to search (default Base)." }, + jewel_socket = { type = "string", description = "Megalomaniac and Watcher's Eye: the jewel socket to measure in, by label (default: the trader's choice, the first allocated non-cluster socket)." }, + ring_slot = { type = "string", enum = { "Ring 1", "Ring 2", "Ring 3" }, description = "Pearl of Tsoatha: the ring slot to measure in (default the first shown)." }, + include_all_watchers_eye_mods = { type = "boolean", description = "Watcher's Eye: also include, at weight 0, mods for the build's auras that could not be weighted (default false)." }, + max_price = { type = "integer", minimum = 1, description = "Maximum price." }, + max_price_currency = { type = "string", enum = CURRENCIES, description = "Currency of max_price (default: chaos orb equivalent)." }, + max_level = { type = "integer", minimum = 1, maximum = 100, description = "Maximum level requirement." }, + sockets = { type = "integer", minimum = 1, maximum = 6, description = "Number of empty sockets." }, + links = { type = "integer", minimum = 1, maximum = 6, description = "Number of links." }, + required_stats = statFilterList("Stats the item must have, by trade site stat id (as in weightedStats), with an optional minimum."), + blocked_stats = statFilterList("Stats the item must not have, by trade site stat id."), +} + +------------------------------------------------------------------------------ +-- trade_query +------------------------------------------------------------------------------ + +T.Tool { + name = "trade_query", + title = "Weighted trade search", + description = "Generates the weighted trade search Path of Building's trader ('Trade for these items', 'Find best') builds for " + .. "an equipment slot, a jewel socket or one of its unique rows (Megalomaniac, Watcher's Eye, Pearl of Tsoatha) of the open " + .. "build: PoB measures every modifier that can appear on that item type with the build's calculator, weights each by how " + .. "much it improves the chosen stats, and sets the minimum weighted sum to half the current item's value. Returns the query " + .. "JSON for the pathofexile.com trade API, the weighted stats in readable form, and a trade site URL when a league is known " + .. "and compression is available. Nothing is sent to the trade site; it uses only data PoB ships, and takes a few seconds. " + .. "Options mirror the trader's Query Options dialog. To run the search and get listings with prices, use trade_search.", + readOnly = true, + idempotent = true, + usesDialog = true, + input = QUERY_INPUT, + required = { "slot" }, + run = function(args) + local build = T.Build() + local tradeQuery = build.itemsTab.tradeQuery + local generated = generateQuery(build, args) + local query = generated.query + local stats = tradeStatLookup() + local weighted = { } + for _, filter in ipairs(query.stats[1].filters) do + t_insert(weighted, { id = filter.id, text = stats[filter.id], weight = T.Round(filter.value.weight) }) + end + local result = { + slot = generated.row.unique and generated.row.slotName or generated.slot.slotName, + measuredIn = generated.row.unique and slotLabel(generated.slot) or nil, + category = generated.generator.calcContext.itemCategoryQueryStr, + weights = usedWeights(generated.weights), + minimumWeightedSum = T.Round(query.stats[1].value.min), + weightedStats = T.Array(weighted), + query = query, + } + local league = generated.league + -- As the trader composes the link when it is not logged in. + local encoded = league and tradeHelpers.B64GzipEncode(dkjson.encode(query)) + if league and encoded and encoded ~= "" then + local realm = args.realm or (tradeQuery.pbRealm ~= "" and tradeQuery.pbRealm) or "pc" + result.url = tradeQuery.tradeQueryRequests:buildUrl(tradeQuery.hostName .. "trade/search", realm, league) .. "/" .. encoded + result.league = league + elseif not league then + result.note = "Pass league to get a trade site link." + else + result.note = "Path of Building could not compress the query into a trade site link here; use the query with the trade site's search API." + end + return result + end, +} + +------------------------------------------------------------------------------ +-- trade_search +------------------------------------------------------------------------------ + +-- Realm and league of a trade site search link (TradeQueryRequests:SearchWithURL). +local function linkRealmAndLeague(tradeQuery, url) + local subpath = url:match(tradeQuery.hostNamePattern .. "trade/search/(.+)$") + local paths = { } + for path in (subpath or ""):gmatch("[^/]+") do + t_insert(paths, path) + end + if #paths < 2 or #paths > 3 then + T.Fail("url must be a pathofexile.com trade search link, as the trader's 'Price Item' takes.") + end + return #paths == 3 and paths[1] or "pc", urlDecode(paths[#paths - 1]) +end + +local function changeLines(build, before, after) + local collector = T.LineCollector() + build:AddStatComparesToTooltip(collector, before, after, "Changes:") + local lines = { } + for _, line in ipairs(collector.lines) do + if line ~= "Changes:" then + t_insert(lines, line) + end + end + return T.Array(lines) +end + +local searchCount = 0 + +local tradeSearchInput = copyTable(QUERY_INPUT, true) +tradeSearchInput.url = { type = "string", maxLength = 4000, description = "A pathofexile.com trade search link to run instead of generating one (the trader's 'Price Item' with a pasted link); results are measured in slot." } +tradeSearchInput.pages = { type = "integer", minimum = 1, maximum = 10, description = "Result pages to fetch, 10 listings each (the trader's 'Fetch Pages', default 2)." } +tradeSearchInput.sort_by = { type = "string", enum = { "stat_value", "stat_value_per_price", "price", "weighted_sum" }, description = "The trader's 'Sort By': stat_value (default, the weighted improvement PoB measures), stat_value_per_price, price (lowest first) or weighted_sum (the trade site's order)." } +tradeSearchInput.enchant_mode = { type = "string", enum = { "Keep", "Copy Current", "Remove" }, description = "Weapons, amulet, belt: what to do with the listings' enchants or anoints before measuring them (the dialog's Enchant/Anoint Behaviour, default Keep)." } +local limitArgs = T.PageArgs(10, 100) +tradeSearchInput.limit = limitArgs.limit +tradeSearchInput.offset = limitArgs.offset + +T.Tool { + name = "trade_search", + title = "Search the trade site", + description = "Runs the search of Path of Building's trader on the pathofexile.com trade site and measures every listing on the open " + .. "build, as 'Find best' followed by the trader's search does: the weighted search trade_query describes (same options), or a " + .. "trade search link given in url. It needs Path of Building to be logged in to Path of Exile (Import/Export tab, 'Authorize " + .. "with Path of Exile'), uses PoB's request queue and rate limits, and only reads listings: nothing is bought, posted or sent " + .. "to sellers. Returns the listings sorted as the trader's 'Sort By' (default: highest stat value), each with its price (and " + .. "in divines when PoB has the currency rates), what equipping it would change on the side bar, the item text to use with " + .. "simulate or items_equip, and the seller's whisper or a link to the listing. Listings are compared with the build's active " + .. "item set (change it with items_sets). A search takes a few seconds, longer when the trade site rate limits it.", + readOnly = true, + openWorld = true, + usesDialog = true, + input = tradeSearchInput, + required = { "slot" }, + run = function(args) + local build = T.Build() + local itemsTab = build.itemsTab + local tradeQuery = itemsTab.tradeQuery + if not main.api or not main.api.authToken then + T.Fail("Path of Building is not logged in to Path of Exile, which the trader needs to search. Ask the user to log in from the " + .. "Import/Export tab ('Authorize with Path of Exile'); meanwhile trade_query gives a trade site link they can open.") + end + local row, slot, weights, generated, realm, league + if args.url then + if not args.url:match("^https://") and not args.url:match("^www%.") and not args.url:match("^pathofexile") then + T.Fail("url must be a pathofexile.com trade search link.") + end + realm, league = linkRealmAndLeague(tradeQuery, args.url) + row, slot = tradeRow(build, args) + weights = chosenWeights(args, tradeQuery) + else + generated = generateQuery(build, args) + row, slot, weights = generated.row, generated.slot, generated.weights + league = generated.league + if not league then + T.Fail("Pass league, for example 'Standard' or the current league.") + end + realm = args.realm or (tradeQuery.pbRealm ~= "" and tradeQuery.pbRealm) or "pc" + end + local sortMode = tradeQuery.sortModes[SORT_MODES[args.sort_by or "stat_value"]] + -- The trader fetches currency rates when it opens; the price sorts and divine prices need them. + tradeQuery:PullCXData(realm) + + -- A queue of our own, so the trader's open searches are not disturbed; the rate limits are shared. + local requests = new("TradeQueryRequests"):TradeQueryRequests(tradeQuery.tradeQueryRequests.rateLimiter) + requests.maxFetchPerSearch = 10 * (args.pages or 2) + local treeTab = build.treeTab + local timeout = 120 + return T.Defer(function(resolve) + searchCount = searchCount + 1 + local frameKey = "McpTradeSearch" .. searchCount + local deadline = os.clock() + timeout + local searchUrl, sentQuery, longWait + local function stop() + main.onFrameFuncs[frameKey] = nil + requests.requestQueue.search, requests.requestQueue.fetch = { }, { } + end + -- PoB waits out rate limits itself; give up on long waits rather than keep the client waiting. + local function onRateLimit(wait) + if wait > 30 then + longWait = wait + end + end + main.onFrameFuncs[frameKey] = function() + if os.clock() > deadline then + return stop() + end + local ok, err = pcall(requests.ProcessQueue, requests, onRateLimit) + if not ok then + stop() + T.Settle(resolve, T.Fail, "Path of Building's trade requests failed: " .. tostring(err)) + elseif longWait then + stop() + T.Settle(resolve, T.Fail, s_format("pathofexile.com is rate limiting trade searches; try again in %d seconds.", longWait)) + end + end + local function onResults(items, errMsg, query) + stop() + T.Settle(resolve, function() + if errMsg then + if errMsg == "No Matching Results Found" then + T.Fail("The trade site found no listings for this search%s.", args.max_price and " (try a higher max_price)" or "") + end + T.Fail("The trade site search failed: %s", tostring(errMsg)) + end + if T.Build().treeTab ~= treeTab then + T.Fail("The open build changed while the search ran; nothing was measured.") + end + sentQuery = query + local filterSlot = row.unique and (row.selectedJewelNodeId and itemsTab.sockets[row.selectedJewelNodeId]) or (not row.unique and slot) or nil + local results + if generated then + results = tradeQuery:PrepareGeneratedResults(items or { }, filterSlot and filterSlot.slotName, row.slotName, + generated.includeEldritch, generated.copyEnchantMode) + else + results = tradeQuery:FilterToSafeItems(items or { }, filterSlot and filterSlot.slotName) + end + if not results[1] then + T.Fail("None of the listings found fit %s.", row.unique and row.slotName or slotLabel(slot)) + end + build:ProcessBuildFlag() + local calcFunc, baseOutput = build.calcsTab:GetMiscCalculator() + local notes = { } + local measured, evaluations, statValues = { }, { }, { } + for _, result in ipairs(results) do + local ok, evaluation = pcall(tradeQuery.EvaluateItem, tradeQuery, row, result.item_string, calcFunc, baseOutput, weights) + if ok then + t_insert(measured, result) + t_insert(evaluations, evaluation) + local sum = 0 + for _, entry in ipairs(evaluation) do + sum = sum + entry.weight + end + t_insert(statValues, sum) + end + end + if #measured < #results then + t_insert(notes, s_format("%d listing%s could not be measured and %s left out.", #results - #measured, + #results - #measured == 1 and "" or "s", #results - #measured == 1 and "is" or "are")) + end + results = measured + if not results[1] then + T.Fail("Path of Building could not measure any of the listings found.") + end + local sortedBy = args.sort_by or "stat_value" + local sorted, sortErr = tradeQuery:SortResults(results, sortMode, function(index) return statValues[index] end, realm, league) + if sortErr == "MissingConversionRates" then + t_insert(notes, "Currency rates were not available, so the listings are sorted by stat value, as the trader falls back to.") + sortedBy = "stat_value" + sorted = tradeQuery:SortResults(results, tradeQuery.sortModes.StatValue, function(index) return statValues[index] end, realm, league) + end + local page, paging = T.Page(sorted, args, 10, 100) + local listings = { } + for position, entry in ipairs(page) do + local result = results[entry.index] + local item = new("Item"):Item(result.item_string) + local listing = { + rank = (args.offset or 0) + position, + name = T.Clean(item.name), + rarity = item.rarity, + price = { amount = result.amount, currency = result.currency, type = result.priceType }, + priceInDivines = T.Round(tradeQuery:ConvertCurrencyToDivs(result.currency, result.amount, realm, league), 3), + statValue = T.Round(statValues[entry.index], 4), + tradeWeightedSum = tonumber(result.weight), + seller = result.trader, + item = result.item_string, + } + local output + if row.slotName == "Megalomaniac" then + local combos = { } + for _, evaluation in ipairs(evaluations[entry.index]) do + t_insert(combos, { nodes = evaluation.DNs, statValue = T.Round(evaluation.weight, 4) }) + end + listing.nodeCombinations = combos + local best = evaluations[entry.index][1] + local addNodes = { } + for _, dn in ipairs(best.DNs) do + addNodes[build.spec.tree.clusterNodeMap[dn]] = true + end + output = calcFunc({ addNodes = addNodes }) + listing.changesFor = t_concat(best.DNs, " + ") + else + output = calcFunc({ repSlotName = tradeQuery:GetEvaluationSlotName(row), repItem = item }) + end + listing.changes = changeLines(build, baseOutput, output) + listing.unmetRequirements = T.Array(T.UnmetRequirements(output)) + if result.whisper and result.priceType ~= "~b/o" then + listing.whisper = result.whisper + elseif sentQuery then + listing.listingUrl = tradeQuery:BuildListingSearchUrl(sentQuery, result, realm, league) + end + t_insert(listings, listing) + end + return { + slot = row.unique and row.slotName or slot.slotName, + measuredIn = row.unique and slotLabel(slot) or nil, + league = league, + realm = realm, + searchUrl = searchUrl, + weights = usedWeights(weights), + sortedBy = sortedBy, + found = #results, + listings = listings, + page = paging, + notes = notes[1] and T.Array(notes) or nil, + } + end) + end + if args.url then + searchUrl = args.url + requests:SearchWithURL(args.url, onResults) + else + -- Trade URLs contain only the query; the API also needs the sort order (as the trader sends it). + local body = dkjson.encode({ query = generated.query, sort = { ["statgroup.0"] = "desc" }, engine = "new" }) + requests:SearchWithQueryWeightAdjusted(realm, league, body, onResults, { + callbackQueryId = function(queryId) + searchUrl = requests:buildUrl(tradeQuery.hostName .. "trade/search", realm, league, queryId) + end, + }) + end + end, timeout) + end, +} From 4e4747ac18aa63e7130951ac9fdb3074405a241b Mon Sep 17 00:00:00 2001 From: Filipe Cavalcante <filipecavalc@gmail.com> Date: Mon, 16 Nov 2026 22:20:08 -0300 Subject: [PATCH 7/7] Add build_notes: read a build's notes from the open build, a saved build, a code or a link Guides keep their stages and advice in the Notes tab; the compare_with_guide prompt now reads them first. --- docs/mcp.md | 1 + spec/System/TestMcpServer_spec.lua | 30 +++++++++ src/Modules/McpTools.lua | 7 ++- src/Modules/McpTools/Build.lua | 99 ++++++++++++++++++++++++++++++ 4 files changed, 134 insertions(+), 3 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 7e1c572c220..5cbeb7bc726 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -59,6 +59,7 @@ Tools are grouped by the part of the window they work on. Read-only tools are ma | | `build_open` | Open a saved build, a code, a build link or a new build | | | `build_save` | Save, or save as a new name | | | `build_export` | Build share code or XML | +| | `build_notes` | A build's notes (Notes tab): the open build, a saved build, a code or a build link | | Side bar | `build_stats` | The side bar as shown, warnings, raw output values | | | `build_edit` | Character level and notes | | Calcs | `simulate` | What an item, passives or a flask would change, without changing the build | diff --git a/spec/System/TestMcpServer_spec.lua b/spec/System/TestMcpServer_spec.lua index 81841e440de..26a40d5c5fc 100644 --- a/spec/System/TestMcpServer_spec.lua +++ b/spec/System/TestMcpServer_spec.lua @@ -336,5 +336,35 @@ describe("MCP server", function() assert.are.equals("Hello", build.notesTab.controls.edit.buf) assert.is_true(build:HasUnsavedChanges()) end) + + it("reads notes from the open build or another build without changing anything", function() + local guide = "^xFF7700Level 1-30^7\nUse Groundslam & Ruthless.\n" .. string.rep("x", 1500) + build.notesTab.controls.edit:SetText(guide) + local xml = callTool("build_export", { format = "xml" }).xml + build:ResetModFlags() + + local open = callTool("build_notes") + assert.are.equals("open build", open.source) + assert.is_truthy(open.notes:find("^Level 1%-30\nUse Groundslam & Ruthless%.")) + assert.is_nil(open.notes:find("^x", 1, true)) + local raw = callTool("build_notes", { keep_colors = true, limit = 1000 }) + assert.is_truthy(raw.notes:find("^xFF7700Level", 1, true)) + assert.are.equals(1000, #raw.notes) + assert.are.equals(1000, raw.next_offset) + local rest = callTool("build_notes", { keep_colors = true, offset = 1000, limit = 1000 }) + assert.are.equals(raw.length - 1000, #rest.notes) + assert.is_nil(rest.next_offset) + + -- Another build's notes, while this one stays open and unchanged. + build.notesTab.controls.edit:SetText("") + build:ResetModFlags() + local other = callTool("build_notes", { code = xml }) + assert.are.equals("code", other.source) + assert.is_truthy(other.notes:find("Use Groundslam & Ruthless.", 1, true)) + assert.are.equals("", build.notesTab.controls.edit.buf) + assert.is_false(build:HasUnsavedChanges()) + assert.are.equals("This build has no notes.", callTool("build_notes").note) + assert.is_truthy(toolError("build_notes", { path = "No such build" }):find("No build file", 1, true)) + end) end) end) diff --git a/src/Modules/McpTools.lua b/src/Modules/McpTools.lua index 83abee3621a..cfd1a1ac019 100644 --- a/src/Modules/McpTools.lua +++ b/src/Modules/McpTools.lua @@ -509,9 +509,10 @@ local promptDefs = { arguments = { { name = "guide", description = "Build link (pobb.in, pob.codes, poe.ninja, ...) or build code.", required = true } }, text = function(args) return "Compare the build open in Path of Building with this guide build: " .. tostring(args.guide) .. "\n" - .. "1. Add it with compare_builds (action add) and read the report (action report) for the stat, tree, item, skill and config differences.\n" - .. "2. Summarise what the guide has that the open build lacks, ordered by impact.\n" - .. "3. Measure the most important differences with simulate before recommending them, and do not change the build unless asked." + .. "1. Read the guide's notes with build_notes (its stages, priorities and advice usually live there).\n" + .. "2. Add it with compare_builds (action add), pick the guide's sets for the open build's stage, and read the report (action report) for the stat, tree, item, skill and config differences.\n" + .. "3. Summarise what the guide has that the open build lacks, ordered by impact and in line with the guide's own priorities.\n" + .. "4. Measure the most important differences with simulate before recommending them, and do not change the build unless asked." end, }, { diff --git a/src/Modules/McpTools/Build.lua b/src/Modules/McpTools/Build.lua index 462de27d47a..f170b3a8ca1 100644 --- a/src/Modules/McpTools/Build.lua +++ b/src/Modules/McpTools/Build.lua @@ -435,6 +435,105 @@ T.Tool { end, } +-- The notes stored in a build's XML; NotesTab:Load keeps the last text node of <Notes>. +local function notesFromXML(xmlText) + local dbXML, errMsg = common.xml.ParseXML(xmlText) + if errMsg or not dbXML or type(dbXML[1]) ~= "table" or dbXML[1].elem ~= "PathOfBuilding" then + T.Fail("That is not a Path of Building build (%s).", tostring(errMsg or "no 'PathOfBuilding' root element")) + end + local notes = "" + for _, node in ipairs(dbXML[1]) do + if type(node) == "table" and node.elem == "Notes" then + for _, child in ipairs(node) do + if type(child) == "string" then + notes = child + end + end + end + end + return notes +end + +local function notesResult(text, args, source) + text = text:gsub("\r\n", "\n") + if not args.keep_colors then + text = T.Clean(text) + end + local offset = args.offset or 0 + local limit = args.limit or 20000 + local result = { source = source, length = #text, offset = offset, notes = text:sub(offset + 1, offset + limit) } + if offset + limit < #text then + result.next_offset = offset + limit + end + if not text:match("%S") then + result.note = "This build has no notes." + end + return result +end + +T.Tool { + name = "build_notes", + title = "Read build notes", + description = "Reads a build's notes (the Notes tab), where build authors and guides usually explain levelling steps, gear " + .. "priorities and how to play. Without a source it reads the open build (including unsaved edits); 'path' reads a saved " + .. "build from builds_list without opening it, 'code' a build share code or XML, and 'link' a build link from a site " + .. "PoB supports (PoB downloads it), so a guide's notes can be read while the user's own build stays open. PoB colour " + .. "codes are removed unless keep_colors is true. Long notes come in pages of characters (offset, next_offset).", + readOnly = true, + idempotent = true, + openWorld = true, + needsBuild = false, + input = { + path = { type = "string", description = "A saved build, as builds_list returns it." }, + code = { type = "string", maxLength = 2000000, description = "A build share code or build XML." }, + link = { type = "string", maxLength = 500, description = "A build link (pobb.in, pob.codes, poe.ninja, ...); PoB downloads it." }, + keep_colors = { type = "boolean", description = "Keep PoB colour codes (^1-^9, ^xRRGGBB) in the text (default false)." }, + offset = { type = "integer", minimum = 0, description = "Character to start from, for the next page (use next_offset)." }, + limit = { type = "integer", minimum = 1000, maximum = 100000, description = "Characters to return (default 20000)." }, + }, + run = function(args) + local sources = (args.path and 1 or 0) + (args.code and 1 or 0) + (args.link and 1 or 0) + if sources > 1 then + T.Fail("Give at most one of path, code or link.") + end + if args.path then + local relative = buildFolderPath(args.path, "path") + if not relative:lower():match("%.xml$") then + relative = relative .. ".xml" + end + local file = io.open(main.buildPath .. relative, "r") + if not file then + T.Fail("No build file '%s' in the builds folder; use builds_list to find it.", relative) + end + local xml = file:read("*a") + file:close() + return notesResult(notesFromXML(xml), args, relative) + elseif args.code then + return notesResult(notesFromXML(T.DecodeBuildCode(args.code)), args, "code") + elseif args.link then + local link = args.link:gsub("^%s+", ""):gsub("%s+$", "") + local site = T.FindBuildSite(link) + if not site then + T.Fail("Path of Building does not recognise that link; see build_open for the supported sites.") + end + return T.Defer(function(resolve) + buildSites.DownloadBuild(link, site, function(isSuccess, data) + if not isSuccess then + return resolve(nil, s_format("Could not download the build from %s: %s", site.label, tostring(data))) + end + T.Settle(resolve, function() + return notesResult(notesFromXML(T.DecodeBuildCode(data)), args, site.label) + end) + end) + end) + end + local build = T.Build() + -- While the Notes tab shows colour codes, its text escapes them (NotesTab:SetShowColorCodes). + local text = build.notesTab.controls.edit.buf:gsub("%^_x(%x%x%x%x%x%x)", "^x%1"):gsub("%^_(%d)", "^%1") + return notesResult(text, args, "open build") + end, +} + -- Raw output values for a list of field names. local function outputValues(output, fields) local values, missing = { }, { }