ai-helper-agent 1.17.3 → 1.17.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{r as e}from"./rolldown-runtime-C0FnF6B9.js";import{a as t,c as n}from"./i18n-B-0w1Ene.js";import{_ as r,g as i}from"./session-store-DXUXNW82.js";var a=e({createAgent:()=>m,deleteAgent:()=>g,getActiveAgentId:()=>_,getAgent:()=>p,getAllAgents:()=>d,getCustomAgents:()=>f,setActiveAgentId:()=>v,updateAgent:()=>h});t(`zh`,{agentStore:{unnamedAgent:`未命名Agent`}}),t(`en`,{agentStore:{unnamedAgent:`Unnamed Agent`}});var o=`customAgents`,s=`activeAssistantId`,c=`activeAgentId`,l=!1;async function u(){if(l)return;l=!0;let e=await chrome.storage.local.get([c,s]),t=e[c],n=e[s];t&&!n&&!t.startsWith(`pa_`)&&(await chrome.storage.local.set({[s]:t}),await chrome.storage.local.remove(c))}async function d(){let e=(await chrome.storage.local.get([o]))[o]||[];return[...i,...e]}async function f(){return(await chrome.storage.local.get([o]))[o]||[]}async function p(e){return e&&(await d()).find(t=>t.id===e)||null}async function m(e){let t=await f(),i={id:r(),name:e.name||n(`agentStore.unnamedAgent`),description:e.description||``,icon:e.icon||`🤖`,systemPrompt:e.systemPrompt||``,toolIds:e.toolIds||null,skillIds:e.skillIds||null,mcpExcludedServerIds:e.mcpExcludedServerIds??null,isBuiltin:!1,allowSubDispatch:e.allowSubDispatch!==void 0&&e.allowSubDispatch,model:e.model||null,temperature:e.temperature===void 0?null:e.temperature,topP:e.topP===void 0?null:e.topP,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return t.push(i),await chrome.storage.local.set({[o]:t}),i}async function h(e,t){let n=await f(),r=n.findIndex(t=>t.id===e);return r===-1?null:(n[r]={...n[r],...t,id:e,isBuiltin:!1,updatedAt:new Date().toISOString()},await chrome.storage.local.set({[o]:n}),n[r])}async function g(e){let t=await f(),n=t.findIndex(t=>t.id===e);return n!==-1&&(t.splice(n,1),await chrome.storage.local.set({[o]:t}),(await chrome.storage.local.get([s]))[s]===e&&await chrome.storage.local.remove(s),!0)}async function _(){return await u(),(await chrome.storage.local.get([s]))[s]||null}async function v(e){e?await chrome.storage.local.set({[s]:e}):await chrome.storage.local.remove(s)}export{p as a,h as c,_ as i,m as n,d as o,g as r,v as s,a as t};
2
- //# sourceMappingURL=agent-store-C-O6g-_E.js.map
1
+ import{r as e}from"./rolldown-runtime-C0FnF6B9.js";import{a as t,c as n}from"./i18n-DRXuSOEO.js";import{_ as r,g as i}from"./session-store-D3XI8_GA.js";var a=e({createAgent:()=>m,deleteAgent:()=>g,getActiveAgentId:()=>_,getAgent:()=>p,getAllAgents:()=>d,getCustomAgents:()=>f,setActiveAgentId:()=>v,updateAgent:()=>h});t(`zh`,{agentStore:{unnamedAgent:`未命名Agent`}}),t(`en`,{agentStore:{unnamedAgent:`Unnamed Agent`}});var o=`customAgents`,s=`activeAssistantId`,c=`activeAgentId`,l=!1;async function u(){if(l)return;l=!0;let e=await chrome.storage.local.get([c,s]),t=e[c],n=e[s];t&&!n&&!t.startsWith(`pa_`)&&(await chrome.storage.local.set({[s]:t}),await chrome.storage.local.remove(c))}async function d(){let e=(await chrome.storage.local.get([o]))[o]||[];return[...i,...e]}async function f(){return(await chrome.storage.local.get([o]))[o]||[]}async function p(e){return e&&(await d()).find(t=>t.id===e)||null}async function m(e){let t=await f(),i={id:r(),name:e.name||n(`agentStore.unnamedAgent`),description:e.description||``,icon:e.icon||`🤖`,systemPrompt:e.systemPrompt||``,toolIds:e.toolIds||null,skillIds:e.skillIds||null,mcpExcludedServerIds:e.mcpExcludedServerIds??null,isBuiltin:!1,allowSubDispatch:e.allowSubDispatch!==void 0&&e.allowSubDispatch,model:e.model||null,temperature:e.temperature===void 0?null:e.temperature,topP:e.topP===void 0?null:e.topP,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return t.push(i),await chrome.storage.local.set({[o]:t}),i}async function h(e,t){let n=await f(),r=n.findIndex(t=>t.id===e);return r===-1?null:(n[r]={...n[r],...t,id:e,isBuiltin:!1,updatedAt:new Date().toISOString()},await chrome.storage.local.set({[o]:n}),n[r])}async function g(e){let t=await f(),n=t.findIndex(t=>t.id===e);return n!==-1&&(t.splice(n,1),await chrome.storage.local.set({[o]:t}),(await chrome.storage.local.get([s]))[s]===e&&await chrome.storage.local.remove(s),!0)}async function _(){return await u(),(await chrome.storage.local.get([s]))[s]||null}async function v(e){e?await chrome.storage.local.set({[s]:e}):await chrome.storage.local.remove(s)}export{p as a,h as c,_ as i,m as n,d as o,g as r,v as s,a as t};
2
+ //# sourceMappingURL=agent-store-B5NQ1yV0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"agent-store-C-O6g-_E.js","names":[],"sources":["../../src/side_panel/agent-store.js"],"sourcesContent":["// side_panel/agent-store.js - Agent 数据持久化\nimport { BUILTIN_AGENTS, generateAgentId } from '../shared/agent-defaults.js';\nimport { t, registerTranslations } from '../shared/i18n.js';\n\nregisterTranslations('zh', {\n agentStore: {\n unnamedAgent: '未命名Agent',\n },\n});\nregisterTranslations('en', {\n agentStore: {\n unnamedAgent: 'Unnamed Agent',\n },\n});\n\nconst STORAGE_KEY = 'customAgents';\nconst ACTIVE_KEY = 'activeAssistantId';\nconst LEGACY_ACTIVE_KEY = 'activeAgentId';\n\nlet migratedActiveKey = false;\n\nasync function migrateLegacyActiveKey() {\n if (migratedActiveKey) return;\n migratedActiveKey = true;\n\n const result = await chrome.storage.local.get([LEGACY_ACTIVE_KEY, ACTIVE_KEY]);\n const legacyValue = result[LEGACY_ACTIVE_KEY];\n const newValue = result[ACTIVE_KEY];\n\n if (legacyValue && !newValue && !legacyValue.startsWith('pa_')) {\n await chrome.storage.local.set({ [ACTIVE_KEY]: legacyValue });\n await chrome.storage.local.remove(LEGACY_ACTIVE_KEY);\n }\n}\n\n/**\n * 获取所有 Agent(内置 + 用户自定义)\n * @returns {Promise<Array>}\n */\nexport async function getAllAgents() {\n const result = await chrome.storage.local.get([STORAGE_KEY]);\n const customAgents = result[STORAGE_KEY] || [];\n return [...BUILTIN_AGENTS, ...customAgents];\n}\n\n/**\n * 仅获取用户自定义的 Agent\n * @returns {Promise<Array>}\n */\nexport async function getCustomAgents() {\n const result = await chrome.storage.local.get([STORAGE_KEY]);\n return result[STORAGE_KEY] || [];\n}\n\n/**\n * 根据 ID 获取单个 Agent\n * @param {string} agentId\n * @returns {Promise<Object|null>}\n */\nexport async function getAgent(agentId) {\n if (!agentId) return null;\n const all = await getAllAgents();\n return all.find(a => a.id === agentId) || null;\n}\n\n/**\n * 创建新的自定义 Agent\n * @param {Object} agentData - 不含 id 的 Agent 数据\n * @returns {Promise<Object>}\n */\nexport async function createAgent(agentData) {\n const agents = await getCustomAgents();\n const newAgent = {\n id: generateAgentId(),\n name: agentData.name || t('agentStore.unnamedAgent'),\n description: agentData.description || '',\n icon: agentData.icon || '🤖',\n systemPrompt: agentData.systemPrompt || '',\n toolIds: agentData.toolIds || null, // null = 继承全局\n skillIds: agentData.skillIds || null, // null = 继承全部启用技能\n mcpExcludedServerIds: agentData.mcpExcludedServerIds ?? null, // MCP 服务排除列表(服务级 deny-list)\n isBuiltin: false,\n allowSubDispatch: agentData.allowSubDispatch !== undefined ? agentData.allowSubDispatch : false,\n model: agentData.model || null,\n temperature: agentData.temperature !== undefined ? agentData.temperature : null,\n topP: agentData.topP !== undefined ? agentData.topP : null,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n agents.push(newAgent);\n await chrome.storage.local.set({ [STORAGE_KEY]: agents });\n return newAgent;\n}\n\n/**\n * 更新已有的自定义 Agent\n * @param {string} agentId\n * @param {Object} updates\n * @returns {Promise<Object|null>}\n */\nexport async function updateAgent(agentId, updates) {\n const agents = await getCustomAgents();\n const idx = agents.findIndex(a => a.id === agentId);\n if (idx === -1) return null;\n \n agents[idx] = {\n ...agents[idx],\n ...updates,\n id: agentId, // id 不可变\n isBuiltin: false, // 不可变\n updatedAt: new Date().toISOString(),\n };\n await chrome.storage.local.set({ [STORAGE_KEY]: agents });\n return agents[idx];\n}\n\n/**\n * 删除自定义 Agent\n * @param {string} agentId\n * @returns {Promise<boolean>}\n */\nexport async function deleteAgent(agentId) {\n const agents = await getCustomAgents();\n const idx = agents.findIndex(a => a.id === agentId);\n if (idx === -1) return false;\n \n agents.splice(idx, 1);\n await chrome.storage.local.set({ [STORAGE_KEY]: agents });\n\n // 如果删除的 Agent 是当前选中的,重置为默认\n const result = await chrome.storage.local.get([ACTIVE_KEY]);\n if (result[ACTIVE_KEY] === agentId) {\n await chrome.storage.local.remove(ACTIVE_KEY);\n }\n \n return true;\n}\n\n/**\n * 获取当前选中的 Agent ID\n * @returns {Promise<string|null>}\n */\nexport async function getActiveAgentId() {\n await migrateLegacyActiveKey();\n const result = await chrome.storage.local.get([ACTIVE_KEY]);\n return result[ACTIVE_KEY] || null;\n}\n\n/**\n * 设置当前选中的 Agent ID\n * @param {string|null} agentId\n */\nexport async function setActiveAgentId(agentId) {\n if (agentId) {\n await chrome.storage.local.set({ [ACTIVE_KEY]: agentId });\n } else {\n await chrome.storage.local.remove(ACTIVE_KEY);\n }\n}\n\n/**\n * 从模板创建 Agent\n * @param {Object} template\n * @returns {Promise<Object>}\n */\nexport async function createAgentFromTemplate(template) {\n return createAgent({\n name: template.name,\n icon: template.icon,\n description: template.description,\n systemPrompt: template.systemPrompt,\n toolIds: template.toolIds ? [...template.toolIds] : null,\n allowSubDispatch: template.allowSubDispatch || false,\n });\n}\n"],"mappings":"+TAIA,EAAqB,KAAM,CACzB,WAAY,CACV,aAAc,UAChB,CACF,CAAC,EACD,EAAqB,KAAM,CACzB,WAAY,CACV,aAAc,eAChB,CACF,CAAC,EAED,IAAM,EAAc,eACd,EAAa,oBACb,EAAoB,gBAEtB,EAAoB,GAExB,eAAe,GAAyB,CACtC,GAAI,EAAmB,OACvB,EAAoB,GAEpB,IAAM,EAAS,MAAM,OAAO,QAAQ,MAAM,IAAI,CAAC,EAAmB,CAAU,CAAC,EACvE,EAAc,EAAO,GACrB,EAAW,EAAO,GAEpB,GAAe,CAAC,GAAY,CAAC,EAAY,WAAW,KAAK,IAC3D,MAAM,OAAO,QAAQ,MAAM,IAAI,EAAG,GAAa,CAAY,CAAC,EAC5D,MAAM,OAAO,QAAQ,MAAM,OAAO,CAAiB,EAEvD,CAMA,eAAsB,GAAe,CAEnC,IAAM,GAAe,MADA,OAAO,QAAQ,MAAM,IAAI,CAAC,CAAW,CAAC,EAAA,CAC/B,IAAgB,CAAC,EAC7C,MAAO,CAAC,GAAG,EAAgB,GAAG,CAAY,CAC5C,CAMA,eAAsB,GAAkB,CAEtC,OAAO,MADc,OAAO,QAAQ,MAAM,IAAI,CAAC,CAAW,CAAC,EAAA,CAC7C,IAAgB,CAAC,CACjC,CAOA,eAAsB,EAAS,EAAS,CAGtC,OAFK,IAEE,MADW,EAAa,EAAA,CACpB,KAAK,GAAK,EAAE,KAAO,CAAO,GAFhB,IAGvB,CAOA,eAAsB,EAAY,EAAW,CAC3C,IAAM,EAAS,MAAM,EAAgB,EAC/B,EAAW,CACf,GAAI,EAAgB,EACpB,KAAM,EAAU,MAAQ,EAAE,yBAAyB,EACnD,YAAa,EAAU,aAAe,GACtC,KAAM,EAAU,MAAQ,KACxB,aAAc,EAAU,cAAgB,GACxC,QAAS,EAAU,SAAW,KAC9B,SAAU,EAAU,UAAY,KAChC,qBAAsB,EAAU,sBAAwB,KACxD,UAAW,GACX,iBAAkB,EAAU,mBAAqB,IAAA,IAAY,EAAU,iBACvE,MAAO,EAAU,OAAS,KAC1B,YAAa,EAAU,cAAgB,IAAA,GAAoC,KAAxB,EAAU,YAC7D,KAAM,EAAU,OAAS,IAAA,GAA6B,KAAjB,EAAU,KAC/C,UAAW,IAAI,KAAK,CAAA,CAAE,YAAY,EAClC,UAAW,IAAI,KAAK,CAAA,CAAE,YAAY,CACpC,EAGA,OAFA,EAAO,KAAK,CAAQ,EACpB,MAAM,OAAO,QAAQ,MAAM,IAAI,EAAG,GAAc,CAAO,CAAC,EACjD,CACT,CAQA,eAAsB,EAAY,EAAS,EAAS,CAClD,IAAM,EAAS,MAAM,EAAgB,EAC/B,EAAM,EAAO,UAAU,GAAK,EAAE,KAAO,CAAO,EAWlD,OAVI,IAAQ,GAAW,MAEvB,EAAO,GAAO,CACZ,GAAG,EAAO,GACV,GAAG,EACH,GAAI,EACJ,UAAW,GACX,UAAW,IAAI,KAAK,CAAA,CAAE,YAAY,CACpC,EACA,MAAM,OAAO,QAAQ,MAAM,IAAI,EAAG,GAAc,CAAO,CAAC,EACjD,EAAO,GAChB,CAOA,eAAsB,EAAY,EAAS,CACzC,IAAM,EAAS,MAAM,EAAgB,EAC/B,EAAM,EAAO,UAAU,GAAK,EAAE,KAAO,CAAO,EAYlD,OAXI,IAAQ,KAEZ,EAAO,OAAO,EAAK,CAAC,EACpB,MAAM,OAAO,QAAQ,MAAM,IAAI,EAAG,GAAc,CAAO,CAAC,GAIpD,MADiB,OAAO,QAAQ,MAAM,IAAI,CAAC,CAAU,CAAC,EAAA,CAC/C,KAAgB,GACzB,MAAM,OAAO,QAAQ,MAAM,OAAO,CAAU,EAGvC,GACT,CAMA,eAAsB,GAAmB,CAGvC,OAFA,MAAM,EAAuB,GAEtB,MADc,OAAO,QAAQ,MAAM,IAAI,CAAC,CAAU,CAAC,EAAA,CAC5C,IAAe,IAC/B,CAMA,eAAsB,EAAiB,EAAS,CAC1C,EACF,MAAM,OAAO,QAAQ,MAAM,IAAI,EAAG,GAAa,CAAQ,CAAC,EAExD,MAAM,OAAO,QAAQ,MAAM,OAAO,CAAU,CAEhD"}
1
+ {"version":3,"file":"agent-store-B5NQ1yV0.js","names":[],"sources":["../../src/side_panel/agent-store.js"],"sourcesContent":["// side_panel/agent-store.js - Agent 数据持久化\nimport { BUILTIN_AGENTS, generateAgentId } from '../shared/agent-defaults.js';\nimport { t, registerTranslations } from '../shared/i18n.js';\n\nregisterTranslations('zh', {\n agentStore: {\n unnamedAgent: '未命名Agent',\n },\n});\nregisterTranslations('en', {\n agentStore: {\n unnamedAgent: 'Unnamed Agent',\n },\n});\n\nconst STORAGE_KEY = 'customAgents';\nconst ACTIVE_KEY = 'activeAssistantId';\nconst LEGACY_ACTIVE_KEY = 'activeAgentId';\n\nlet migratedActiveKey = false;\n\nasync function migrateLegacyActiveKey() {\n if (migratedActiveKey) return;\n migratedActiveKey = true;\n\n const result = await chrome.storage.local.get([LEGACY_ACTIVE_KEY, ACTIVE_KEY]);\n const legacyValue = result[LEGACY_ACTIVE_KEY];\n const newValue = result[ACTIVE_KEY];\n\n if (legacyValue && !newValue && !legacyValue.startsWith('pa_')) {\n await chrome.storage.local.set({ [ACTIVE_KEY]: legacyValue });\n await chrome.storage.local.remove(LEGACY_ACTIVE_KEY);\n }\n}\n\n/**\n * 获取所有 Agent(内置 + 用户自定义)\n * @returns {Promise<Array>}\n */\nexport async function getAllAgents() {\n const result = await chrome.storage.local.get([STORAGE_KEY]);\n const customAgents = result[STORAGE_KEY] || [];\n return [...BUILTIN_AGENTS, ...customAgents];\n}\n\n/**\n * 仅获取用户自定义的 Agent\n * @returns {Promise<Array>}\n */\nexport async function getCustomAgents() {\n const result = await chrome.storage.local.get([STORAGE_KEY]);\n return result[STORAGE_KEY] || [];\n}\n\n/**\n * 根据 ID 获取单个 Agent\n * @param {string} agentId\n * @returns {Promise<Object|null>}\n */\nexport async function getAgent(agentId) {\n if (!agentId) return null;\n const all = await getAllAgents();\n return all.find(a => a.id === agentId) || null;\n}\n\n/**\n * 创建新的自定义 Agent\n * @param {Object} agentData - 不含 id 的 Agent 数据\n * @returns {Promise<Object>}\n */\nexport async function createAgent(agentData) {\n const agents = await getCustomAgents();\n const newAgent = {\n id: generateAgentId(),\n name: agentData.name || t('agentStore.unnamedAgent'),\n description: agentData.description || '',\n icon: agentData.icon || '🤖',\n systemPrompt: agentData.systemPrompt || '',\n toolIds: agentData.toolIds || null, // null = 继承全局\n skillIds: agentData.skillIds || null, // null = 继承全部启用技能\n mcpExcludedServerIds: agentData.mcpExcludedServerIds ?? null, // MCP 服务排除列表(服务级 deny-list)\n isBuiltin: false,\n allowSubDispatch: agentData.allowSubDispatch !== undefined ? agentData.allowSubDispatch : false,\n model: agentData.model || null,\n temperature: agentData.temperature !== undefined ? agentData.temperature : null,\n topP: agentData.topP !== undefined ? agentData.topP : null,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n };\n agents.push(newAgent);\n await chrome.storage.local.set({ [STORAGE_KEY]: agents });\n return newAgent;\n}\n\n/**\n * 更新已有的自定义 Agent\n * @param {string} agentId\n * @param {Object} updates\n * @returns {Promise<Object|null>}\n */\nexport async function updateAgent(agentId, updates) {\n const agents = await getCustomAgents();\n const idx = agents.findIndex(a => a.id === agentId);\n if (idx === -1) return null;\n \n agents[idx] = {\n ...agents[idx],\n ...updates,\n id: agentId, // id 不可变\n isBuiltin: false, // 不可变\n updatedAt: new Date().toISOString(),\n };\n await chrome.storage.local.set({ [STORAGE_KEY]: agents });\n return agents[idx];\n}\n\n/**\n * 删除自定义 Agent\n * @param {string} agentId\n * @returns {Promise<boolean>}\n */\nexport async function deleteAgent(agentId) {\n const agents = await getCustomAgents();\n const idx = agents.findIndex(a => a.id === agentId);\n if (idx === -1) return false;\n \n agents.splice(idx, 1);\n await chrome.storage.local.set({ [STORAGE_KEY]: agents });\n\n // 如果删除的 Agent 是当前选中的,重置为默认\n const result = await chrome.storage.local.get([ACTIVE_KEY]);\n if (result[ACTIVE_KEY] === agentId) {\n await chrome.storage.local.remove(ACTIVE_KEY);\n }\n \n return true;\n}\n\n/**\n * 获取当前选中的 Agent ID\n * @returns {Promise<string|null>}\n */\nexport async function getActiveAgentId() {\n await migrateLegacyActiveKey();\n const result = await chrome.storage.local.get([ACTIVE_KEY]);\n return result[ACTIVE_KEY] || null;\n}\n\n/**\n * 设置当前选中的 Agent ID\n * @param {string|null} agentId\n */\nexport async function setActiveAgentId(agentId) {\n if (agentId) {\n await chrome.storage.local.set({ [ACTIVE_KEY]: agentId });\n } else {\n await chrome.storage.local.remove(ACTIVE_KEY);\n }\n}\n\n/**\n * 从模板创建 Agent\n * @param {Object} template\n * @returns {Promise<Object>}\n */\nexport async function createAgentFromTemplate(template) {\n return createAgent({\n name: template.name,\n icon: template.icon,\n description: template.description,\n systemPrompt: template.systemPrompt,\n toolIds: template.toolIds ? [...template.toolIds] : null,\n allowSubDispatch: template.allowSubDispatch || false,\n });\n}\n"],"mappings":"+TAIA,EAAqB,KAAM,CACzB,WAAY,CACV,aAAc,UAChB,CACF,CAAC,EACD,EAAqB,KAAM,CACzB,WAAY,CACV,aAAc,eAChB,CACF,CAAC,EAED,IAAM,EAAc,eACd,EAAa,oBACb,EAAoB,gBAEtB,EAAoB,GAExB,eAAe,GAAyB,CACtC,GAAI,EAAmB,OACvB,EAAoB,GAEpB,IAAM,EAAS,MAAM,OAAO,QAAQ,MAAM,IAAI,CAAC,EAAmB,CAAU,CAAC,EACvE,EAAc,EAAO,GACrB,EAAW,EAAO,GAEpB,GAAe,CAAC,GAAY,CAAC,EAAY,WAAW,KAAK,IAC3D,MAAM,OAAO,QAAQ,MAAM,IAAI,EAAG,GAAa,CAAY,CAAC,EAC5D,MAAM,OAAO,QAAQ,MAAM,OAAO,CAAiB,EAEvD,CAMA,eAAsB,GAAe,CAEnC,IAAM,GAAe,MADA,OAAO,QAAQ,MAAM,IAAI,CAAC,CAAW,CAAC,EAAA,CAC/B,IAAgB,CAAC,EAC7C,MAAO,CAAC,GAAG,EAAgB,GAAG,CAAY,CAC5C,CAMA,eAAsB,GAAkB,CAEtC,OAAO,MADc,OAAO,QAAQ,MAAM,IAAI,CAAC,CAAW,CAAC,EAAA,CAC7C,IAAgB,CAAC,CACjC,CAOA,eAAsB,EAAS,EAAS,CAGtC,OAFK,IAEE,MADW,EAAa,EAAA,CACpB,KAAK,GAAK,EAAE,KAAO,CAAO,GAFhB,IAGvB,CAOA,eAAsB,EAAY,EAAW,CAC3C,IAAM,EAAS,MAAM,EAAgB,EAC/B,EAAW,CACf,GAAI,EAAgB,EACpB,KAAM,EAAU,MAAQ,EAAE,yBAAyB,EACnD,YAAa,EAAU,aAAe,GACtC,KAAM,EAAU,MAAQ,KACxB,aAAc,EAAU,cAAgB,GACxC,QAAS,EAAU,SAAW,KAC9B,SAAU,EAAU,UAAY,KAChC,qBAAsB,EAAU,sBAAwB,KACxD,UAAW,GACX,iBAAkB,EAAU,mBAAqB,IAAA,IAAY,EAAU,iBACvE,MAAO,EAAU,OAAS,KAC1B,YAAa,EAAU,cAAgB,IAAA,GAAoC,KAAxB,EAAU,YAC7D,KAAM,EAAU,OAAS,IAAA,GAA6B,KAAjB,EAAU,KAC/C,UAAW,IAAI,KAAK,CAAA,CAAE,YAAY,EAClC,UAAW,IAAI,KAAK,CAAA,CAAE,YAAY,CACpC,EAGA,OAFA,EAAO,KAAK,CAAQ,EACpB,MAAM,OAAO,QAAQ,MAAM,IAAI,EAAG,GAAc,CAAO,CAAC,EACjD,CACT,CAQA,eAAsB,EAAY,EAAS,EAAS,CAClD,IAAM,EAAS,MAAM,EAAgB,EAC/B,EAAM,EAAO,UAAU,GAAK,EAAE,KAAO,CAAO,EAWlD,OAVI,IAAQ,GAAW,MAEvB,EAAO,GAAO,CACZ,GAAG,EAAO,GACV,GAAG,EACH,GAAI,EACJ,UAAW,GACX,UAAW,IAAI,KAAK,CAAA,CAAE,YAAY,CACpC,EACA,MAAM,OAAO,QAAQ,MAAM,IAAI,EAAG,GAAc,CAAO,CAAC,EACjD,EAAO,GAChB,CAOA,eAAsB,EAAY,EAAS,CACzC,IAAM,EAAS,MAAM,EAAgB,EAC/B,EAAM,EAAO,UAAU,GAAK,EAAE,KAAO,CAAO,EAYlD,OAXI,IAAQ,KAEZ,EAAO,OAAO,EAAK,CAAC,EACpB,MAAM,OAAO,QAAQ,MAAM,IAAI,EAAG,GAAc,CAAO,CAAC,GAIpD,MADiB,OAAO,QAAQ,MAAM,IAAI,CAAC,CAAU,CAAC,EAAA,CAC/C,KAAgB,GACzB,MAAM,OAAO,QAAQ,MAAM,OAAO,CAAU,EAGvC,GACT,CAMA,eAAsB,GAAmB,CAGvC,OAFA,MAAM,EAAuB,GAEtB,MADc,OAAO,QAAQ,MAAM,IAAI,CAAC,CAAU,CAAC,EAAA,CAC5C,IAAe,IAC/B,CAMA,eAAsB,EAAiB,EAAS,CAC1C,EACF,MAAM,OAAO,QAAQ,MAAM,IAAI,EAAG,GAAa,CAAQ,CAAC,EAExD,MAAM,OAAO,QAAQ,MAAM,OAAO,CAAU,CAEhD"}
@@ -1,4 +1,4 @@
1
- import{a as e,c as t,i as n,l as r,r as i}from"./i18n-B-0w1Ene.js";import{a,d as o,f as s,h as c,i as l,l as u,m as d,p as f,s as p,t as m,u as h}from"./constants-C6-BtNIC.js";import{$ as g,A as _,B as v,E as y,F as b,G as x,H as S,I as C,J as w,K as T,M as E,N as D,R as ee,T as O,V as k,Z as A,at as te,ct as ne,dt as re,et as ie,ft as ae,g as j,it as M,k as oe,lt as se,mt as ce,nt as le,ot as ue,pt as de,q as fe,r as pe,t as N,tt as me,ut as he,z as P}from"./session-store-DXUXNW82.js";var ge=new Map,_e=new Map,ve=new Map,ye=new Map,be=new Map;function xe(e){e&&ye.set(e,0)}function Se(e){if(e){let t=(ye.get(e)||0)+1;return ye.set(e,t),t}return 0}function Ce(e){return e&&ye.get(e)||0}function we(e){if(typeof e==`number`){be.set(e,!0),r.debug(`[Background] ReAct loop cancelled,tabId:`,e);return}if(e===null){ge.clear(),be.clear();for(let[e,t]of _e)t.abort(),r.debug(`[Background] cancelledsession fetch requested ,sessionId:`,e);_e.clear(),ve.clear(),r.debug(`[Background] all has session ReAct loop cancelled`)}else{ge.set(e,!0);let t=_e.get(e);t&&(t.abort(),r.debug(`[Background] cancelledsession fetch requested ,sessionId:`,e)),r.debug(`[Background] ReAct loop cancelled,sessionId:`,e)}}function Te(e){if(typeof e==`number`){be.delete(e);return}e!=null&&(ge.delete(e),_e.delete(e),r.debug(`[Background] sessioncancelstatereset,sessionId:`,e))}function Ee(e,t=!0){if(t){let t=_e.get(e);t&&t.abort()}let n=new AbortController;return _e.set(e,n),n}function F(e){if(e==null)return!1;if(typeof e==`number`)return be.get(e)===!0;if(ge.get(e)===!0)return!0;for(let t of ge.keys())if(e.startsWith(t+`_`))return!0;return!1}function I(e){e!==null&&be.delete(e)}function De(e){I(e)}var Oe=new Map;function ke(e,t){e&&t!=null&&Oe.set(e,t)}function L(e){return e?Oe.get(e):null}function Ae(e){if(!e)return null;let t=new AbortController;return ve.set(e,t),t}function je(e){if(!e)return!1;let t=ve.get(e);return t&&!t.signal.aborted?(t.abort(),ve.delete(e),!0):!1}function Me(e){e&&ve.delete(e)}function R(){return new Promise(e=>{chrome.storage.local.get([`apiBase`,`apiKey`,`modelName`,`enabledTools`,`temperature`,`topP`,`reactMaxIterations`,`reactApiTimeout`,`reactLoopTimeout`,`reactToolTimeout`,`enableToolPreselect`,`toolConfirmationEnabled`,`reflectionConfig`,`streamEnabled`,`streamChunkDelay`,`agentStreamEnabled`],t=>{e({apiBase:t.apiBase||`https://api.deepseek.com`,apiKey:t.apiKey||``,modelName:t.modelName||`deepseek-v4-pro`,temperature:t.temperature===void 0?void 0:t.temperature,topP:t.topP===void 0?void 0:t.topP,enabledTools:t.enabledTools||[`page_content`,`query_elements`,`clipboard`],reactConfig:{maxIterations:t.reactMaxIterations||u.maxIterations,apiTimeout:t.reactApiTimeout||u.apiTimeout,loopTimeout:t.reactLoopTimeout||u.loopTimeout,toolTimeout:t.reactToolTimeout||u.toolTimeout,clarifyTimeout:u.clarifyTimeout,apiRetryCount:u.apiRetryCount,apiRetryBaseDelay:u.apiRetryBaseDelay,enableToolPreselect:t.enableToolPreselect===void 0?u.enableToolPreselect:t.enableToolPreselect,preselectMinToolCount:u.preselectMinToolCount,toolConfirmationEnabled:t.toolConfirmationEnabled===void 0?u.toolConfirmationEnabled:t.toolConfirmationEnabled,reflection:t.reflectionConfig||h},streamConfig:{streamEnabled:t.streamEnabled===void 0?o.streamEnabled:t.streamEnabled,streamChunkDelay:t.streamChunkDelay===void 0?o.streamChunkDelay:t.streamChunkDelay,agentStreamEnabled:t.agentStreamEnabled===void 0?o.agentStreamEnabled:t.agentStreamEnabled}})})})}function Ne(){return new Promise(e=>{chrome.storage.local.get([`chatMaxMemoryMessages`,`enableExecutionLog`,`customModels`,`streamExpandTools`,`showMessageTimestamp`],t=>{e({maxMemoryMessages:t.chatMaxMemoryMessages===void 0?p.maxMemoryMessages:t.chatMaxMemoryMessages,enableExecutionLog:t.enableExecutionLog===void 0?p.enableExecutionLog:t.enableExecutionLog,customModelMap:ne(t.customModels||[]),streamExpandTools:t.streamExpandTools===!0,showMessageTimestamp:t.showMessageTimestamp!==!1})})})}e(`zh`,{agentClient:{pairingFailed:`配对失败`,cannotConnectAgent:`无法连接到 Agent: {error}`,agentNotPaired:`Agent 未配对,请先在设置中完成配对`,proxyNotConnected:`代理服务未连接,请确认代理服务已启动`,requestTimeout:`请求超时 ({timeout}ms)`,agentRequestFailed:`Agent 请求失败: {error}`,agentNotPairedShort:`Agent 未配对`,uploadTimeout:`文件上传超时 (60s)`,uploadFailed:`文件上传失败: {error}`,skillPromptFailed:`获取技能提示词失败`}}),e(`en`,{agentClient:{pairingFailed:`Pairing failed`,cannotConnectAgent:`Cannot connect to Agent: {error}`,agentNotPaired:`Agent not paired, please complete pairing in settings first`,proxyNotConnected:`Proxy service not connected, please confirm the proxy service is running`,requestTimeout:`Request timeout ({timeout}ms)`,agentRequestFailed:`Agent request failed: {error}`,agentNotPairedShort:`Agent not paired`,uploadTimeout:`File upload timeout (60s)`,uploadFailed:`File upload failed: {error}`,skillPromptFailed:`Failed to get skill prompt`}});var z=new Map;function Pe(e,t){z.get(e)!==t&&r.debug(`[AgentClient] agentreachable toggle change:`,e,t?`reachable`:`unreachable`),z.set(e,t)}function Fe(e){return z.get(e)??null}function Ie(){return`pa_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}async function Le(){try{let e=await chrome.storage.local.get([`agentUrl`,`agentToken`,`agentPlatform`,`pairedAgents`]);if(e.pairedAgents&&e.pairedAgents.length>0)return!1;if(e.agentUrl&&e.agentToken){let t=e.agentPlatform||{},n=t.platformName?`${t.platformName} ${t.arch||``}`.trim():`默认代理`,i=Ie(),a=[{id:i,name:n,url:e.agentUrl,token:e.agentToken,pairedAt:new Date().toISOString()}];return await chrome.storage.local.set({pairedAgents:a,activeAgentId:i}),await chrome.storage.local.remove([`agentUrl`,`agentToken`,`agentPlatform`]),r.debug(`[AgentClient] from old formatmigrate agentconfiguration:`,n),!0}}catch(e){r.warn(`[AgentClient] old format migration failed:`,e.message)}return!1}async function Re(){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=e.pairedAgents||[],n=e.activeAgentId;if(!n||t.length===0)return{url:null,token:null,connected:!1,agentId:null};let r=t.find(e=>e.id===n);if(!r){let e=t[0];return await chrome.storage.local.set({activeAgentId:e.id}),{url:e.url,token:e.token,connected:!0,agentId:e.id}}return{url:r.url,token:r.token,connected:!0,agentId:r.id}}async function ze(){return(await chrome.storage.local.get(`pairedAgents`)).pairedAgents||[]}async function Be(){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=e.pairedAgents||[];return!e.activeAgentId||t.length===0?null:t.find(t=>t.id===e.activeAgentId)||t[0]||null}async function B(e){return(await ze()).find(t=>t.id===e)?(await chrome.storage.local.set({activeAgentId:e}),z.delete(e),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}).catch(()=>{}),r.debug(`[AgentClient] switched to agent:`,e),!0):(r.warn(`[AgentClient] switch failed,agent not found:`,e),!1)}async function V(e,n={},r=`POST`,a=6e4){let o=await Re();if(!o.connected)return{success:!1,error:t(`agentClient.agentNotPaired`)};if(o.agentId&&z.get(o.agentId)===!1)return{success:!1,error:t(`agentClient.proxyNotConnected`)};let s=new AbortController,c=setTimeout(()=>s.abort(),a);try{let t={method:r,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${o.token}`,"Accept-Language":i()},signal:s.signal};r!==`GET`&&r!==`HEAD`&&(t.body=JSON.stringify(n));let a=await fetch(`${o.url}${e}`,t);clearTimeout(c);let l=await a.json();return l&&typeof l==`object`&&(l.httpStatus=a.status),l}catch(e){return clearTimeout(c),e.name===`AbortError`?{success:!1,error:t(`agentClient.requestTimeout`,{timeout:a})}:{success:!1,error:t(`agentClient.agentRequestFailed`,{error:e.message})}}}async function H(e,n=3e4){let r=await Re();if(!r.connected)return{success:!1,error:t(`agentClient.agentNotPairedShort`)};if(r.agentId&&z.get(r.agentId)===!1)return{success:!1,error:t(`agentClient.proxyNotConnected`)};let a=new AbortController,o=setTimeout(()=>a.abort(),n);try{let t=await fetch(`${r.url}${e}`,{method:`GET`,headers:{Authorization:`Bearer ${r.token}`,"Accept-Language":i()},signal:a.signal});return clearTimeout(o),await t.json()}catch(e){return clearTimeout(o),e.name===`AbortError`?{success:!1,error:t(`agentClient.requestTimeout`,{timeout:n})}:{success:!1,error:t(`agentClient.agentRequestFailed`,{error:e.message})}}}async function Ve(e){return V(`/api/fs/read`,{path:e})}async function He(e){let t=await V(`/api/fs/stat`,{path:e});return t.success?{success:!0,exists:!0,info:t.info}:t.httpStatus===404?{success:!0,exists:!1}:{success:!1}}async function Ue(e,t){return V(`/api/fs/write`,{path:e,content:t})}async function We(e){return V(`/api/browser/open`,{path:e})}async function Ge(e){return V(`/api/fs/list`,{path:e})}async function Ke(e){return V(`/api/fs/delete`,{path:e})}async function qe(e){return V(`/api/fs/download`,{path:e},`POST`,12e4)}async function Je(e,t=`*`,n=!0,r=200){return V(`/api/fs/search_files`,{path:e,pattern:t,recursive:n,maxResults:r})}async function Ye(e,t,n=null,r=!1,i=!0,a=100,o=2){return V(`/api/fs/search_content`,{path:e,pattern:t,filePattern:n,caseSensitive:r,recursive:i,maxResults:a,contextLines:o})}async function Xe(e,t,n=!1){return V(`/api/exec`,{command:e,cwd:t,force:n})}async function Ze(e,t,n=!1,r=6e5){return V(`/api/exec`,{command:e,cwd:t,wait:!0,force:n},`POST`,r)}async function Qe(e){return V(`/api/exec/stop`,{execId:e})}async function $e(e,n,i,a,o){let s=await Re();if(!s.connected)return a&&a(Error(t(`agentClient.agentNotPairedShort`))),null;if(s.agentId&&z.get(s.agentId)===!1)return a&&a(Error(t(`agentClient.proxyNotConnected`))),null;let c=e;if(s.url)try{let t=new URL(s.url),n=/^ws[s]?:\/\/(0\.0\.0\.0|127\.0\.0\.1|localhost):/;if(n.test(e)){let r=t.protocol===`https:`?`wss:`:`ws:`;c=e.replace(n,`${r}//${t.hostname}:`)}}catch{c=e.replace(`0.0.0.0`,`127.0.0.1`)}let l=c.includes(`?`)?`&`:`?`,u=`${c}${l}token=${encodeURIComponent(s.token)}`;return new Promise((e,t)=>{let o=new WebSocket(u),s=!1;o.onopen=()=>{s||(s=!0,r.debug(`[AgentClient] WebSocket connected:`,c,`(with token)`),e(o))},o.onmessage=e=>{try{let t=JSON.parse(e.data);n&&n(t)}catch{n&&n({type:`raw`,data:e.data})}},o.onclose=()=>{r.debug(`[AgentClient] WebSocket closed`),i&&i()},o.onerror=e=>{if(s)return;s=!0;let n=e instanceof Error?e:Error(`WebSocket 连接失败`);r.error(`[AgentClient] WebSocket error:`,n.message||e),a&&a(n),t(n)}})}async function et(e){return H(e?`/api/mcp/tools?serverId=${encodeURIComponent(e)}`:`/api/mcp/tools`)}async function tt(e,t,n){return V(`/api/mcp/call`,{serverId:e,toolName:t,args:n})}async function nt(){return H(`/api/mcp/servers`)}async function rt(){return H(`/api/rag/collections`)}async function it(e){return V(`/api/rag/search`,e,`POST`,18e4)}async function at(e,t){return V(`/api/rag/collections/${encodeURIComponent(e)}/ingest`,t,`POST`,6e5)}async function ot(){return H(`/api/skill/list`)}async function st(e,t){return V(`/api/skill/run`,{name:e,params:t})}var ct=null,lt=null;function ut(){ct=null,lt=null}async function dt(){return ct&&Date.now()-ct.loadedAt<6e4?ct.agentNames:lt?(await lt,ct.agentNames):(lt=(async()=>{try{let e=await H(`/api/skill/list`),t=e?.success&&e.skills||[];ct={agentNames:new Set(t.filter(e=>e.type===`agent`).map(e=>e.name)),loadedAt:Date.now()}}catch{}finally{lt=null}})(),await lt,ct?.agentNames||new Set)}async function ft(){return H(`/api/skill/agent-prompts`)}async function pt(e){if(!e||e.length===0)return{success:!0,prompts:``};try{let t=await dt(),n=e.filter(e=>t.has(e));return n.length===0?{success:!0,prompts:``}:{success:!0,prompts:(await Promise.all(n.map(e=>mt(e).catch(()=>null)))).filter(e=>e&&e.success&&e.prompt).map(e=>e.prompt).join(`
1
+ import{a as e,c as t,i as n,l as r,r as i}from"./i18n-DRXuSOEO.js";import{a,d as o,f as s,h as c,i as l,l as u,m as d,p as f,s as p,t as m,u as h}from"./constants-C6-BtNIC.js";import{$ as g,A as _,B as v,E as y,F as b,G as x,H as S,I as C,J as w,K as T,M as E,N as D,R as ee,T as O,V as k,Z as A,at as te,ct as ne,dt as re,et as ie,ft as ae,g as j,it as M,k as oe,lt as se,mt as ce,nt as le,ot as ue,pt as de,q as fe,r as pe,t as N,tt as me,ut as he,z as P}from"./session-store-D3XI8_GA.js";var ge=new Map,_e=new Map,ve=new Map,ye=new Map,be=new Map;function xe(e){e&&ye.set(e,0)}function Se(e){if(e){let t=(ye.get(e)||0)+1;return ye.set(e,t),t}return 0}function Ce(e){return e&&ye.get(e)||0}function we(e){if(typeof e==`number`){be.set(e,!0),r.debug(`[Background] ReAct loop cancelled,tabId:`,e);return}if(e===null){ge.clear(),be.clear();for(let[e,t]of _e)t.abort(),r.debug(`[Background] cancelledsession fetch requested ,sessionId:`,e);_e.clear(),ve.clear(),r.debug(`[Background] all has session ReAct loop cancelled`)}else{ge.set(e,!0);let t=_e.get(e);t&&(t.abort(),r.debug(`[Background] cancelledsession fetch requested ,sessionId:`,e)),r.debug(`[Background] ReAct loop cancelled,sessionId:`,e)}}function Te(e){if(typeof e==`number`){be.delete(e);return}e!=null&&(ge.delete(e),_e.delete(e),r.debug(`[Background] sessioncancelstatereset,sessionId:`,e))}function Ee(e,t=!0){if(t){let t=_e.get(e);t&&t.abort()}let n=new AbortController;return _e.set(e,n),n}function F(e){if(e==null)return!1;if(typeof e==`number`)return be.get(e)===!0;if(ge.get(e)===!0)return!0;for(let t of ge.keys())if(e.startsWith(t+`_`))return!0;return!1}function I(e){e!==null&&be.delete(e)}function De(e){I(e)}var Oe=new Map;function ke(e,t){e&&t!=null&&Oe.set(e,t)}function L(e){return e?Oe.get(e):null}function Ae(e){if(!e)return null;let t=new AbortController;return ve.set(e,t),t}function je(e){if(!e)return!1;let t=ve.get(e);return t&&!t.signal.aborted?(t.abort(),ve.delete(e),!0):!1}function Me(e){e&&ve.delete(e)}function R(){return new Promise(e=>{chrome.storage.local.get([`apiBase`,`apiKey`,`modelName`,`enabledTools`,`temperature`,`topP`,`reactMaxIterations`,`reactApiTimeout`,`reactLoopTimeout`,`reactToolTimeout`,`enableToolPreselect`,`toolConfirmationEnabled`,`reflectionConfig`,`streamEnabled`,`streamChunkDelay`,`agentStreamEnabled`],t=>{e({apiBase:t.apiBase||`https://api.deepseek.com`,apiKey:t.apiKey||``,modelName:t.modelName||`deepseek-v4-pro`,temperature:t.temperature===void 0?void 0:t.temperature,topP:t.topP===void 0?void 0:t.topP,enabledTools:t.enabledTools||[`page_content`,`query_elements`,`clipboard`],reactConfig:{maxIterations:t.reactMaxIterations||u.maxIterations,apiTimeout:t.reactApiTimeout||u.apiTimeout,loopTimeout:t.reactLoopTimeout||u.loopTimeout,toolTimeout:t.reactToolTimeout||u.toolTimeout,clarifyTimeout:u.clarifyTimeout,apiRetryCount:u.apiRetryCount,apiRetryBaseDelay:u.apiRetryBaseDelay,enableToolPreselect:t.enableToolPreselect===void 0?u.enableToolPreselect:t.enableToolPreselect,preselectMinToolCount:u.preselectMinToolCount,toolConfirmationEnabled:t.toolConfirmationEnabled===void 0?u.toolConfirmationEnabled:t.toolConfirmationEnabled,reflection:t.reflectionConfig||h},streamConfig:{streamEnabled:t.streamEnabled===void 0?o.streamEnabled:t.streamEnabled,streamChunkDelay:t.streamChunkDelay===void 0?o.streamChunkDelay:t.streamChunkDelay,agentStreamEnabled:t.agentStreamEnabled===void 0?o.agentStreamEnabled:t.agentStreamEnabled}})})})}function Ne(){return new Promise(e=>{chrome.storage.local.get([`chatMaxMemoryMessages`,`enableExecutionLog`,`customModels`,`streamExpandTools`,`showMessageTimestamp`],t=>{e({maxMemoryMessages:t.chatMaxMemoryMessages===void 0?p.maxMemoryMessages:t.chatMaxMemoryMessages,enableExecutionLog:t.enableExecutionLog===void 0?p.enableExecutionLog:t.enableExecutionLog,customModelMap:ne(t.customModels||[]),streamExpandTools:t.streamExpandTools===!0,showMessageTimestamp:t.showMessageTimestamp!==!1})})})}e(`zh`,{agentClient:{pairingFailed:`配对失败`,cannotConnectAgent:`无法连接到 Agent: {error}`,agentNotPaired:`Agent 未配对,请先在设置中完成配对`,proxyNotConnected:`代理服务未连接,请确认代理服务已启动`,requestTimeout:`请求超时 ({timeout}ms)`,agentRequestFailed:`Agent 请求失败: {error}`,agentNotPairedShort:`Agent 未配对`,uploadTimeout:`文件上传超时 (60s)`,uploadFailed:`文件上传失败: {error}`,skillPromptFailed:`获取技能提示词失败`}}),e(`en`,{agentClient:{pairingFailed:`Pairing failed`,cannotConnectAgent:`Cannot connect to Agent: {error}`,agentNotPaired:`Agent not paired, please complete pairing in settings first`,proxyNotConnected:`Proxy service not connected, please confirm the proxy service is running`,requestTimeout:`Request timeout ({timeout}ms)`,agentRequestFailed:`Agent request failed: {error}`,agentNotPairedShort:`Agent not paired`,uploadTimeout:`File upload timeout (60s)`,uploadFailed:`File upload failed: {error}`,skillPromptFailed:`Failed to get skill prompt`}});var z=new Map;function Pe(e,t){z.get(e)!==t&&r.debug(`[AgentClient] agentreachable toggle change:`,e,t?`reachable`:`unreachable`),z.set(e,t)}function Fe(e){return z.get(e)??null}function Ie(){return`pa_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}async function Le(){try{let e=await chrome.storage.local.get([`agentUrl`,`agentToken`,`agentPlatform`,`pairedAgents`]);if(e.pairedAgents&&e.pairedAgents.length>0)return!1;if(e.agentUrl&&e.agentToken){let t=e.agentPlatform||{},n=t.platformName?`${t.platformName} ${t.arch||``}`.trim():`默认代理`,i=Ie(),a=[{id:i,name:n,url:e.agentUrl,token:e.agentToken,pairedAt:new Date().toISOString()}];return await chrome.storage.local.set({pairedAgents:a,activeAgentId:i}),await chrome.storage.local.remove([`agentUrl`,`agentToken`,`agentPlatform`]),r.debug(`[AgentClient] from old formatmigrate agentconfiguration:`,n),!0}}catch(e){r.warn(`[AgentClient] old format migration failed:`,e.message)}return!1}async function Re(){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=e.pairedAgents||[],n=e.activeAgentId;if(!n||t.length===0)return{url:null,token:null,connected:!1,agentId:null};let r=t.find(e=>e.id===n);if(!r){let e=t[0];return await chrome.storage.local.set({activeAgentId:e.id}),{url:e.url,token:e.token,connected:!0,agentId:e.id}}return{url:r.url,token:r.token,connected:!0,agentId:r.id}}async function ze(){return(await chrome.storage.local.get(`pairedAgents`)).pairedAgents||[]}async function Be(){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=e.pairedAgents||[];return!e.activeAgentId||t.length===0?null:t.find(t=>t.id===e.activeAgentId)||t[0]||null}async function B(e){return(await ze()).find(t=>t.id===e)?(await chrome.storage.local.set({activeAgentId:e}),z.delete(e),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}).catch(()=>{}),r.debug(`[AgentClient] switched to agent:`,e),!0):(r.warn(`[AgentClient] switch failed,agent not found:`,e),!1)}async function V(e,n={},r=`POST`,a=6e4){let o=await Re();if(!o.connected)return{success:!1,error:t(`agentClient.agentNotPaired`)};if(o.agentId&&z.get(o.agentId)===!1)return{success:!1,error:t(`agentClient.proxyNotConnected`)};let s=new AbortController,c=setTimeout(()=>s.abort(),a);try{let t={method:r,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${o.token}`,"Accept-Language":i()},signal:s.signal};r!==`GET`&&r!==`HEAD`&&(t.body=JSON.stringify(n));let a=await fetch(`${o.url}${e}`,t);clearTimeout(c);let l=await a.json();return l&&typeof l==`object`&&(l.httpStatus=a.status),l}catch(e){return clearTimeout(c),e.name===`AbortError`?{success:!1,error:t(`agentClient.requestTimeout`,{timeout:a})}:{success:!1,error:t(`agentClient.agentRequestFailed`,{error:e.message})}}}async function H(e,n=3e4){let r=await Re();if(!r.connected)return{success:!1,error:t(`agentClient.agentNotPairedShort`)};if(r.agentId&&z.get(r.agentId)===!1)return{success:!1,error:t(`agentClient.proxyNotConnected`)};let a=new AbortController,o=setTimeout(()=>a.abort(),n);try{let t=await fetch(`${r.url}${e}`,{method:`GET`,headers:{Authorization:`Bearer ${r.token}`,"Accept-Language":i()},signal:a.signal});return clearTimeout(o),await t.json()}catch(e){return clearTimeout(o),e.name===`AbortError`?{success:!1,error:t(`agentClient.requestTimeout`,{timeout:n})}:{success:!1,error:t(`agentClient.agentRequestFailed`,{error:e.message})}}}async function Ve(e){return V(`/api/fs/read`,{path:e})}async function He(e){let t=await V(`/api/fs/stat`,{path:e});return t.success?{success:!0,exists:!0,info:t.info}:t.httpStatus===404?{success:!0,exists:!1}:{success:!1}}async function Ue(e,t){return V(`/api/fs/write`,{path:e,content:t})}async function We(e){return V(`/api/browser/open`,{path:e})}async function Ge(e){return V(`/api/fs/list`,{path:e})}async function Ke(e){return V(`/api/fs/delete`,{path:e})}async function qe(e){return V(`/api/fs/download`,{path:e},`POST`,12e4)}async function Je(e,t=`*`,n=!0,r=200){return V(`/api/fs/search_files`,{path:e,pattern:t,recursive:n,maxResults:r})}async function Ye(e,t,n=null,r=!1,i=!0,a=100,o=2){return V(`/api/fs/search_content`,{path:e,pattern:t,filePattern:n,caseSensitive:r,recursive:i,maxResults:a,contextLines:o})}async function Xe(e,t,n=!1){return V(`/api/exec`,{command:e,cwd:t,force:n})}async function Ze(e,t,n=!1,r=6e5){return V(`/api/exec`,{command:e,cwd:t,wait:!0,force:n},`POST`,r)}async function Qe(e){return V(`/api/exec/stop`,{execId:e})}async function $e(e,n,i,a,o){let s=await Re();if(!s.connected)return a&&a(Error(t(`agentClient.agentNotPairedShort`))),null;if(s.agentId&&z.get(s.agentId)===!1)return a&&a(Error(t(`agentClient.proxyNotConnected`))),null;let c=e;if(s.url)try{let t=new URL(s.url),n=/^ws[s]?:\/\/(0\.0\.0\.0|127\.0\.0\.1|localhost):/;if(n.test(e)){let r=t.protocol===`https:`?`wss:`:`ws:`;c=e.replace(n,`${r}//${t.hostname}:`)}}catch{c=e.replace(`0.0.0.0`,`127.0.0.1`)}let l=c.includes(`?`)?`&`:`?`,u=`${c}${l}token=${encodeURIComponent(s.token)}`;return new Promise((e,t)=>{let o=new WebSocket(u),s=!1;o.onopen=()=>{s||(s=!0,r.debug(`[AgentClient] WebSocket connected:`,c,`(with token)`),e(o))},o.onmessage=e=>{try{let t=JSON.parse(e.data);n&&n(t)}catch{n&&n({type:`raw`,data:e.data})}},o.onclose=()=>{r.debug(`[AgentClient] WebSocket closed`),i&&i()},o.onerror=e=>{if(s)return;s=!0;let n=e instanceof Error?e:Error(`WebSocket 连接失败`);r.error(`[AgentClient] WebSocket error:`,n.message||e),a&&a(n),t(n)}})}async function et(e){return H(e?`/api/mcp/tools?serverId=${encodeURIComponent(e)}`:`/api/mcp/tools`)}async function tt(e,t,n){return V(`/api/mcp/call`,{serverId:e,toolName:t,args:n})}async function nt(){return H(`/api/mcp/servers`)}async function rt(){return H(`/api/rag/collections`)}async function it(e){return V(`/api/rag/search`,e,`POST`,18e4)}async function at(e,t){return V(`/api/rag/collections/${encodeURIComponent(e)}/ingest`,t,`POST`,6e5)}async function ot(){return H(`/api/skill/list`)}async function st(e,t){return V(`/api/skill/run`,{name:e,params:t})}var ct=null,lt=null;function ut(){ct=null,lt=null}async function dt(){return ct&&Date.now()-ct.loadedAt<6e4?ct.agentNames:lt?(await lt,ct.agentNames):(lt=(async()=>{try{let e=await H(`/api/skill/list`),t=e?.success&&e.skills||[];ct={agentNames:new Set(t.filter(e=>e.type===`agent`).map(e=>e.name)),loadedAt:Date.now()}}catch{}finally{lt=null}})(),await lt,ct?.agentNames||new Set)}async function ft(){return H(`/api/skill/agent-prompts`)}async function pt(e){if(!e||e.length===0)return{success:!0,prompts:``};try{let t=await dt(),n=e.filter(e=>t.has(e));return n.length===0?{success:!0,prompts:``}:{success:!0,prompts:(await Promise.all(n.map(e=>mt(e).catch(()=>null)))).filter(e=>e&&e.success&&e.prompt).map(e=>e.prompt).join(`
2
2
 
3
3
  `)}}catch{return{success:!1,prompts:``,error:t(`agentClient.skillPromptFailed`)}}}async function mt(e){return H(`/api/skill/agent-prompt?name=${encodeURIComponent(e)}`)}async function ht(){try{return await V(`/api/agent/restart`,{},`POST`,1e4)}catch(e){return{success:!1,error:e.message}}}async function gt(){try{return await V(`/api/agent/update`,{},`POST`,12e4)}catch(e){return{success:!1,error:e.message}}}async function _t(){try{return await V(`/api/shutdown`,{},`POST`,1e4)}catch(e){return{success:!1,error:e.message}}}async function vt(e={}){return V(`/api/logs/query`,{category:e.category||null,limit:Math.min(e.limit||200,500)})}async function yt(){return H(`/api/trash/list`)}async function bt(e){return V(`/api/trash/restore`,{trashId:e})}async function xt(){let e=await Re();if(!e.url)return!1;try{let t=new URL(e.url).hostname;return t===`localhost`||t===`127.0.0.1`||t===`[::1]`}catch{return!1}}var St=12e4;function Ct(e){return Array.isArray(e)?e.filter(e=>e&&typeof e==`object`).map(e=>({...e,id:e.id||`tc_fb_${crypto.randomUUID().slice(0,8)}`})):[]}var wt=class{constructor(e,t,n={}){this.sessionId=e,this.callId=n.callId||null,this.config=t,this.fullContent=``,this.reasoningContent=``,this.usage=null,this.toolCalls=[],this.isStreaming=!1,this.lastSendTime=0,this._pendingChunk=``,this._streamStarted=!!n.preStarted,this._streamDone=!1,this._sendFn=n.sendFn||(e=>chrome.runtime.sendMessage(e).catch(()=>{})),this._typePrefix=n.typePrefix||``}feedLine(e){if(!e||e.startsWith(`:`))return{type:`ignore`};let t=null;if(e.startsWith(`data:`)&&(t=e.substring(5).replace(/^\s+/,``)),t===null)return{type:`ignore`};if(t===`[DONE]`)return{type:`done`};let n;try{n=JSON.parse(t)}catch{return{type:`ignore`}}n.usage&&(this.usage=n.usage);let i=n.choices?.[0];if(!i)return{type:`ignore`};let a=i.delta||{},o=i.finish_reason;if(a.reasoning_content&&(this.reasoningContent+=a.reasoning_content),a.content&&(this.fullContent+=a.content),a.tool_calls)for(let e of a.tool_calls){let t=e.index||0;if(this.toolCalls[t]||(this.toolCalls[t]={id:e.id||``,type:`function`,function:{name:``,arguments:``}}),e.id&&(this.toolCalls[t].id=e.id),e.function?.name&&(this.toolCalls[t].function.name+=e.function.name),e.function?.arguments){let n=typeof e.function.arguments==`string`?e.function.arguments:JSON.stringify(e.function.arguments);this.toolCalls[t].function.arguments+=n}}return o===`stop`?a.content?{type:`content`,content:a.content}:{type:`done`}:o===`length`?a.content?{type:`content`,content:a.content}:{type:`done`,truncated:!0}:o===`tool_calls`?(r.debug(`[StreamController] tool_calls complete: ${this.toolCalls.length} call with `,this.toolCalls.map(e=>({name:e.function?.name,argsLen:e.function?.arguments?.length}))),{type:`tool_calls`}):a.content?{type:`content`,content:a.content}:a.tool_calls?{type:`accumulating`}:{type:`ignore`}}sendStart(){this._streamStarted||(this._streamStarted=!0,this.isStreaming=!0,this._sendFn({type:this._typePrefix+`STREAM_START`,sessionId:this.sessionId,callId:this.callId}))}sendChunk(e){this._pendingChunk+=e;let t=Date.now(),n=this.config.streamChunkDelay||0;t-this.lastSendTime<n||this._flushChunk()}_flushChunk(){this._pendingChunk&&(this.sendStart(),this._sendFn({type:this._typePrefix+`STREAM_CHUNK`,sessionId:this.sessionId,callId:this.callId,delta:this._pendingChunk}),this._pendingChunk=``,this.lastSendTime=Date.now())}finish(){this._flushChunk(),this.isStreaming=!1;let e=Ct(this.toolCalls);this._sendFn({type:this._typePrefix+`STREAM_DONE`,sessionId:this.sessionId,callId:this.callId,finalContent:this.fullContent,reasoningContent:this.reasoningContent||null,usage:this.usage,toolCalls:e.length>0?e:null})}sendToolCallNotification(){this._flushChunk(),this._sendFn({type:this._typePrefix+`STREAM_TOOL_CALL`,sessionId:this.sessionId,callId:this.callId,toolCalls:this.toolCalls,thinkingContent:this.fullContent})}reset(){this._flushChunk(),this.fullContent=``,this.reasoningContent=``,this.usage=null,this._streamDone=!1,this.toolCalls=[],this._pendingChunk=``,this._streamStarted=!1,this.isStreaming=!1}getResult(){let e=Ct(this.toolCalls);return{content:this.fullContent,reasoningContent:this.reasoningContent||null,usage:this.usage,toolCalls:e.length>0?e:null}}};async function Tt(e,t,n,i=St){let a=new TextDecoder,o=``;t.sendStart();let s=null,c=()=>{s&&=(clearTimeout(s),null)},l=()=>new Promise((e,t)=>{s=setTimeout(()=>{let e=Error(`Stream idle timeout: no SSE data received for ${i}ms`);e.name=`StreamIdleTimeout`,e.idleMs=i,t(e)},i)});try{for(;;){let r,i=()=>{};try{let t=[e.read(),l()];n&&t.push(new Promise((e,t)=>{if(n.aborted){t(new DOMException(`Aborted`,`AbortError`));return}let r=()=>{t(new DOMException(`Aborted`,`AbortError`))};n.addEventListener(`abort`,r,{once:!0}),i=()=>n.removeEventListener(`abort`,r)})),r=await Promise.race(t)}finally{c(),i()}let{done:s,value:u}=r;if(s)break;o+=a.decode(u,{stream:!1});let d=o.split(`
4
4
  `);o=d.pop()||``;for(let e of d){let n=t.feedLine(e.trim());if(n.type===`content`)t.sendChunk(n.content);else if(n.type===`tool_calls`){let e=Ct(t.toolCalls);return t.toolCalls=e,t._flushChunk(),(!t.config||t.config.streamEnabled!==!1)&&t._sendFn({type:t._typePrefix+`STREAM_TOOL_CALL`,sessionId:t.sessionId,callId:t.callId,toolCalls:e,thinkingContent:t.fullContent}).catch(()=>{}),{status:`tool_calls`,...t.getResult()}}else n.type===`done`&&(t._streamDone=!0)}}if(o.trim()){let e=t.feedLine(o.trim());if(e.type===`content`)t.sendChunk(e.content);else if(e.type===`tool_calls`)return{status:`tool_calls`,...t.getResult()}}return t.finish(),{status:`done`,...t.getResult()}}catch(n){if(c(),n.name===`AbortError`)throw r.debug(`[StreamController] streamingread was already cancel`),n;if(n.name===`StreamIdleTimeout`){r.warn(`[StreamController] streamingread idle timeout (${n.idleMs}ms no data),cancel reader`);try{await e.cancel()}catch{}throw t.finish(),n}throw r.error(`[StreamController] streamingread error:`,n.message),t.finish(),n}}function Et(e,t,n,r,i){chrome.runtime.sendMessage({type:`AGENT_STREAM`,sessionId:e,execId:t,toolCallId:n,streamType:r,data:i}).catch(()=>{})}function U(e,t,n,r){chrome.runtime.sendMessage({type:`AGENT_STREAM_DONE`,sessionId:e,execId:t,toolCallId:n,exitCode:r}).catch(()=>{})}e(`zh`,{preselector:{nodeName:`工具预筛选`,reasonFewTools:`工具数量少`,reasonExtractFailed:`无法提取用户问题`,reasonApiFailed:`API 请求失败: {status}`,reasonEmptyResult:`模型返回空数组`,reasonNoMatch:`筛选结果无匹配`}}),e(`en`,{preselector:{nodeName:`Tool Pre-filter`,reasonFewTools:`Too few tools`,reasonExtractFailed:`Unable to extract user question`,reasonApiFailed:`API request failed: {status}`,reasonEmptyResult:`Model returned empty array`,reasonNoMatch:`No matching results after filtering`}});function Dt(e,t=2e3){let n=me(e);return n.length>t?n.substring(0,t)+`...`:n}function Ot(e){let t=e.filter(e=>e.role===`user`);return t.length===0?``:Dt(t[t.length-1].content)}function kt(e){let t=e.filter(e=>e.role===`user`||e.role===`assistant`);if(t.length===0)return[];let n=t.map((e,t)=>({m:e,i:t})).filter(e=>e.m.role===`user`).pop()?.i;return n===void 0?[]:t.slice(0,n).slice(-4).map(e=>({role:e.role,content:Dt(e.content,1e3)}))}function At(e){return`You are an intelligent assistant. Based on the user's question, determine whether tools are needed to complete the task.
@@ -345,7 +345,7 @@ Image recognition analysis failed: {error}`,dialogAccept:`auto-accept`,dialogDis
345
345
  {list}`,knowledgeListItem:`- {name} (id: {id}): {docs} documents · {chunks} chunks`,knowledgeListFailed:`Failed to list knowledge bases: {error}`,knowledgeSearchDisabled:`This knowledge base is disabled and cannot be searched. Ask the user to enable it in the extension settings "Knowledge" tab and retry.`,knowledgeIngestDisabled:`This knowledge base is disabled; ingest is not allowed. Ask the user to enable it in the extension settings "Knowledge" tab and retry.`}});var Br=new Map,Vr=new Set,Hr=new Set,Ur=new Map,Wr=null,Gr=150,Kr=3,qr=20;function Jr(e,t=Gr){return!e||typeof e!=`string`||e.length<=t?e:e.slice(0,t-3)+`...`}function Yr(e,t=0){if(!e||typeof e!=`object`||t>=Kr)return e;let n={};for(let[r,i]of Object.entries(e)){if(!i||typeof i!=`object`){n[r]=i;continue}let e={...i};delete e.$schema,delete e.$ref,delete e.definitions,delete e.additionalProperties,e.description&&=Jr(e.description),e.properties&&=Yr(e.properties,t+1),e.items&&typeof e.items==`object`&&(e.items.properties&&(e.items.properties=Yr(e.items.properties,t+1)),e.items.description&&(e.items.description=Jr(e.items.description))),n[r]=e}return n}function Xr(e){if(!e||typeof e!=`object`)return{type:`object`,properties:{}};let{$schema:n,$ref:r,definitions:i,additionalProperties:a,...o}=e;if(o.type||=`object`,o.description&&=Jr(o.description),o.properties){o.properties=Yr(o.properties,0);let e=Object.keys(o.properties);if(e.length>qr){let n=e.slice(0,qr),r=e.slice(qr),i={};n.forEach(e=>{i[e]=o.properties[e]}),i.additionalParams={type:`object`,description:t(`toolExec.additionalParamsDesc`,{count:r.length,names:r.join(`, `).slice(0,100)})},o.properties=i}}return o}Promise.resolve();async function Zr(){let e=Wr,t;Wr=new Promise(e=>{t=e}),await e;try{let{mcpEnabled:e}=await chrome.storage.local.get([`mcpEnabled`]);if(e!==!0)return r.debug(`[Background] MCP globaltoggleclosed,skip toolload`),0;Qr();let[t,n]=await Promise.all([et(),nt()]);if(!t.success||!t.tools||t.tools.length===0)return r.debug(`[Background] no available MCP tool`),0;let i=new Set;if(n?.servers)for(let e of n.servers)e.enabled===!1&&i.add(e.id);let a=0;for(let e of t.tools){if(i.has(e.serverId)){r.debug(`[Background] skip disabled MCP server "${e.serverName}" tool: ${e.name}`);continue}let t=`mcp_${e.serverId}_${e.name}`;if(Hr.has(t))continue;let n={id:t,category:`mcp`,execution:`background`,parallelizable:!0,requiresConfirmation:!1,type:`function`,function:{name:t,description:Jr(`[MCP:${e.serverName}] ${e.description||e.name}`,200),parameters:Xr(e.inputSchema)}};f.push(n),m.push({id:n.id,type:n.type,function:n.function}),d[t]=`background`,Ui[t]=async(t,n)=>{let r=await tt(e.serverId,e.name,t);return{success:r.success,content:r.content||r.error||``,tool_call_id:n}},Hr.add(t),Ur.set(t,{serverId:e.serverId,serverName:e.serverName,toolName:e.name}),a++}oi();let o=t.tools.filter(e=>!i.has(e.serverId)).map(e=>({id:`mcp_${e.serverId}_${e.name}`,name:e.name,description:`[MCP:${e.serverName}] ${e.description||e.name}`,category:`mcp`,execution:`background`,parallelizable:!0,requiresConfirmation:!1,enabled:!0,serverId:e.serverId,serverName:e.serverName}));return await chrome.storage.local.set({mcpTools:o}),r.debug(`[Background] loaded ${a} MCP tool`),a}catch(e){return r.warn(`[Background] load MCP tool failed (Agent may not be supported MCP):`,e.message),0}finally{t()}}function Qr(){for(let e of Hr){let t=f.findIndex(t=>t.id===e);t>=0&&f.splice(t,1),t=m.findIndex(t=>t.id===e),t>=0&&m.splice(t,1),delete d[e],delete Ui[e]}Hr.clear(),Ur.clear(),oi(),chrome.storage.local.remove(`mcpTools`)}async function $r(){let e=Wr,t;Wr=new Promise(e=>{t=e}),await e;try{Qr()}finally{t()}}function ei(e){return Ur.get(e)||null}function ti(e){if(!e)return[];let t=e instanceof Set?e:new Set(e);if(t.size===0)return[];let n=[];for(let[e,r]of Ur)t.has(r.serverId)&&n.push(e);return n}var ni=new Map;function ri(e,t){e&&(Array.isArray(t)&&t.length>0?ni.set(e,[...t]):ni.delete(e))}function ii(e){return e&&ni.get(e)||null}function ai(e,t,n){if(!Array.isArray(n)||n.length===0)return e;let r=new Set(ti(n));if(r.size===0)return e;let i=new Set(e.map(e=>e.id)),a=[...e];for(let e of t)r.has(e.id)&&!i.has(e.id)&&a.push(e);return a}function oi(){for(let e of Object.keys(Wi))delete Wi[e];s.clear(),a.clear();for(let e of f)e.execution===`background`&&Ui[e.id]&&(Wi[e.id]=Ui[e.id]),e.parallelizable&&s.add(e.id),e.requiresConfirmation&&a.add(e.id)}var si=new Set,ci=null;async function li(e,n){let{query:r,collectionId:i,topK:a}=e||{};if(!r||!String(r).trim())return Y(!1,t(`toolExec.knowledgeQueryRequired`),{tool_call_id:n});let o={query:String(r)};if(i){let e=await ui(i,`toolExec.knowledgeSearchDisabled`);if(e)return Y(!1,e,{tool_call_id:n});o.collectionIds=[i]}a&&(o.topK=a);let s=await it(o);if(!s||s.success!==!0)return Y(!1,t(`toolExec.knowledgeSearchFailed`,{error:s?.error||t(`toolExec.unknownError`)}),{tool_call_id:n});let c=Array.isArray(s.results)?s.results:[];if(c.length===0)return Y(!0,t(`toolExec.knowledgeSearchNoResult`,{query:String(r)}),{tool_call_id:n});let l=c.map((e,n)=>{let r=e.metadata||{},i=r.documentName||r.source||``,a=i?t(`toolExec.knowledgeSourcePart`,{source:i}):``,o=typeof e.score==`number`?e.score.toFixed(3):`-`;return`${t(`toolExec.knowledgeResultHeader`,{index:n+1,score:o,sourcePart:a})}\n${e.content||``}`});return Y(!0,t(`toolExec.knowledgeSearchResult`,{count:c.length,results:l.join(`
346
346
 
347
347
  `)}),{tool_call_id:n})}async function ui(e,n){try{let r=await rt();if(!r||r.success!==!0)return null;let i=(Array.isArray(r.collections)?r.collections:[]).find(t=>t.id===e);if(i&&i.enabled===!1)return t(n)}catch{}return null}async function di(e,n){let{collectionId:r,type:i,content:a,name:o,metadata:s}=e||{};if(!r||!i||!a)return Y(!1,t(`toolExec.knowledgeIngestParamsRequired`),{tool_call_id:n});let c=await ui(r,`toolExec.knowledgeIngestDisabled`);if(c)return Y(!1,c,{tool_call_id:n});let l;if(i===`text`)l={type:i,content:a,name:o,metadata:s};else if(i===`file`)l={type:i,path:a,metadata:s};else if(i===`url`)l={type:i,url:a,metadata:s};else return Y(!1,t(`toolExec.knowledgeIngestBadType`,{type:i}),{tool_call_id:n});let u=await at(r,l);return!u||u.success!==!0?Y(!1,t(`toolExec.knowledgeIngestFailed`,{error:u?.error||t(`toolExec.unknownError`)}),{tool_call_id:n}):Y(!0,t(`toolExec.knowledgeIngestSuccess`,{name:u.name||o||``,chunks:u.chunkCount||0}),{tool_call_id:n})}async function fi(e,n){let r=await rt();if(!r||r.success!==!0)return Y(!1,t(`toolExec.knowledgeListFailed`,{error:r?.error||t(`toolExec.unknownError`)}),{tool_call_id:n});let i=(Array.isArray(r.collections)?r.collections:[]).filter(e=>e.enabled!==!1);if(i.length===0)return Y(!0,t(`toolExec.knowledgeListEmpty`),{tool_call_id:n});let a=i.map(e=>t(`toolExec.knowledgeListItem`,{name:e.name||e.id,id:e.id,docs:e.documentCount||0,chunks:e.chunkCount||0}));return Y(!0,t(`toolExec.knowledgeListResult`,{count:i.length,list:a.join(`
348
- `)}),{tool_call_id:n})}var pi={knowledge_search:li,knowledge_ingest:di,knowledge_list:fi};async function mi(){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=(e.pairedAgents||[]).find(t=>t.id===e.activeAgentId);if(!t)return!1;try{let e=new AbortController,n=setTimeout(()=>e.abort(),5e3),r=await fetch(`${t.url}/api/status`,{signal:e.signal,cache:`no-cache`});return clearTimeout(n),r.ok?(await r.json())?.ragAvailable===!0:!1}catch(e){return r.debug(`[Background] RAG availability check failed:`,e.message),!1}}async function hi(){let e=ci,t;ci=new Promise(e=>{t=e}),await e;try{let{ragEnabled:e}=await chrome.storage.local.get([`ragEnabled`]);if(e!==!0)return gi(),r.debug(`[Background] RAG globaltoggleclosed,skip toolload`),0;if(gi(),!await mi())return r.debug(`[Background] Agent RAG not available, skip tool load`),0;for(let e of zr)f.push(e),m.push({id:e.id,type:e.type,function:e.function}),d[e.id]=`background`,Ui[e.id]=pi[e.id],si.add(e.id);return oi(),_i(),r.debug(`[Background] loaded ${si.size} RAG tool`),si.size}catch(e){return r.warn(`[Background] load RAG tool failed:`,e.message),0}finally{t()}}function gi(){for(let e of si){let t=f.findIndex(t=>t.id===e);t>=0&&f.splice(t,1),t=m.findIndex(t=>t.id===e),t>=0&&m.splice(t,1),delete d[e],delete Ui[e]}si.clear(),oi(),_i()}function _i(){let e=zr.filter(e=>si.has(e.id)).map(e=>({id:e.id,name:e.function?.name||e.id,description:e.function?.description||``,category:e.category||`knowledge`,execution:e.execution||`background`,parallelizable:e.parallelizable!==!1,requiresConfirmation:e.requiresConfirmation||!1,enabled:!0}));chrome.storage.local.set({ragTools:e}).catch(()=>{})}async function vi(){let e=ci,t;ci=new Promise(e=>{t=e}),await e;try{gi()}finally{t()}}var yi=`sensitiveAuditLog`,bi=100;async function xi(e,t,n={}){try{let r=(await chrome.storage.local.get([yi]))[yi]||[];r.unshift({timestamp:new Date().toISOString(),category:e,action:t,details:n}),r.length>bi&&(r.length=bi),await chrome.storage.local.set({[yi]:r})}catch(e){console.warn(`[Background] Audit log write failed:`,e)}}var Si=new Map,Ci=3e4;function wi(e){e?Si.delete(e):Si.clear()}async function Ti(){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=(e.pairedAgents||[]).find(t=>t.id===e.activeAgentId);if(!t)return Si.clear(),Pe(`__global__`,!1),!1;let n=Date.now(),r=Si.get(t.id);if(r&&r.connected!==null&&n-r.checkedAt<Ci)return r.connected;try{let e=new AbortController,r=setTimeout(()=>e.abort(),5e3),i=await fetch(`${t.url}/api/status`,{signal:e.signal,cache:`no-cache`});clearTimeout(r);let a=i.ok;return Si.set(t.id,{connected:a,checkedAt:n}),Pe(t.id,a),console.log(`[Background] Agent connectivity check:`,a?`reachable`:`unreachable (status=`+i.status+`)`),a}catch(e){return Si.set(t.id,{connected:!1,checkedAt:n}),Pe(t.id,!1),console.log(`[Background] Agent connectivity check: unreachable (`+(e.name===`AbortError`?`timeout`:e.message)+`)`),!1}}async function Ei(e=null,n=null,r=null,i=null,a=null){return new Promise(o=>{let s=`agentEnabledTools_${n||`default`}`,c=`agentMcpClosedServers_${n||`default`}`;chrome.storage.local.get([s,`enabledTools`,`enableImageInput`,`pairedAgents`,`enableToolPreselect`,c],async n=>{let l=n[s]||n.enabledTools;(!l||!Array.isArray(l)||l.length===0)&&(l=m.map(e=>e.id),console.log(`[Background] not foundtool configuration,using default value (all enabled)`));let u={open_tab:`manage_tab`,switch_tab:`manage_tab`,close_tab:`manage_tab`,reload_tab:`manage_tab`,navigate_back_forward:`manage_tab`,search_bookmarks:`search_browser_data`,search_history:`search_browser_data`,agent_list_trash:`agent_trash`,agent_restore_trash:`agent_trash`,ai_agent_list:`manage_agent`,ai_agent_switch:`manage_agent`,manage_ai_agent:`manage_agent`,dispatch_sub_agent:`dispatch_task`,search_conversation_memory:`search_chats`,preview_ui_prototype:`preview_ui`,agent_read_file:`agent_file`,agent_write_file:`agent_file`,agent_list_dir:`agent_file`,agent_delete_file:`agent_file`,agent_download_file:`agent_file`,agent_search_files:`agent_search`,agent_search_content:`agent_search`,agent_skill_load:`agent_skill`,agent_workflow_run:`agent_skill`,click_element:`interact_element`,hover_element:`interact_element`,agent_exec_command:`agent_exec`,get_page_content:`page_content`,get_iframe_content:`iframe_content`,get_browser_info:`browser_info`,get_tabs:`list_tabs`,wait_for_element:`wait_element`,wait_for_navigation:`wait_navigation`,query_interactive_elements:`query_elements`,scroll_and_collect:`scroll_collect`,drag_and_drop:`drag_drop`,show_notification:`notify`,generate_qrcode:`qrcode`,clear_page_data:`clear_data`,search_chat_history:`search_chats`,ui_prototype:`preview_ui`},d=!1;l=l.map(e=>u[e]?(d=!0,u[e]):e),l=[...new Set(l)],d&&console.log(`[Background] detected old tool name,migrated to merged new tool name`);let f=e?l.filter(t=>e.includes(t)):l;if(e&&console.log(`[Background] tool filter: ${l.length} global → ${f.length} final`),r!=null&&Array.isArray(r)&&r.length>0&&(f.includes(`agent_skill`)||(f.push(`agent_skill`),console.log(`[Background] auto-adding skill tool: agent_skill`))),si.size>0){let{ragToolsIntroduced:e}=await chrome.storage.local.get([`ragToolsIntroduced`]);if(e!==!0){for(let e of si)f.includes(e)||f.push(e);console.log(`[Background] auto-adding ${si.size} RAG knowledge tools (not yet introduced)`)}}let p=n.enableImageInput===!0,h=n.enableToolPreselect===!0;console.log(`[Background] getTools - enableToolPreselect:`,h);let g=await Ti(),_=(n.pairedAgents||[]).length;console.log(`[Background] tool configuration: ${f.length} enable, Agent=${g}, image recognition=${p}`);let{mcpEnabled:v,skillsEnabled:y}=await chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`]),b=new Set(Array.isArray(n[c])?n[c]:[]),x=new Set(Array.isArray(a)?a:[]),S=new Set(Array.isArray(i)?i:[]),C=m.filter(e=>e.id.startsWith(`mcp_`)?!0:f.includes(e.id)).filter(e=>{if(e.id.startsWith(`agent_`)&&!g||e.id===`manage_agent`&&_<2||e.id===`agent_skill`&&y===!1)return!1;if(e.id.startsWith(`mcp_`)){if(v!==!0||!g||!Hr.has(e.id))return!1;let t=Ur.get(e.id);if(t){if(S.has(t.serverId))return!0;if(b.has(t.serverId)||x.has(t.serverId))return!1}return!0}return!(e.id.startsWith(`knowledge_`)&&(!si.has(e.id)||!g))}),w=C.map(e=>{let r=JSON.parse(JSON.stringify(e));if(e.id===`capture_page`){let e=r.function.parameters.properties.action;p||(e.enum=[`download`],e.description=t(`toolExec.captureDownloadAction`),e.default=`download`,r.function.description=t(`toolExec.captureDownloadDesc`))}if(e.id===`plan_task`){let e=n.preselectMinToolCount||10,i=h&&C.length>e;if(console.log(`[Background] getTools - processing plan_task, enableToolPreselect:`,h,`toolCount:`,C.length,`threshold:`,e,`shouldAdd:`,i),i){r.function.description=`任务规划与拆解,将复杂任务分解为子任务。重要:必须为每个子任务的 requiredTools 字段指定所需工具ID列表,子任务仅继承此处指定的工具。`;let e=r.function.parameters.properties.subtasks.items.properties;e.requiredTools={type:`array`,items:{type:`string`},description:t(`toolExec.requiredToolsDesc`,{tools:C.map(e=>e.id).join(`, `)})};let n=r.function.parameters.properties.subtasks.items.required;n.includes(`requiredTools`)||n.push(`requiredTools`),console.log(`[Background] getTools - added requiredTools to plan_task (required)`)}}return r});console.log(`[Background] finalavailable tools: ${w.length} `),o(w)})})}chrome.storage?.onChanged?.addListener?.(e=>{if(e.mcpEnabled){let t=e.mcpEnabled.newValue===!0;r.debug(`[Background] MCP globaltoggle changed:`,t),t?Zr().then(e=>{r.debug(`[Background] MCP tools re-load:`,e,``)}):$r().then(()=>{r.debug(`[Background] MCP all toolsunload`)})}if(e.skillsEnabled&&console.log(`[Background] Skill global toggle changed:`,e.skillsEnabled.newValue!==!1),e.ragEnabled){let t=e.ragEnabled.newValue===!0;r.debug(`[Background] RAG globaltoggle changed:`,t),t?hi().then(e=>{r.debug(`[Background] RAG tools re-load:`,e,``)}):vi().then(()=>{r.debug(`[Background] RAG all toolsunload`)})}});async function Di(e,n,r=null){let{action:i=`both`,tabId:a,format:o=`jpeg`,quality:s=60,visionMaxDim:c=1024,visionQuality:l=65}=e;try{let e,u,d=``,f=``;if(a)try{let t=await chrome.tabs.get(a);e=t.id,u=t.windowId,d=t.url||``,f=t.title||``,await chrome.tabs.update(e,{active:!0}),await new Promise(e=>setTimeout(e,300))}catch{return Y(!1,t(`toolExec.tabNotExistOrAccessible`,{tabId:a}),{tool_call_id:n})}else{let r=await chrome.tabs.query({active:!0,currentWindow:!0});if(!r.length)return Y(!1,t(`toolExec.cannotGetCurrentTab`),{tool_call_id:n});e=r[0].id,u=r[0].windowId,d=r[0].url||``,f=r[0].title||``}console.log(`[Background] taking screenshot: tabId=`,e,`url=`,d,`action=`,i,`format=`,o,`quality=`,s,`visionMaxDim=`,c,`visionQuality=`,l);let p=await new Promise((e,t)=>{chrome.tabs.captureVisibleTab(u,{format:o,quality:s},n=>{chrome.runtime.lastError?t(Error(chrome.runtime.lastError.message)):e(n)})}),m=(p.length/1024).toFixed(1);console.log(`[Background] screenshot complete,size:`,m,`KB`),chrome.storage.local.set({_lastVisionScreenshot:{dataUrl:p,sizeKB:m,url:d,title:f,timestamp:Date.now()}}).catch(()=>{});let h=i===`download`||i===`both`,g=i===`analyze`||i===`both`;if(h&&yn(p,o),g){let e=await Oi(p,c,l/100),i=(e.length/1024).toFixed(1);console.log(`[Background] screenshot compressed size:`,i,`KB (maxDim:`,c,`quality:`,l,`)`);let a=await ki(e,d,f,r);return h?Y(!0,`${t(`toolExec.screenshotDownloaded`,{size:m})}。\n\n${a}`,{tool_call_id:n}):Y(!0,a,{tool_call_id:n})}let _=(p.length/1024/1024).toFixed(2);return Y(!0,t(`toolExec.screenshotSuccess`,{size:_,format:o===`png`?`png`:`jpg`,quality:s}),{tool_call_id:n})}catch(e){return Y(!1,t(`toolExec.screenshotFailed`,{error:e.message}),{tool_call_id:n})}}async function Oi(e,t=1024,n=.65){try{let r=await(await fetch(e)).blob(),i=await createImageBitmap(r),{width:a,height:o}=i;(a>t||o>t)&&(a>o?(o=Math.round(t/a*o),a=t):(a=Math.round(t/o*a),o=t));let s=new OffscreenCanvas(a,o);s.getContext(`2d`).drawImage(i,0,0,a,o);let c=await s.convertToBlob({type:`image/jpeg`,quality:n});return new Promise((e,t)=>{let n=new FileReader;n.onloadend=()=>e(n.result),n.onerror=t,n.readAsDataURL(c)})}catch(t){return console.warn(`[Background] image compression failed, using original screenshot:`,t.message),e}}async function ki(e,n,r,i=null){let a=await new Promise(e=>{chrome.storage.local.get([`imageApiBase`,`imageApiKey`,`imageModelName`,`apiBase`,`apiKey`,`modelName`,`streamEnabled`],e)}),o=a.imageApiBase||a.apiBase,s=a.imageApiKey||a.apiKey,c=a.imageModelName||a.modelName,l=a.streamEnabled!==!1;if(!o||!s)return console.log(`[Background] image recognition API not configured,returnscreenshotbasicinfo`),t(`toolExec.screenshotBasicInfo`,{title:r,url:n});console.log(`[Background] calling image recognition API to analyze screenshot,model:`,c,`endpoint:`,o,`streaming:`,l);let u=t(`toolExec.visionPrompt`,{title:r,url:n}),d=new AbortController,f=setTimeout(()=>d.abort(),6e4);try{let t={model:c,messages:[{role:`user`,content:[{type:`text`,text:u},{type:`image_url`,image_url:{url:e,detail:`auto`}}]}],max_tokens:2e3};l&&(t.stream=!0);let a=await fetch(`${o}/chat/completions`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${s}`},body:JSON.stringify(t),signal:d.signal});if(clearTimeout(f),!a.ok){let e=await a.text().catch(()=>``);return console.error(`[Background] image recognition API request failed:`,a.status,e),`页面截图已获取。\n\n- 页面标题: ${r}\n- 页面地址: ${n}\n\n图片识别分析失败(API 返回 ${a.status}),请检查图片识别 API 配置。`}let p;return p=l?await Ai(a,d,i):(await a.json()).choices?.[0]?.message?.content,p?(console.log(`[Background] image recognition analysis complete,result length:`,p.length),`页面截图分析结果:\n\n**页面**: ${r}\n**地址**: ${n}\n\n${p}`):(console.error(`[Background] image recognition API result is empty`),`页面截图已获取。\n\n- 页面标题: ${r}\n- 页面地址: ${n}\n\n图片识别返回结果为空,请重试。`)}catch(e){return clearTimeout(f),console.error(`[Background] image recognition API call exception:`,e.message),e.name===`AbortError`?`页面截图已获取。\n\n- 页面标题: ${r}\n- 页面地址: ${n}\n\n图片识别分析超时(60秒),请检查图片识别 API 是否可用或尝试重新截图。`:t(`toolExec.screenshotAnalysisError`,{title:r,url:n,error:e.message})}}async function Ai(e,t,n=null){let r=e.body.getReader(),i=new TextDecoder,a=``,o=``;try{for(;;){let e;e=t&&t.signal?await Promise.race([r.read(),new Promise((e,n)=>{if(t.signal.aborted){n(new DOMException(`Aborted`,`AbortError`));return}t.signal.addEventListener(`abort`,()=>n(new DOMException(`Aborted`,`AbortError`)),{once:!0})})]):await r.read();let{done:s,value:c}=e;if(s)break;a+=i.decode(c,{stream:!1});let l=a.split(`
348
+ `)}),{tool_call_id:n})}var pi={knowledge_search:li,knowledge_ingest:di,knowledge_list:fi};async function mi(){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=(e.pairedAgents||[]).find(t=>t.id===e.activeAgentId);if(!t)return!1;try{let e=new AbortController,n=setTimeout(()=>e.abort(),5e3),r=await fetch(`${t.url}/api/status`,{signal:e.signal,cache:`no-cache`});return clearTimeout(n),r.ok?(await r.json())?.ragAvailable===!0:!1}catch(e){return r.debug(`[Background] RAG availability check failed:`,e.message),!1}}async function hi(){let e=ci,t;ci=new Promise(e=>{t=e}),await e;try{let{ragEnabled:e}=await chrome.storage.local.get([`ragEnabled`]);if(e!==!0)return gi(),r.debug(`[Background] RAG globaltoggleclosed,skip toolload`),0;if(gi(),!await mi())return r.debug(`[Background] Agent RAG not available, skip tool load`),0;for(let e of zr)f.push(e),m.push({id:e.id,type:e.type,function:e.function}),d[e.id]=`background`,Ui[e.id]=pi[e.id],si.add(e.id);return oi(),_i(),r.debug(`[Background] loaded ${si.size} RAG tool`),si.size}catch(e){return r.warn(`[Background] load RAG tool failed:`,e.message),0}finally{t()}}function gi(){for(let e of si){let t=f.findIndex(t=>t.id===e);t>=0&&f.splice(t,1),t=m.findIndex(t=>t.id===e),t>=0&&m.splice(t,1),delete d[e],delete Ui[e]}si.clear(),oi(),_i()}function _i(){let e=zr.filter(e=>si.has(e.id)).map(e=>({id:e.id,name:e.function?.name||e.id,description:e.function?.description||``,category:e.category||`knowledge`,execution:e.execution||`background`,parallelizable:e.parallelizable!==!1,requiresConfirmation:e.requiresConfirmation||!1,enabled:!0}));chrome.storage.local.set({ragTools:e}).catch(()=>{})}async function vi(){let e=ci,t;ci=new Promise(e=>{t=e}),await e;try{gi()}finally{t()}}var yi=`sensitiveAuditLog`,bi=100;async function xi(e,t,n={}){try{let r=(await chrome.storage.local.get([yi]))[yi]||[];r.unshift({timestamp:new Date().toISOString(),category:e,action:t,details:n}),r.length>bi&&(r.length=bi),await chrome.storage.local.set({[yi]:r})}catch(e){console.warn(`[Background] Audit log write failed:`,e)}}var Si=new Map,Ci=3e4;function wi(e){e?Si.delete(e):Si.clear()}async function Ti(){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=(e.pairedAgents||[]).find(t=>t.id===e.activeAgentId);if(!t)return Si.clear(),Pe(`__global__`,!1),!1;let n=Date.now(),r=Si.get(t.id);if(r&&r.connected!==null&&n-r.checkedAt<Ci)return r.connected;try{let e=new AbortController,r=setTimeout(()=>e.abort(),5e3),i=await fetch(`${t.url}/api/status`,{signal:e.signal,cache:`no-cache`});clearTimeout(r);let a=i.ok;return Si.set(t.id,{connected:a,checkedAt:n}),Pe(t.id,a),console.log(`[Background] Agent connectivity check:`,a?`reachable`:`unreachable (status=`+i.status+`)`),a}catch(e){return Si.set(t.id,{connected:!1,checkedAt:n}),Pe(t.id,!1),console.log(`[Background] Agent connectivity check: unreachable (`+(e.name===`AbortError`?`timeout`:e.message)+`)`),!1}}async function Ei(e=null,n=null,r=null,i=null,a=null){return new Promise(o=>{let s=`agentEnabledTools_${n||`default`}`,c=`agentMcpClosedServers_${n||`default`}`;chrome.storage.local.get([s,`enabledTools`,`enableImageInput`,`pairedAgents`,`enableToolPreselect`,c],async n=>{let l=n[s];Array.isArray(l)||(l=n.enabledTools),Array.isArray(l)||(l=m.map(e=>e.id),console.log(`[Background] tool configuration not found, using default value (all enabled)`));let u={open_tab:`manage_tab`,switch_tab:`manage_tab`,close_tab:`manage_tab`,reload_tab:`manage_tab`,navigate_back_forward:`manage_tab`,search_bookmarks:`search_browser_data`,search_history:`search_browser_data`,agent_list_trash:`agent_trash`,agent_restore_trash:`agent_trash`,ai_agent_list:`manage_agent`,ai_agent_switch:`manage_agent`,manage_ai_agent:`manage_agent`,dispatch_sub_agent:`dispatch_task`,search_conversation_memory:`search_chats`,preview_ui_prototype:`preview_ui`,agent_read_file:`agent_file`,agent_write_file:`agent_file`,agent_list_dir:`agent_file`,agent_delete_file:`agent_file`,agent_download_file:`agent_file`,agent_search_files:`agent_search`,agent_search_content:`agent_search`,agent_skill_load:`agent_skill`,agent_workflow_run:`agent_skill`,click_element:`interact_element`,hover_element:`interact_element`,agent_exec_command:`agent_exec`,get_page_content:`page_content`,get_iframe_content:`iframe_content`,get_browser_info:`browser_info`,get_tabs:`list_tabs`,wait_for_element:`wait_element`,wait_for_navigation:`wait_navigation`,query_interactive_elements:`query_elements`,scroll_and_collect:`scroll_collect`,drag_and_drop:`drag_drop`,show_notification:`notify`,generate_qrcode:`qrcode`,clear_page_data:`clear_data`,search_chat_history:`search_chats`,ui_prototype:`preview_ui`},d=!1;l=l.map(e=>u[e]?(d=!0,u[e]):e),l=[...new Set(l)],d&&console.log(`[Background] detected old tool name,migrated to merged new tool name`);let f=e?l.filter(t=>e.includes(t)):l;if(e&&console.log(`[Background] tool filter: ${l.length} global → ${f.length} final`),r!=null&&Array.isArray(r)&&r.length>0&&(f.includes(`agent_skill`)||(f.push(`agent_skill`),console.log(`[Background] auto-adding skill tool: agent_skill`))),si.size>0){let{ragToolsIntroduced:e}=await chrome.storage.local.get([`ragToolsIntroduced`]);if(e!==!0){for(let e of si)f.includes(e)||f.push(e);console.log(`[Background] auto-adding ${si.size} RAG knowledge tools (not yet introduced)`)}}let p=n.enableImageInput===!0,h=n.enableToolPreselect===!0;console.log(`[Background] getTools - enableToolPreselect:`,h);let g=await Ti(),_=(n.pairedAgents||[]).length;console.log(`[Background] tool configuration: ${f.length} enable, Agent=${g}, image recognition=${p}`);let{mcpEnabled:v,skillsEnabled:y}=await chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`]),b=new Set(Array.isArray(n[c])?n[c]:[]),x=new Set(Array.isArray(a)?a:[]),S=new Set(Array.isArray(i)?i:[]),C=m.filter(e=>e.id.startsWith(`mcp_`)?!0:f.includes(e.id)).filter(e=>{if(e.id.startsWith(`agent_`)&&!g||e.id===`manage_agent`&&_<2||e.id===`agent_skill`&&y===!1)return!1;if(e.id.startsWith(`mcp_`)){if(v!==!0||!g||!Hr.has(e.id))return!1;let t=Ur.get(e.id);if(t){if(S.has(t.serverId))return!0;if(b.has(t.serverId)||x.has(t.serverId))return!1}return!0}return!(e.id.startsWith(`knowledge_`)&&(!si.has(e.id)||!g))}),w=C.map(e=>{let r=JSON.parse(JSON.stringify(e));if(e.id===`capture_page`){let e=r.function.parameters.properties.action;p||(e.enum=[`download`],e.description=t(`toolExec.captureDownloadAction`),e.default=`download`,r.function.description=t(`toolExec.captureDownloadDesc`))}if(e.id===`plan_task`){let e=n.preselectMinToolCount||10,i=h&&C.length>e;if(console.log(`[Background] getTools - processing plan_task, enableToolPreselect:`,h,`toolCount:`,C.length,`threshold:`,e,`shouldAdd:`,i),i){r.function.description=`任务规划与拆解,将复杂任务分解为子任务。重要:必须为每个子任务的 requiredTools 字段指定所需工具ID列表,子任务仅继承此处指定的工具。`;let e=r.function.parameters.properties.subtasks.items.properties;e.requiredTools={type:`array`,items:{type:`string`},description:t(`toolExec.requiredToolsDesc`,{tools:C.map(e=>e.id).join(`, `)})};let n=r.function.parameters.properties.subtasks.items.required;n.includes(`requiredTools`)||n.push(`requiredTools`),console.log(`[Background] getTools - added requiredTools to plan_task (required)`)}}return r});console.log(`[Background] finalavailable tools: ${w.length} `),o(w)})})}chrome.storage?.onChanged?.addListener?.(e=>{if(e.mcpEnabled){let t=e.mcpEnabled.newValue===!0;r.debug(`[Background] MCP globaltoggle changed:`,t),t?Zr().then(e=>{r.debug(`[Background] MCP tools re-load:`,e,``)}):$r().then(()=>{r.debug(`[Background] MCP all toolsunload`)})}if(e.skillsEnabled&&console.log(`[Background] Skill global toggle changed:`,e.skillsEnabled.newValue!==!1),e.ragEnabled){let t=e.ragEnabled.newValue===!0;r.debug(`[Background] RAG globaltoggle changed:`,t),t?hi().then(e=>{r.debug(`[Background] RAG tools re-load:`,e,``)}):vi().then(()=>{r.debug(`[Background] RAG all toolsunload`)})}});async function Di(e,n,r=null){let{action:i=`both`,tabId:a,format:o=`jpeg`,quality:s=60,visionMaxDim:c=1024,visionQuality:l=65}=e;try{let e,u,d=``,f=``;if(a)try{let t=await chrome.tabs.get(a);e=t.id,u=t.windowId,d=t.url||``,f=t.title||``,await chrome.tabs.update(e,{active:!0}),await new Promise(e=>setTimeout(e,300))}catch{return Y(!1,t(`toolExec.tabNotExistOrAccessible`,{tabId:a}),{tool_call_id:n})}else{let r=await chrome.tabs.query({active:!0,currentWindow:!0});if(!r.length)return Y(!1,t(`toolExec.cannotGetCurrentTab`),{tool_call_id:n});e=r[0].id,u=r[0].windowId,d=r[0].url||``,f=r[0].title||``}console.log(`[Background] taking screenshot: tabId=`,e,`url=`,d,`action=`,i,`format=`,o,`quality=`,s,`visionMaxDim=`,c,`visionQuality=`,l);let p=await new Promise((e,t)=>{chrome.tabs.captureVisibleTab(u,{format:o,quality:s},n=>{chrome.runtime.lastError?t(Error(chrome.runtime.lastError.message)):e(n)})}),m=(p.length/1024).toFixed(1);console.log(`[Background] screenshot complete,size:`,m,`KB`),chrome.storage.local.set({_lastVisionScreenshot:{dataUrl:p,sizeKB:m,url:d,title:f,timestamp:Date.now()}}).catch(()=>{});let h=i===`download`||i===`both`,g=i===`analyze`||i===`both`;if(h&&yn(p,o),g){let e=await Oi(p,c,l/100),i=(e.length/1024).toFixed(1);console.log(`[Background] screenshot compressed size:`,i,`KB (maxDim:`,c,`quality:`,l,`)`);let a=await ki(e,d,f,r);return h?Y(!0,`${t(`toolExec.screenshotDownloaded`,{size:m})}。\n\n${a}`,{tool_call_id:n}):Y(!0,a,{tool_call_id:n})}let _=(p.length/1024/1024).toFixed(2);return Y(!0,t(`toolExec.screenshotSuccess`,{size:_,format:o===`png`?`png`:`jpg`,quality:s}),{tool_call_id:n})}catch(e){return Y(!1,t(`toolExec.screenshotFailed`,{error:e.message}),{tool_call_id:n})}}async function Oi(e,t=1024,n=.65){try{let r=await(await fetch(e)).blob(),i=await createImageBitmap(r),{width:a,height:o}=i;(a>t||o>t)&&(a>o?(o=Math.round(t/a*o),a=t):(a=Math.round(t/o*a),o=t));let s=new OffscreenCanvas(a,o);s.getContext(`2d`).drawImage(i,0,0,a,o);let c=await s.convertToBlob({type:`image/jpeg`,quality:n});return new Promise((e,t)=>{let n=new FileReader;n.onloadend=()=>e(n.result),n.onerror=t,n.readAsDataURL(c)})}catch(t){return console.warn(`[Background] image compression failed, using original screenshot:`,t.message),e}}async function ki(e,n,r,i=null){let a=await new Promise(e=>{chrome.storage.local.get([`imageApiBase`,`imageApiKey`,`imageModelName`,`apiBase`,`apiKey`,`modelName`,`streamEnabled`],e)}),o=a.imageApiBase||a.apiBase,s=a.imageApiKey||a.apiKey,c=a.imageModelName||a.modelName,l=a.streamEnabled!==!1;if(!o||!s)return console.log(`[Background] image recognition API not configured,returnscreenshotbasicinfo`),t(`toolExec.screenshotBasicInfo`,{title:r,url:n});console.log(`[Background] calling image recognition API to analyze screenshot,model:`,c,`endpoint:`,o,`streaming:`,l);let u=t(`toolExec.visionPrompt`,{title:r,url:n}),d=new AbortController,f=setTimeout(()=>d.abort(),6e4);try{let t={model:c,messages:[{role:`user`,content:[{type:`text`,text:u},{type:`image_url`,image_url:{url:e,detail:`auto`}}]}],max_tokens:2e3};l&&(t.stream=!0);let a=await fetch(`${o}/chat/completions`,{method:`POST`,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${s}`},body:JSON.stringify(t),signal:d.signal});if(clearTimeout(f),!a.ok){let e=await a.text().catch(()=>``);return console.error(`[Background] image recognition API request failed:`,a.status,e),`页面截图已获取。\n\n- 页面标题: ${r}\n- 页面地址: ${n}\n\n图片识别分析失败(API 返回 ${a.status}),请检查图片识别 API 配置。`}let p;return p=l?await Ai(a,d,i):(await a.json()).choices?.[0]?.message?.content,p?(console.log(`[Background] image recognition analysis complete,result length:`,p.length),`页面截图分析结果:\n\n**页面**: ${r}\n**地址**: ${n}\n\n${p}`):(console.error(`[Background] image recognition API result is empty`),`页面截图已获取。\n\n- 页面标题: ${r}\n- 页面地址: ${n}\n\n图片识别返回结果为空,请重试。`)}catch(e){return clearTimeout(f),console.error(`[Background] image recognition API call exception:`,e.message),e.name===`AbortError`?`页面截图已获取。\n\n- 页面标题: ${r}\n- 页面地址: ${n}\n\n图片识别分析超时(60秒),请检查图片识别 API 是否可用或尝试重新截图。`:t(`toolExec.screenshotAnalysisError`,{title:r,url:n,error:e.message})}}async function Ai(e,t,n=null){let r=e.body.getReader(),i=new TextDecoder,a=``,o=``;try{for(;;){let e;e=t&&t.signal?await Promise.race([r.read(),new Promise((e,n)=>{if(t.signal.aborted){n(new DOMException(`Aborted`,`AbortError`));return}t.signal.addEventListener(`abort`,()=>n(new DOMException(`Aborted`,`AbortError`)),{once:!0})})]):await r.read();let{done:s,value:c}=e;if(s)break;a+=i.decode(c,{stream:!1});let l=a.split(`
349
349
  `);a=l.pop()||``;for(let e of l){let t=``;if(e.startsWith(`data:`)&&(t=e.substring(5).replace(/^\s+/,``)),!(!t||t===`[DONE]`))try{let e=JSON.parse(t),r=e.choices?.[0]?.delta?.content||e.choices?.[0]?.message?.content||e.choices?.[0]?.text||``;r&&(o+=r,n&&chrome.runtime.sendMessage({type:`VISION_ANALYSIS_CHUNK`,sessionId:n,delta:r}).catch(()=>{}))}catch(e){console.warn(`[Background] image recognition SSE parse failed,raw data:`,t.substring(0,200),`error:`,e.message)}}}}finally{r.releaseLock()}return o}function Y(e,t,n={}){return{success:e,content:t,...n}}function ji(e){if(e===0)return`0 B`;let t=[`B`,`KB`,`MB`,`GB`,`TB`],n=1024,r=Math.floor(Math.log(e)/Math.log(n));return`${(e/n**r).toFixed(r===0?0:1)} ${t[r]}`}function Mi(e,n){if(e&&typeof e==`object`&&`success`in e){if(!(`content`in e)){if(e.message)e.content=e.message;else if(!e.success&&e.error){let n=String(e.error).replace(/\\/g,`\\\\`).replace(/"/g,`\\"`);e.content=t(`toolExec.operationFailed`,{error:n}),e.message=e.error}else{let{success:t,error:n,tool_call_id:r,...i}=e;e.content=JSON.stringify(i),e.metadata=i}console.warn(`[Background] toolreturnformatnon-standard (missing content field),auto-filled`)}return e.tool_call_id||=n,e}return typeof e==`string`?(console.warn(`[Background] toolreturnpurecharsstring but non-standardobject,use instead with makeResult()`),{success:!0,content:e,tool_call_id:n}):{success:!1,error:t(`toolExec.unknownResultFormat`),content:``,tool_call_id:n}}async function Ni(e,t,n){try{let r=`toolUsageStats`,i=(await chrome.storage.local.get([r]))[r]||{},a=i[e]||{callCount:0,successCount:0,totalDuration:0,lastUsed:0};a.callCount++,t.success&&a.successCount++,a.totalDuration+=n,a.lastUsed=Date.now(),i[e]=a,chrome.storage.local.set({[r]:i})}catch(e){console.warn(`[Background] recordtoolstats failed:`,e)}}function Pi(){return new Promise(e=>{chrome.tabs.query({active:!0,currentWindow:!0},t=>{e(t&&t.length>0?t[0].id:null)})})}async function Fi(e,n,r){return new Promise(i=>{chrome.tabs.sendMessage(e,n,a=>{if(chrome.runtime.lastError){let a=chrome.runtime.lastError.message;console.warn(`[Background] sendmessage to content script failed:`,a),chrome.tabs.get(e,o=>{if(chrome.runtime.lastError||!o){i({success:!1,error:t(`toolExec.tabAccessDenied`,{error:a}),tool_call_id:r});return}let s=o.url||``;if(s.startsWith(`chrome://`)||s.startsWith(`chrome-extension://`)||s.startsWith(`about:`)||s.startsWith(`chrome-error://`)){s.startsWith(`chrome-error://`)?i({success:!1,error:t(`toolExec.tabErrorPage`),tool_call_id:r}):i({success:!1,error:t(`toolExec.systemPageNotAllowed`,{url:s}),tool_call_id:r});return}console.log(`[Background] attempt autoinject content script to Tab:`,e);let c=chrome.runtime.getManifest().content_scripts?.[0]?.js||[],l=c.findIndex(e=>/content/i.test(e)&&e.endsWith(`.js`)),u=l===-1?c:[c[l]];if(l===-1&&u.length===0){i({success:!1,error:t(`toolExec.contentScriptNotFound`),tool_call_id:r});return}chrome.scripting.executeScript({target:{tabId:e},files:u}).then(()=>{console.log(`[Background] Content script inject successful, startretrysendmessage`),d(e,n,0)}).catch(e=>{console.warn(`[Background] inject content script failed:`,e.message),e.message&&e.message.includes(`error page`)?i({success:!1,error:t(`toolExec.tabErrorPage`),tool_call_id:r}):i({success:!1,error:t(`toolExec.contentScriptInjectFailed`,{error:e.message}),tool_call_id:r})});function d(e,t,n){let a=[300,600,1200],o=a.length;setTimeout(()=>{chrome.tabs.sendMessage(e,t,s=>{chrome.runtime.lastError?n<o-1?(console.warn(`[Background] retry ${n+2}/${o+1} failed, ${a[n+1]}ms after retry:`,chrome.runtime.lastError.message),d(e,t,n+1)):(console.warn(`[Background] all has retryaverage failed:`,chrome.runtime.lastError.message),i({success:!1,error:chrome.runtime.lastError.message,tool_call_id:r})):(console.log(`[Background] retry successful (`+(n+2)+` times)`),i({...s,tool_call_id:r}))})},a[n])}})}else i({...a,tool_call_id:r})})})}async function Ii(e,n,r){let{action:i}=e;switch(i){case`open`:return ia(e,n,r);case`switch`:return aa(e,n,r);case`close`:return oa(e,n);case`reload`:return fa(e,n);case`navigate`:return da(e,n);default:return Y(!1,t(`toolExec.unknownManageTabAction`,{action:i}),{tool_call_id:n})}}async function Li(e,n){let{action:r}=e;switch(r){case`bookmark`:return qi(e,n);case`history`:return Ji(e,n);default:return Y(!1,t(`toolExec.unknownSearchBrowserDataAction`,{action:r}),{tool_call_id:n})}}async function Ri(e,n){let{action:r}=e;switch(r){case`list`:return Sa(e,n);case`restore`:return Ca(e,n);default:return Y(!1,t(`toolExec.unknownAgentTrashAction`,{action:r}),{tool_call_id:n})}}async function zi(e,n){let{action:r}=e;switch(r){case`list`:return Ra(e,n);case`switch`:return za(e,n);default:return Y(!1,t(`toolExec.unknownManageAgentAction`,{action:r}),{tool_call_id:n})}}async function Bi(e,n){let{action:r}=e;switch(r){case`read`:return _a(e,n);case`write`:return ya(e,n);case`list`:return ba(e,n);case`delete`:return xa(e,n);case`download`:return wa(e,n);default:return Y(!1,t(`toolExec.unknownAgentFileAction`,{action:r}),{tool_call_id:n})}}async function Vi(e,n){let{searchType:r}=e;switch(r){case`file`:return Oa(e,n);case`content`:return ka(e,n);default:return Y(!1,t(`toolExec.unknownAgentSearchType`,{type:r}),{tool_call_id:n})}}async function Hi(e,n,r){let{scope:i=`last_n_rounds`,rounds:a=3,sessionId:o}=e,s=o||r||await D();if(!s)return Y(!1,t(`toolExec.cannotGetSessionId`),{tool_call_id:n});let c=await k(s);if(!c)return Y(!1,t(`toolExec.sessionNotFound`,{id:s}),{tool_call_id:n});let l=(c.messageHistory||[]).map((e,t)=>({msg:e,idx:t})).filter(({msg:e})=>e.role===`assistant`&&Array.isArray(e.executionLog)&&e.executionLog.length>0);if(l.length===0)return Y(!0,t(`toolExec.noExecutionLog`),{tool_call_id:n});let u;u=i===`full_session`?l:l.slice(-Math.min(a,l.length));let d=[],f=[],p=[],m=[];for(let{msg:e,idx:n}of u){let r=n+1,i=e.executionLog||[];for(let e of i){let n=e.nodeType;if(m.push({round:r,nodeType:n,nodeName:e.nodeName||e.action?.name||t(`toolExec.unknown`),status:e.status||`unknown`,timestamp:e.timestamp||null,toolName:e.action?.name||null}),n===`tool_exec`){let n=e.action?.name||e.nodeName||t(`toolExec.unknownTool`,{name:`unknown`}),i=e.action?.arguments||e.action?.args||{},a=e.status;a===`success`?d.push({round:r,tool:n,args:i,result:e.observation||e.result||`成功`,description:e.nodeName||``}):(a===`failed`||a===`cancelled`)&&f.push({round:r,tool:n,args:i,status:a,error:e.error||e.observation||e.result||t(`toolExec.unknownError`),description:e.nodeName||``})}n===`reflection`&&p.push({round:r,tool:e.action?.name||e.nodeName||t(`toolExec.unknown`),effective:e.effective===void 0?null:e.effective,reasoning:e.reasoning||e.analysis||``,suggestion:e.suggestion||e.advice||``,reflectionType:e.reflectionType||``})}}let h=u.length,g=m.length,_=m.filter(e=>e.status===`success`).length,v=m.filter(e=>e.status===`failed`||e.status===`cancelled`).length,y={sessionId:s,scope:i,roundsAnalyzed:h,stats:{totalSteps:g,successCount:_,failCount:v,successRate:g>0?(_/g*100).toFixed(1)+`%`:`0%`},successPaths:d,failures:f,reflections:p,timeline:m},b=[];if(b.push(`## 执行日志提炼报告`),b.push(``),b.push(`**会话**: ${c.title||s.slice(0,8)}`),b.push(`**分析范围**: ${i}(${h} 轮)`),b.push(`**统计**: 共 ${g} 步,成功 ${_},失败 ${v},成功率 ${y.stats.successRate}`),b.push(``),d.length>0){b.push(`### ✅ 成功路径`),b.push(``);for(let e of d)b.push(`- **[轮次${e.round}]** 工具 \`${e.tool}\` → ${typeof e.result==`string`?e.result.substring(0,100):`执行成功`}`);b.push(``)}if(f.length>0){b.push(`### ❌ 失败教训`),b.push(``);for(let e of f)b.push(`- **[轮次${e.round}]** 工具 \`${e.tool}\` ${e.status}: ${typeof e.error==`string`?e.error.substring(0,150):`未知错误`}`);b.push(``)}if(p.length>0){b.push(`### 🎯 反思建议`),b.push(``);for(let e of p)b.push(`- **[轮次${e.round}]** 工具 \`${e.tool}\``),e.reasoning&&b.push(` - 推理: ${e.reasoning.substring(0,200)}`),e.suggestion&&b.push(` - 建议: ${e.suggestion.substring(0,200)}`);b.push(``)}return Y(!0,b.join(`
350
350
  `),{tool_call_id:n,extractedData:y})}var Ui={capture_page:Di,clarify_question:Xi,notify:Zi,fetch_url:ea,list_tabs:sa,browser_info:na,download_file:ra,manage_cookies:ca,plan_task:la,clear_data:ua,search_chats:Yi,preview_ui:pa,agent_file:Bi,agent_exec:Ea,agent_search:Vi,agent_skill:ga,wait_navigation:va,handle_dialog:ta,dispatch_task:vn,agent_memory:async(e,t,n)=>zn(e,t,n),debug_page:Rr,page_content:Ma,extract_data:Na,clipboard:Pa,manage_tab:Ii,search_browser_data:Li,agent_trash:Ri,manage_agent:zi,exec_log:Hi},Wi={};for(let e of f)e.execution===`background`&&Ui[e.id]&&(Wi[e.id]=Ui[e.id]);var Gi={};for(let e of f)if(e.execution===`content_script`){let t=e.function.parameters?.properties;if(t){let n=Object.keys(t);Gi[e.id]=e=>{let t={};for(let r of n)t[r]=e[r];return t}}else Gi[e.id]=()=>({})}Gi.search_in_page=e=>({query:e.query||e.pattern,mode:e.mode,caseSensitive:e.caseSensitive,contextLength:e.contextLength,maxResults:e.maxResults,highlight:e.highlight});async function Ki(e,n,r=null){let i=Date.now(),{name:a,arguments:o,id:s,function:c,index:l}=e,u=a||c&&c.name,f=s,p={};if(console.log(`[Background] tool callraw data:`,JSON.stringify(e)),c&&c.arguments){console.log(`[Background] toolCall.function.arguments type:`,typeof c.arguments);try{p=Cn(c.arguments)||{}}catch(e){return console.error(`[Background] parsetool parameter failed:`,e,`originalvalue:`,JSON.stringify(c.arguments).substring(0,300)),{success:!1,error:t(`toolExec.argParseFailed`),tool_call_id:f}}let e=typeof c.arguments==`string`?c.arguments.trim():JSON.stringify(c.arguments);Object.keys(p).length===0&&e.length>0&&e!==`{}`&&console.error(`[Background] parameterparse after empty object!original arguments:`,JSON.stringify(c.arguments).substring(0,300))}else if(typeof o==`object`)p=o||{};else if(typeof o==`string`){console.log(`[Background] using backup argsStr parse:`,o.substring(0,300));try{p=Cn(o)||{}}catch(e){return console.error(`[Background] parsetool parameter failed:`,e,`originalvalue:`,o),{success:!1,error:t(`toolExec.argParseFailed`),tool_call_id:f}}}console.log(`[Background] exec tool:`,u,p,`id:`,f);let m=d[u],h;if(m===`background`){let e=Wi[u];e?(console.log(`[Background] ${u} directly execute, not passed content script`),h=await e(p,f,r,n)):h={success:!1,error:t(`toolExec.unknownTool`,{name:u}),tool_call_id:f}}else if(m===`content_script`){let e=Gi[u];if(e){let n=u.toUpperCase(),i=e(p),a=r?L(r):null,o=p.tabId||a||await Pi();h=o?await Fi(o,{type:n,...i},f):{success:!1,error:t(`toolExec.noTabAvailable`),tool_call_id:f}}else h={success:!1,error:t(`toolExec.unknownTool`,{name:u}),tool_call_id:f}}else h={success:!1,error:t(`toolExec.unknownTool`,{name:u}),tool_call_id:f};h=Mi(h,f);let g=Date.now()-i;return Ni(u,h,g),h}function qi(e,n){let r=e.query||``,a=parseInt(e.maxResults,10)||10;return console.log(`[Background] exec bookmarksearch:`,`query=`,JSON.stringify(r),`maxResults=`,a),new Promise(e=>{if(!chrome.bookmarks){console.error(`[Background] chrome.bookmarks API non- with `),e(Y(!1,t(`toolExec.bookmarkApiUnavailable`)));return}if(!r||r.trim()===``){console.log(`[Background] emptyquery,getbookmark rootnode...`),chrome.bookmarks.getTree(n=>{if(console.log(`[Background] chrome.bookmarks.getTree callback, tree node count:`,n?n.length:`null`),chrome.runtime.lastError){console.error(`[Background] chrome.bookmarks.getTree error:`,chrome.runtime.lastError.message),e(Y(!1,t(`toolExec.bookmarkFetchFailed`,{error:chrome.runtime.lastError.message})));return}let r=[];function o(e){e&&e.forEach(e=>{e.url&&r.push(e),e.children&&e.children.length>0&&o(e.children)})}if(o(n),console.log(`[Background] receiset to total bookmarks:`,r.length),r.length===0){e(Y(!0,t(`toolExec.noBookmarks`)));return}let s=r.slice(0,a).map(e=>({title:e.title||t(`toolExec.noTitle`),url:e.url||``,dateAdded:e.dateAdded?new Date(e.dateAdded).toLocaleString(i()===`en`?`en-US`:`zh-CN`):null})),c=`${t(`toolExec.bookmarksCount`,{total:r.length,shown:s.length})}\n`+s.map((e,t)=>`${t+1}. ${e.title}\n URL: ${e.url}`).join(`
351
351
 
@@ -420,4 +420,4 @@ ${r}`.trim()}function to(e,t=15e3){return new Promise(n=>{let r=Date.now(),i=asy
420
420
  ${r.join(`
421
421
 
422
422
  `)}`}var _o=2048,vo=6e4;async function yo({material:e,model:t,sessionId:n}={}){if(!Array.isArray(e)||e.length===0)return{success:!1,error:`material_empty`};let i=await R();if(!i?.apiBase||!i?.apiKey)return{success:!1,error:`config_missing`};let a=go(e),o=`${i.apiBase}/chat/completions`,s=t||i.modelName;try{let e=await $i(o,{method:`POST`,headers:{Authorization:`Bearer ${i.apiKey}`,"Content-Type":`application/json`},body:JSON.stringify({model:s,messages:[{role:`user`,content:a}],stream:!1,max_tokens:_o,temperature:.2})},vo,1,1e3);if(!e.ok)return r.warn(`[ContextCompactor] request failed: ${e.status}`),{success:!1,error:`http_${e.status}`};let t=await e.json(),c=(t.choices?.[0]?.message?.content||``).trim();return c?(Ft({sessionId:n,model:s,usage:t.usage,callType:`context_compaction`}).catch(()=>{}),r.debug(`[ContextCompactor] summary done, ${c.length} chars`),{success:!0,summary:c}):{success:!1,error:`empty_summary`}}catch(e){return r.warn(`[ContextCompactor] exception:`,e.message),{success:!1,error:e.message||`request_failed`}}}e(`zh`,{bg:{missingSessionId:`缺少 sessionId`,resumingFromCheckpoint:`从 checkpoint 恢复中...`,checkpointNotFound:`未找到可恢复的任务 checkpoint,可能已过期或被清理。请检查 Service Worker 控制台中的诊断日志(搜索 "checkpoint" 关键字)。`,resumeFailed:`恢复失败`,missingSkillName:`缺少技能名称`,fetchFailed:`获取失败`,preparing:`准备中...`,toolPreselect:`工具预筛选`,requestCancelled:`请求已被用户取消`,reactCancelled:`ReAct 循环已被用户取消`,apiCallFailed:`API 调用失败`}}),e(`en`,{bg:{missingSessionId:`Missing sessionId`,resumingFromCheckpoint:`Resuming from checkpoint...`,checkpointNotFound:`No checkpoint found for resumption. It may have expired or been cleaned. Check Service Worker console logs (search "checkpoint").`,resumeFailed:`Resume failed`,missingSkillName:`Missing skill name`,fetchFailed:`Fetch failed`,preparing:`Preparing...`,toolPreselect:`Tool Pre-filter`,requestCancelled:`Request was cancelled by user`,reactCancelled:`ReAct loop was cancelled by user`}}),n(),Za(),Promise.all([y().then(()=>b()),Le()]).then(([e,t])=>{r.debug(`[Background] DB self-check passed,current has ${e.length} checkpoint`+(t?`,completedoldformat Agent migrate`:``))}).catch(e=>{r.warn(`[Background] cleanup expired checkpoint or DB self-check failed:`,e)});var bo=1e3,xo=null,So=null,Co=new Map,X=null;po().then(e=>{X=e}),chrome.runtime?.onConnect?.addListener?.(async e=>{if(e.name?.startsWith(`keepalive-`)){let t=e.name.replace(`keepalive-`,``),n=Co.has(t);if(Co.set(t,e),r.debug(`[Background] keepalive portconnected, sessionId:`,t,n?`(reconnect)`:`(first times)`),n&&!Yt.has(t)){r.warn(`[Background] ⚠️ detected SW re started,sessionId`,t,` API call lost`);let n=null;try{let e=await P(t);e&&(n={iteration:e.iteration,interruptedReason:e.interruptedReason,updatedAt:e.updatedAt,messageCount:e.currentMessages?.length||0,subtaskPlan:e.subtaskPlan?{subtaskCount:e.subtaskPlan.subtasks?.length||0}:null},r.debug(`[Background] detected recoverable checkpoint:`,n))}catch(e){r.warn(`[Background] read checkpoint failed:`,e.message)}try{e.postMessage({type:`SW_RESTARTED`,sessionId:t,checkpoint:n})}catch(e){r.warn(`[Background] send SW_RESTARTED message failed:`,e.message)}}e.onDisconnect.addListener(()=>{Co.delete(t),r.debug(`[Background] keepalive port disconnected, sessionId:`,t)})}}),chrome.sidePanel?.setPanelBehavior?.({openPanelOnActionClick:!1}).catch(()=>{});var Z=`global`,Q=new Map,wo=!!chrome.sidePanel?.onOpened,To=!1,Eo=(async()=>{try{let e=await chrome.runtime.getContexts({contextTypes:[`SIDE_PANEL`]});return To=e.length>0,e}catch{return[]}})();chrome.sidePanel?.onOpened?.addListener(e=>{e?.windowId!=null&&(r.debug(`[Background] sidePanel onOpened:`,JSON.stringify(e)),Q.set(e.windowId,e.tabId??null))}),chrome.sidePanel?.onClosed?.addListener(e=>{if(e?.windowId==null)return;r.debug(`[Background] sidePanel onClosed:`,JSON.stringify(e));let t=Q.get(e.windowId);Q.delete(e.windowId);let n=e.tabId??(typeof t==`number`?t:null);n!=null&&Ro(n)}),chrome.sidePanel?.setOptions?.({path:`side_panel.html`,enabled:!0}).catch(()=>{}),(async()=>{try{Z=Do((await chrome.storage.local.get([`sidePanelScope`])).sidePanelScope),Oo()}catch{}})();function Do(e){return e===`tab-specific`?`tab-specific`:`global`}function Oo(){Z===`tab-specific`?chrome.sidePanel?.setOptions?.({enabled:!1}).catch(()=>{}):(chrome.sidePanel?.setOptions?.({path:`side_panel.html`,enabled:!0}).catch(()=>{}),Fo?.then(()=>zo()).catch(()=>{}))}function ko(e,{group:t=!0}={}){t&&Z===`tab-specific`&&Lo(e),Z===`tab-specific`&&chrome.sidePanel?.setOptions?.({tabId:e,path:`side_panel.html`,enabled:!0}).catch(()=>{})}var $=new Map,Ao=`_aiHelperGroupByWindow`,jo=`AI Helper`;async function Mo(){try{return(await chrome.storage.local.get(`autoGroupTabs`))?.autoGroupTabs!==!1}catch{return!0}}async function No(){if(chrome.tabGroups)try{let e=(await chrome.storage.session.get(Ao))[Ao];if(Array.isArray(e))for(let[t,n]of e)try{await chrome.tabGroups.get(n),$.set(t,n)}catch{}}catch{}}function Po(){chrome.storage.session?.set({[Ao]:Array.from($.entries())}).catch(()=>{})}var Fo=No();async function Io(e){if(!(!chrome.tabGroups||!e?.id||e.windowId==null)&&!e.pinned&&await Mo()){await Fo;try{let t=$.get(e.windowId);if(t!=null)try{await chrome.tabGroups.get(t)}catch{t=null,$.delete(e.windowId),Po()}if(t==null){try{let n=await chrome.tabGroups.query({windowId:e.windowId,title:jo});n.length>0&&(t=n[0].id)}catch{}if(t==null){t=await chrome.tabs.group({tabIds:[e.id]});try{await chrome.tabGroups.update(t,{title:jo,color:`blue`,collapsed:!1})}catch{}}else if(e.groupId!==t)try{await chrome.tabs.group({groupId:t,tabIds:[e.id]})}catch{}$.set(e.windowId,t),Po()}else if(e.groupId!==t)try{await chrome.tabs.group({groupId:t,tabIds:[e.id]})}catch{}}catch(e){r.debug(`[Background] ensureAiHelperGroup failed:`,e?.message)}}}function Lo(e){!chrome.tabGroups||e==null||chrome.tabs.get(e).then(e=>Io(e)).catch(()=>{})}async function Ro(e){if(!(Z!==`tab-specific`||!chrome.tabGroups||!chrome.tabs?.ungroup))try{let t=await chrome.tabs.get(e),[n]=await chrome.tabs.query({active:!0,windowId:t.windowId});if(n?.id!==t.id)return;let i=$.get(t.windowId);if(i==null||t.groupId!==i)return;await chrome.tabs.ungroup([t.id]),r.debug(`[Background] tab unbound from AI Helper group:`,t.id)}catch(e){r.debug(`[Background] unbindTabFromAiHelperGroup failed:`,e?.message)}}async function zo(){if(!chrome.tabGroups||!chrome.tabs?.ungroup)return;let e=[...new Set($.values())];if(e.length!==0){$.clear(),Po();for(let t of e)try{let e=await chrome.tabs.query({groupId:t});e.length>0&&await chrome.tabs.ungroup(e.map(e=>e.id))}catch{}r.debug(`[Background] AI Helper groups dissolved (scope switched to global)`)}}chrome.storage?.onChanged?.addListener?.((e,t)=>{if(t===`local`&&e.sidePanelScope){let t=Do(e.sidePanelScope.newValue);if(t!==Z){if(Z=t,t===`tab-specific`){chrome.runtime.getContexts({contextTypes:[`SIDE_PANEL`]}).then(e=>{e.length>0?chrome.tabs.query({active:!0,currentWindow:!0},e=>{e[0]?.id&&ko(e[0].id,{group:!1}),Oo()}):Oo()}).catch(()=>{Oo()});return}Oo(),r.debug(`[Background] sidePanel scope changed to:`,t)}}}),chrome.action?.onClicked?.addListener?.(e=>{if(X){try{chrome.windows.update(X,{focused:!0}).catch(()=>{X=null,chrome.storage.local.remove(`_detachWindowId`).catch(()=>{}),ko(e.id),chrome.sidePanel?.open?.({tabId:e.id}).catch(()=>{})})}catch{X=null,chrome.storage.local.remove(`_detachWindowId`).catch(()=>{}),ko(e.id),chrome.sidePanel?.open?.({tabId:e.id}).catch(()=>{})}return}ko(e.id),chrome.sidePanel?.open?.({tabId:e.id}).catch(e=>{r.warn(`[Background] open sidePanel failed:`,e?.message)})}),chrome.windows?.onRemoved?.addListener?.(e=>{X===e&&(X=null,chrome.storage.local.remove(`_detachWindowId`).catch(()=>{}),r.debug(`[Background] detached window closed, cleaned up windowId:`,e)),$.has(e)&&($.delete(e),Po())}),chrome.tabs?.onUpdated?.addListener?.((e,t,n)=>{t.status===`complete`&&n.url?.startsWith(`http`)&&Z===`global`&&chrome.sidePanel?.setOptions?.({path:`side_panel.html`,enabled:!0})}),chrome.tabGroups?.onRemoved?.addListener?.(e=>{for(let[t,n]of $)if(n===e.id){$.delete(t),Po();break}});var Bo=`_toggle_sidepanel`,Vo=new Map,Ho=null;chrome.tabs?.onActivated?.addListener?.(({tabId:e,windowId:t})=>{Vo.set(t,e),Ho=t}),chrome.tabs?.onRemoved?.addListener?.((e,{windowId:t})=>{Vo.get(t)===e&&Vo.delete(t)}),chrome.windows?.onFocusChanged?.addListener?.(e=>{e!==chrome.windows.WINDOW_ID_NONE&&(Ho=e)}),(async()=>{try{let[e]=await chrome.tabs.query({active:!0,lastFocusedWindow:!0});if(!e?.id)return;Vo.set(e.windowId,e.id),Ho??=e.windowId}catch{}})(),chrome.commands?.getAll?.().then(e=>{let t=e.find(e=>e.name===Bo);t&&(t.shortcut?r.debug(`[Background] sidePanel shortcut:`,t.shortcut):r.warn(`[Background] sidePanel shortcut is not bound, set it at chrome://extensions/shortcuts`))}).catch(()=>{});function Uo(){return Ho==null?null:Vo.get(Ho)??null}function Wo(e){let t=Q.get(e.windowId);return t===void 0?!wo&&To:t===null||t===e.id}function Go(e,t=null){let n=e=>{r.warn(`[Background] close sidePanel failed, fallback to panel self-close:`,e),chrome.runtime.sendMessage({type:`CLOSE_SIDEPANEL`}).catch(()=>{})};if(!chrome.sidePanel?.close){chrome.runtime.sendMessage({type:`CLOSE_SIDEPANEL`}).catch(e=>{r.warn(`[Background] send CLOSE_SIDEPANEL failed:`,e?.message)});return}let i=typeof t==`number`?{tabId:t}:{windowId:e};chrome.sidePanel.close(i).then(()=>{Q.delete(e)}).catch(r=>{if(typeof t!=`number`)return n(r?.message);chrome.sidePanel.close({windowId:e}).then(()=>{Q.delete(e)}).catch(e=>n(e?.message))})}function Ko(){setTimeout(()=>{chrome.runtime.getContexts({contextTypes:[`SIDE_PANEL`]}).then(e=>{e.length===0&&Q.clear()}).catch(()=>{})},300)}function qo(e){let t=Z===`global`;if(Wo(e)){r.debug(`[Background] command: close sidePanel on tab`,e.id,e.windowId);let n=Q.get(e.windowId);Go(e.windowId,t||n===null?null:e.id);return}r.debug(`[Background] command: open sidePanel on tab`,e.id,e.windowId),ko(e.id);let n=t?{windowId:e.windowId}:{tabId:e.id};chrome.sidePanel?.open?.(n).then(()=>{Q.set(e.windowId,t?null:e.id)}).catch(e=>{r.warn(`[Background] open sidePanel failed:`,e?.message)})}function Jo(){if(Z===`global`){r.debug(`[Background] command: cold start, open sidePanel on current window`),chrome.sidePanel?.open?.({windowId:chrome.windows.WINDOW_ID_CURRENT}).catch(e=>{r.warn(`[Background] open sidePanel failed:`,e?.message)}),Eo.then(e=>{let t=e?.length>0;chrome.tabs.query({active:!0,lastFocusedWindow:!0}).then(([e])=>{if(e?.id){if(Vo.set(e.windowId,e.id),Ho??=e.windowId,t){Go(e.windowId,null);return}Q.set(e.windowId,null)}}).catch(()=>{})}).catch(()=>{});return}chrome.tabs.query({active:!0,lastFocusedWindow:!0},e=>{let t=e[0];t?.id&&(Vo.set(t.windowId,t.id),Ho=t.windowId,qo(t))})}chrome.commands?.onCommand?.addListener(e=>{if(e===Bo)try{if(X){try{chrome.windows.update(X,{focused:!0}).catch(()=>{X=null,chrome.storage.local.remove(`_detachWindowId`).catch(()=>{})})}catch{X=null,chrome.storage.local.remove(`_detachWindowId`).catch(()=>{})}return}let e=Uo();r.debug(`[Background] toggle: scope=%s focusedWindow=%s tab=%s panels=%s events=%s close=%s`,Z,Ho,e,JSON.stringify([...Q]),wo,!!chrome.sidePanel?.close),e==null?Jo():qo({id:e,windowId:Ho}),Ko()}catch(e){r.warn(`[Background] toggle sidePanel exception:`,e?.message)}}),chrome.runtime?.onMessage?.addListener?.((e,n,i)=>{if(e.type===`IFRAME_SELECTION`){let t=n.tab?.id;return t&&chrome.tabs.sendMessage(t,{type:`IFRAME_SELECTION`,text:e.text,x:e.x,y:e.y},{frameId:0}).catch(()=>{}),!1}if(e.type===`IFRAME_CLICK_DISMISS`){let e=n.tab?.id;return e&&chrome.tabs.sendMessage(e,{type:`IFRAME_CLICK_DISMISS`}).catch(()=>{}),!1}if(e.type===`IFRAME_SELECTION_CLEAR`){let e=n.tab?.id;return e&&chrome.tabs.sendMessage(e,{type:`IFRAME_SELECTION_CLEAR`}).catch(()=>{}),!1}if(e.type===`CANCEL_REACT`){let{tabId:t,sessionId:n}=e;return n?(we(n),La(n)):we(t),!1}if(e.type===`COMPACT_CONTEXT_SUMMARY`){let{material:t,model:n,sessionId:a}=e;return yo({material:t,model:n,sessionId:a}).then(e=>{i(e)}).catch(e=>{r.warn(`[Background] COMPACT_CONTEXT_SUMMARY failed:`,e),i({success:!1,error:e?.message||`unknown`})}),!0}if(e.type===`GET_CHECKPOINT`){let{sessionId:t}=e;return t?(P(t).then(e=>{if(!e){i({exists:!1});return}i({exists:!0,checkpoint:{iteration:e.iteration,interruptedReason:e.interruptedReason,updatedAt:e.updatedAt,messageCount:e.currentMessages?.length||0,subtaskPlan:e.subtaskPlan?{subtaskCount:e.subtaskPlan.subtasks?.length||0}:null}})}).catch(e=>{r.warn(`[Background] GET_CHECKPOINT query failed:`,e),i({exists:!1})}),!0):(i({exists:!1}),!1)}if(e.type===`DELETE_CHECKPOINT`){let{sessionId:t}=e;return t?oe(t).then(e=>{i({success:e})}).catch(e=>{r.warn(`[Background] DELETE_CHECKPOINT failed:`,e),i({success:!1})}):i({success:!1}),!0}if(e.type===`RESUME_REACT`){let{sessionId:n,callId:a,userGuidance:o=``}=e;if(!n)return i({error:t(`bg.missingSessionId`)}),!1;r.debug(`[Background] recei to RESUME_REACT,sessionId:`,n,`userGuidance:`,o?`"${o.substring(0,50)}..."`:`( no )`);let s=Yt.has(n),c=()=>{xe(n);let e={type:`EXECUTION_STATUS_UPDATE`,nodeName:t(`bg.resumingFromCheckpoint`),status:`processing`,executionLog:[],sessionId:n};a&&(e.callId=a),chrome.runtime.sendMessage(e).catch(()=>{}),on(n,o,a).then(e=>{if(!e){r.warn(`[Background] RESUME_REACT: not found checkpoint or restore failed`),P(n).then(e=>{r.warn(`[Background] RESUME_REACT: re-query checkpoint result:`,e?`exists`:`not found`)}).catch(()=>{}),chrome.runtime.sendMessage({type:`API_ERROR`,sessionId:n,callId:a,error:t(`bg.checkpointNotFound`),executionLog:[],resumed:!0}).catch(()=>{});return}r.debug(`[Background] RESUME_REACT complete,content length:`,e.content?.length);let i=(e.executionLog||[]).length>bo?e.executionLog.slice(-1e3):e.executionLog||[];chrome.runtime.sendMessage({type:`API_COMPLETE`,sessionId:n,callId:a,content:e.content||``,executionLog:i,reflectionScore:e.reflectionScore,reasoningContent:e.reasoningContent||null,wasRevised:e.wasRevised||!1,resumed:!0}).catch(e=>{r.warn(`[Background] send RESUME completemessage failed:`,e)})}).catch(e=>{let i=e.name===`AbortError`||e.message===t(`bg.requestCancelled`)||e.message===t(`bg.reactCancelled`);r.debug(`[Background] RESUME_REACT failed:`,i?`(usercancel)`:e.message);let o=e.executionLog||[],s=o.length>bo?o.slice(-1e3):o;chrome.runtime.sendMessage({type:`API_ERROR`,sessionId:n,callId:a,error:e.message||t(`bg.resumeFailed`),executionLog:s,resumed:!0}).catch(()=>{})})};return s?(r.debug(`[Background] RESUME_REACT: detectedoldtaskstill running , first cancel`),we(n),La(n),setTimeout(c,300)):c(),!1}if(e.type===`TERMINATE_COMMAND`){let{sessionId:t,mode:n}=e;return t&&La(t,n||`kill`),!1}if(e.type===`ABORT_CURRENT_TOOL`){let{sessionId:t}=e;return i({success:je(t)}),!1}if(e.type===`RELOAD_MCP_TOOLS`)return xo=null,Zr().then(e=>{i({success:!0,count:e})}).catch(e=>{i({success:!1,error:e.message})}),!0;if(e.type===`RELOAD_RAG_TOOLS`)return hi().then(e=>{i({success:!0,count:e})}).catch(e=>{i({success:!1,error:e.message})}),!0;if(e.type===`RAG_LIST_COLLECTIONS`)return rt().then(e=>{e&&e.success?i({success:!0,collections:e.collections||[]}):i({success:!1,error:e&&e.error||`rag unavailable`})}).catch(e=>{i({success:!1,error:e.message})}),!0;if(e.type===`RAG_SEARCH`)return it(e.params||{}).then(e=>{e&&e.success?i({success:!0,results:e.results||[],hasContext:!!e.hasContext}):i({success:!1,error:e&&e.error||`rag unavailable`})}).catch(e=>{i({success:!1,error:e.message})}),!0;if(e.type===`GET_MCP_TOOLS`){hi().catch(()=>{});let e=Date.now();return xo&&e-xo.loadedAt<3e4?(r.debug(`[Background] GET_MCP_TOOLS usingcache (${xo.tools.length} tool,${Math.round((e-xo.loadedAt)/1e3)}s before )`),i({success:!0,tools:xo.tools}),!0):(Zr().then(e=>{let t=f.filter(e=>e.id.startsWith(`mcp_`)).map(e=>{let t=ei(e.id);return{id:e.id,name:t?.toolName||e.function?.name||e.id,description:e.function?.description||``,category:e.category||`mcp`,execution:e.execution||`background`,parallelizable:e.parallelizable!==!1,requiresConfirmation:e.requiresConfirmation||!1,enabled:!0,serverId:t?.serverId||``,serverName:t?.serverName||``}});xo={tools:t,loadedAt:Date.now()},r.debug(`[Background] GET_MCP_TOOLS return ${t.length} tool ( reloads ${e} )`),i({success:!0,tools:t})}).catch(e=>{i({success:!1,error:e.message})}),!0)}if(e.type===`GET_AGENT_SKILL_PROMPTS`){let t=Date.now(),n=e.skillNames||null;return!n&&So&&t-So.loadedAt<6e4?(i({success:!0,prompts:So.prompts}),!0):((n&&n.length>0?pt(n):ft()).then(e=>{let t=e.success&&e.prompts||``;n||(So={prompts:t,loadedAt:Date.now()}),i({success:!0,prompts:t})}).catch(e=>{i({success:!1,error:e.message})}),!0)}if(e.type===`GET_AGENT_SKILL_PROMPT`){let n=e.name;return n?(mt(n).then(e=>{i(e)}).catch(e=>{i({success:!1,error:e.message})}),!0):(i({success:!1,error:t(`bg.missingSkillName`)}),!0)}if(e.type===`GET_SKILL_LIST`)return ot().then(e=>{e?.success?i({success:!0,skills:e.skills||[]}):i({success:!1,skills:[],error:e?.error||t(`bg.fetchFailed`)})}).catch(e=>{i({success:!1,skills:[],error:e.message})}),!0;if(e.type===`CAPTURE_TAB`)return chrome.tabs.captureVisibleTab(null,{format:`jpeg`,quality:100},e=>{chrome.runtime.lastError?(r.error(`[Background] screenshot failed:`,chrome.runtime.lastError.message),i({error:chrome.runtime.lastError.message})):i({dataUrl:e})}),!0;if(e.type===`CAPTURE_TAB_FROM_PAGE`)return chrome.tabs.captureVisibleTab(null,{format:`jpeg`,quality:100},e=>{chrome.runtime.lastError?r.error(`[Background] pageshortcutscreenshot failed:`,chrome.runtime.lastError.message):chrome.runtime.sendMessage({type:`SCREENSHOT_RESULT`,dataUrl:e,mode:`full`}).catch(()=>{})}),!0;if(e.type===`CAPTURE_REGION_FROM_PAGE`){let e=n.tab?.id;return e?(chrome.tabs.sendMessage(e,{type:`START_REGION_SELECTION`},e=>{e&&chrome.tabs.captureVisibleTab(null,{format:`png`},t=>{chrome.runtime.lastError?r.error(`[Background] region screenshot failed:`,chrome.runtime.lastError.message):chrome.runtime.sendMessage({type:`SCREENSHOT_RESULT`,dataUrl:t,mode:`region`,rect:e}).catch(()=>{})})}),!0):!1}if(e.type===`CALL_API`){let{messages:n,model:i,useTools:a,tabId:o,apiParams:s,sessionId:c,imageApiBase:l,imageApiKey:u,agentId:d,agentToolIds:f,agentSkillIds:p,callId:m,forcedMcpServerIds:h,agentMcpExcludedServerIds:g}=e;ri(c,h),l&&(s.imageApiBase=l),u&&(s.imageApiKey=u),xe(c);let _={type:`EXECUTION_STATUS_UPDATE`,nodeName:t(`bg.preparing`),status:`processing`,executionLog:[]};return c&&(_.sessionId=c),m&&(_.callId=m),chrome.runtime.sendMessage(_).catch(()=>{}),r.debug(`[Background] recei to CALL_API message,sessionId:`,c,`useTools:`,a,`tabId:`,o,`apiParams:`,s),(a?(async()=>{let e=await Ei(f,d,p,h,g);if(e.length===0)return r.debug(`[Background] no available tools, skip pre-filter, direct normal conversation`),pn(n,i,s,c,{},m);r.debug(`[Background] get to ${e.length} tool`);let a=(await R()).reactConfig.enableToolPreselect,l;if(a?l=await Pt(n,i,e,s):(r.debug(`[Background] toolpre-filterclosed,using alltool`),l={type:`tools`,tools:e,executionLog:[]}),l.executionLog.length>0){let e={type:`EXECUTION_STATUS_UPDATE`,nodeName:t(`bg.toolPreselect`),status:`success`,executionLog:l.executionLog};c&&(e.sessionId=c),m&&(e.callId=m),r.debug(`[Background] sendpre-filterstateupdate:`,e),chrome.runtime.sendMessage(e).then(()=>{r.debug(`[Background] pre-filterstateupdatesend successful`)}).catch(e=>{r.error(`[Background] pre-filterstateupdatesend failed:`,e)})}if(l.type===`answer`)return r.debug(`[Background] pre-filtermodeldirect answer,skip mainmodelcall with `),{content:l.content,executionLog:l.executionLog};let{tools:u,executionLog:_}=l,v=ai(u,e,h);r.debug(`[Background] after pre-filter ${v.length} tool`),r.debug(`[Background] pre-filter executionlog:`,JSON.stringify(_).substring(0,500)),_.length>0&&chrome.runtime.sendMessage({type:`STREAM_PRESELECT`,sessionId:c,callId:m,preselectLog:_}).catch(()=>{});let y=await sn(n,i,v,o,s,c,null,null,{value:1},_,m);return r.debug(`[Background] ReAct complete,executionLog total:`,y.executionLog?.length),{content:y.content===void 0?y:y.content,executionLog:y.executionLog||_,reflectionScore:y.reflectionScore,wasRevised:y.wasRevised||!1,reasoningContent:y.reasoningContent||null}})():pn(n,i,s,c)).then(e=>{let t=e.content===void 0?e:e.content,n=e.executionLog||[],o=e.reflectionScore,s=e.wasRevised||!1,l=e.reasoningContent||null;e.usage&&(Ft({sessionId:c,model:i||``,usage:e.usage,callType:`non_stream`}).catch(()=>{}),n.length===0&&(n=[{nodeType:`api_call`,nodeName:`API Call`,status:`success`,timestamp:new Date().toISOString(),apiResponse:{tokenUsage:e.usage}}])),r.debug(`[Background] API call complete,content length:`,t.length,`execution logcount:`,n.length),console.log(`[Background API_COMPLETE] useTools:`,a,`| executionLog entries:`,n.length,`| agent_file entries:`,n.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length,`| first few types:`,n.slice(0,5).map(e=>`${e.nodeType}${e.action?`(${e.action.name})`:``}`));let u=n.length>bo?n.slice(-1e3):n;chrome.runtime.sendMessage({type:`API_COMPLETE`,sessionId:c,callId:m,content:t,executionLog:u,reflectionScore:o,reasoningContent:l,wasRevised:s}).catch(e=>{r.warn(`[Background] send backmessage failed:`,e)})}).catch(e=>{e.name===`AbortError`||e.message===t(`bg.requestCancelled`)||e.message===t(`bg.reactCancelled`)?r.debug(`[Background] API call with by usercancel`):r.error(`[Background] API call with failed:`,e.message||e);let n=e.executionLog||[],i=n.length>bo?n.slice(-1e3):n;chrome.runtime.sendMessage({type:`API_ERROR`,sessionId:c,callId:m,error:e.message||t(`bg.apiCallFailed`),executionLog:i}).catch(e=>{r.warn(`[Background] send errormessage failed:`,e)})}),!1}if(e.type===`GET_SESSION`)return R().then(e=>{i({modelName:e.modelName})}),!0;if(e.type===`GET_CHAT_CONFIG`)return Ne().then(e=>{i(e)}),!0;if(e.type===`GET_PERMANENT_NOTES`)return kn().then(e=>{if(!e.success){i({success:!1,facts:[],error:e.error});return}i({success:!0,facts:(e.data.facts||[]).sort((e,t)=>(t.importance||0)-(e.importance||0))})}).catch(e=>{i({success:!1,facts:[],error:e.message})}),!0;if(e.type===`OPEN_OPTIONS_PAGE`){let t=e.hash||``;return chrome.runtime.openOptionsPage(()=>{t&&chrome.tabs.query({url:chrome.runtime.getURL(`options.html`)+`*`},e=>{e.length>0&&chrome.tabs.update(e[0].id,{url:chrome.runtime.getURL(`options.html`)+`#`+t})})}),!1}if(e.type===`DETACH_SIDEPANEL`){let t=Math.min(Math.max(e.width||480,320),900);return(async()=>{try{let e=null;if(n.tab?.windowId)try{e=await chrome.windows.get(n.tab.windowId)}catch{}if(!e)try{e=await chrome.windows.getLastFocused()}catch{}let a=e?Math.max(e.left,Math.round(e.left+(e.width-t)/2)):void 0,o=e?Math.max(e.top,Math.round(e.top+(e.height-720)/2)):void 0,s=await chrome.windows.create({url:chrome.runtime.getURL(`side_panel.html`)+`?popup=1`,type:`popup`,width:t,height:720,left:a,top:o});X=s.id,await chrome.storage.local.set({_detachWindowId:s.id}).catch(()=>{}),r.debug(`[Background] sidePanel detached, windowId:`,s.id),i({success:!0,windowId:s.id})}catch(e){r.warn(`[Background] detach sidePanel failed:`,e?.message),i({success:!1,error:e?.message})}})(),!0}if(e.type===`ATTACH_SIDEPANEL`)return X=null,e.windowId&&chrome.windows.remove(e.windowId).catch(()=>{}),chrome.storage.local.remove(`_detachWindowId`).catch(()=>{}),chrome.tabs.query({active:!0,currentWindow:!0},e=>{e[0]?.id&&(ko(e[0].id),chrome.sidePanel?.open?.({tabId:e[0].id}).catch(e=>{r.warn(`[Background] open sidePanel after attach failed:`,e?.message)}))}),i({success:!0}),!1;if(e.type===`SELECTION_TOOLBAR_ACTION`){let{prompt:i,action:a,text:o,systemPrompt:s}=e,c=n.tab?.id,l=n.frameId;if(r.debug(`[Background] received selected text toolbar operation:`,a,`tabId:`,c),a===`ai-search`)return X==null&&c&&(ko(c),chrome.sidePanel.open({tabId:c}).catch(e=>{r.warn(`[Background] open Side Panel failed:`,e?.message||e)})),Yo(i,o,c),!1;let u=[{role:`system`,content:s||{explain:`你正在处理用户在网页上选中的内容。用1-3句简洁解释选中内容,必要时补充一个简短示例。不要展开长篇论述。`,translate:`你正在处理用户在网页上选中的内容。自动检测语言:中文→英文,英文→中文,其他语言→同时给出中英文。只输出翻译结果,不添加额外说明。`,summary:`你正在处理用户在网页上选中的内容。用3-5个要点总结选中内容,每条要点一句话,提炼核心信息即可。`}[a]||`你正在处理用户在网页上选中的内容,请用简洁的语言回答用户的问题。`},{role:`user`,content:i}];return xe(),R().then(async e=>{try{if(e.streamConfig?.streamEnabled!==!1&&c){let t=`toolbar_${c}_${Date.now()}`,n=await pn(u,e.modelName,{},t,{sendFn:e=>chrome.tabs.sendMessage(c,e,{frameId:l}).catch(()=>{}),typePrefix:`SELECTION_TOOLBAR_`}),i=n.content===void 0?n:n.content;n.usage&&Ft({sessionId:`selection_toolbar`,model:e.modelName,usage:n.usage,callType:`stream`}).catch(()=>{}),r.debug(`[Background] selected texttoolbarstreaming API complete,content length:`,i.length)}else{let t=await pn(u,e.modelName,{}),n=t.content===void 0?t:t.content;t.usage&&Ft({sessionId:`selection_toolbar`,model:e.modelName,usage:t.usage,callType:`non_stream`}).catch(()=>{}),r.debug(`[Background] selected texttoolbar API complete,content length:`,n.length),c&&chrome.tabs.sendMessage(c,{type:`SELECTION_TOOLBAR_RESULT`,content:n,usage:t.usage||null},{frameId:l}).catch(()=>{r.warn(`[Background] send SELECTION_TOOLBAR_RESULT to tab failed`)})}}catch(e){r.error(`[Background] selected texttoolbar API failed:`,e),c&&chrome.tabs.sendMessage(c,{type:`SELECTION_TOOLBAR_RESULT`,error:e.message||t(`bg.apiCallFailed`)},{frameId:l}).catch(()=>{})}}),!1}if(e.type===`FILL_SIDEPANEL_INPUT`){let t=n.tab?.id,i=e.text;return r.debug(`[Background] received follow-upfillrequested :`,i?.substring(0,50)),t&&(ko(t),chrome.sidePanel.open({tabId:t}).catch(e=>{r.warn(`[Background] open Side Panel failed:`,e?.message||e)})),chrome.storage.session.set({pendingFillInput:{text:i,timestamp:Date.now()}}).catch(()=>{}),chrome.runtime.sendMessage({type:`FILL_SIDEPANEL_INPUT`,text:i}).catch(()=>{r.debug(`[Background] Side Panel not open,fillcontentstorage,waiting Side Panel load`)}),!1}if(e.type===`DIRECT_SEND`){let t=n.tab?.id,i=e.text,a=e.selectedText||``;return r.debug(`[Background] received directsendrequested :`,i?.substring(0,50)),t&&(ko(t),chrome.sidePanel.open({tabId:t}).catch(e=>{r.warn(`[Background] open Side Panel failed:`,e?.message||e)})),chrome.storage.session.set({pendingDirectSend:{text:i,selectedText:a,timestamp:Date.now()}}).catch(()=>{}),chrome.runtime.sendMessage({type:`DIRECT_SEND`,text:i,selectedText:a}).catch(()=>{r.debug(`[Background] Side Panel not open,sendcontentstorage,waiting Side Panel load`)}),!1}if(e.type===`TRIGGER_AGENT_HEALTH_CHECK`)return $o.clear(),ns(),!1;if(e.type===`OPTIONS_PAGE_OPEN`)return Qo=!0,$o.clear(),ns(),!1;if(e.type===`OPTIONS_PAGE_CLOSED`)return Qo=!1,!1;if(e.type===`AGENT_CONNECTION_CHANGED`)return chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:e.connected,agentId:e.agentId}).catch(()=>{}),e.connected&&e.agentId?(ut(),So=null,xo=null,ha(),$o.clear(),wi(),Pe(e.agentId,!0),as(),Zr().then(e=>{e>0&&r.debug(`[Background] switchagent after loaded: ${e} MCP tool`)}).catch(()=>{}),hi().then(e=>{e>0&&r.debug(`[Background] switchagent after loaded: ${e} RAG tool`)}).catch(()=>{}),setTimeout(()=>{ns()},3e3)):e.connected||(as(),xo=null,So=null,ha(),ns()),!1;if(e.type===`CHECK_FILES_EXIST`){let t=e.paths||[];return t.length===0?(i({success:!0,results:{}}),!1):((async()=>{let e=await Promise.allSettled(t.map(e=>He(e))),n={};e.forEach((e,r)=>{e.status===`fulfilled`&&e.value.success?n[t[r]]=e.value.exists:n[t[r]]=!0}),i({success:!0,results:n})})(),!0)}if(e.type===`AGENT_RESTART`)return(async()=>{i(await ht())})(),!0;if(e.type===`AGENT_UPDATE`)return(async()=>{i(await gt())})(),!0;if(e.type===`AGENT_STOP`)return(async()=>{i(await _t())})(),!0;if(e.type===`OPEN_LOCAL_PROTOTYPE`)return(async()=>{i(await We(e.path))})(),!0;if(e.type===`DELETE_LOCAL_PROTOTYPE`)return(async()=>{try{let t=e.path.replace(/[\\/][^\\/]+\.html$/,``),n=await Ke(t);n.success?r.debug(`[Background] local prototypefile deleted:`,t):r.warn(`[Background] local prototypefiledelete failed:`,n.error),i(n)}catch(e){r.warn(`[Background] local prototypefiledelete failed:`,e.message),i({success:!1,error:e.message})}})(),!0;if(e.type?.startsWith(`SCHEDULED_TASK_`))return uo(e,i);if(e.type===`QUERY_AUDIT_LOGS`)return vt({category:e.category,limit:e.limit}).then(e=>{i(e)}).catch(e=>{i({success:!1,error:e.message})}),!0});async function Yo(e,t,n){r.debug(`[Background] processselected text AI search:`,e.substring(0,50)+`...`),await chrome.storage.session.set({pendingSelectionSearch:{prompt:e,selectedText:t,timestamp:Date.now()}}),chrome.runtime.sendMessage({type:`SELECTION_AI_SEARCH`,prompt:e,selectedText:t}).catch(()=>{r.debug(`[Background] Side Panel not open,searchcontentstorage,waiting Side Panel load`)})}var Xo=null,Zo=null,Qo=!1,$o=new Map,es=new Map;async function ts(e){let t=!1,n=5e3;try{let r=new AbortController,i=setTimeout(()=>r.abort(),n),a=await fetch(`${e.url}/api/status`,{signal:r.signal,cache:`no-cache`});clearTimeout(i),t=a.ok}catch{t=!1}if(!t){await new Promise(e=>setTimeout(e,500));try{let r=new AbortController,i=setTimeout(()=>r.abort(),n),a=await fetch(`${e.url}/api/status`,{signal:r.signal,cache:`no-cache`});clearTimeout(i),t=a.ok}catch{t=!1}}return t}async function ns(){try{let e=await ze();if(e.length===0){$o.size>0&&($o.clear(),wi(),Pe(`__global__`,!1),ss(!1,`未配对`));return}let t=await Be(),n=e.filter(e=>!e.disabled),i=Qo?n:t&&!t.disabled?[t]:[];if(i.length===0)return;let a=(await Promise.allSettled(i.map(async e=>{let t=await ts(e);return $o.get(e.id)===t?{agentId:e.id,name:e.name,connected:t,changed:!1}:($o.set(e.id,t),Pe(e.id,t),r.debug(`[Background] agent ${e.name} status change: ${t?`online`:`offline`}`),{agentId:e.id,name:e.name,connected:t,changed:!0})}))).filter(e=>e.status===`fulfilled`&&e.value.changed).map(e=>e.value);if(a.length>0){wi();let e=a.find(e=>e.agentId===t?.id);e&&(ss(e.connected,e.connected?`在线`:`离线`,e.agentId),e.connected?(is(e.agentId),Zr().then(e=>{e>0&&r.debug(`[Background] Agent after reconnect loaded: ${e} MCP tool`)}).catch(()=>{}),hi().then(e=>{e>0&&r.debug(`[Background] Agent after reconnect loaded: ${e} RAG tool`)}).catch(()=>{})):(await $r(),await vi(),xo=null,r.debug(`[Background] Agent disconnect,cleaned MCP tool`),rs(t)))}}catch(e){r.warn(`[Background] agenthealth checkexception:`,e.message)}}function rs(e){if(!e||e.disabled||es.get(e.id))return;let t=n=>{if(n>=20){es.delete(e.id),r.debug(`[Background] agent ${e.name} auto reconnectabandoned (exceed maxretry times)`);return}let i=setTimeout(async()=>{let i=(await ze()).find(t=>t.id===e.id);if(!i||i.disabled){es.delete(e.id),r.debug(`[Background] agent ${e.name} ${i?.disabled?`disable`:`delete`},stopauto reconnect`);return}r.debug(`[Background] agent ${e.name} auto reconnectattempt ${n+1}/20`),await ts(e)?(es.delete(e.id),$o.set(e.id,!0),Pe(e.id,!0),wi(),ss(!0,`在线`,e.id),os(e.id),Zr().then(t=>{t>0&&r.debug(`[Background] Agent ${e.name} reconnect successful,loaded: ${t} MCP tool`)}).catch(()=>{}),hi().then(t=>{t>0&&r.debug(`[Background] Agent ${e.name} reconnect successful,loaded: ${t} RAG tool`)}).catch(()=>{}),r.debug(`[Background] agent ${e.name} auto reconnect successful`)):t(n+1)},15e3);es.set(e.id,{timer:i,retries:n})};t(0)}function is(e){let t=es.get(e);t&&(clearTimeout(t.timer),es.delete(e))}function as(){for(let[e,t]of es)clearTimeout(t.timer);es.clear()}async function os(e){try{let t=await Be();t&&t.id===e&&(Zr().then(e=>{e>0&&r.debug(`[Background] active agentafter reconnect loaded: ${e} MCP tool`)}).catch(()=>{}),hi().then(e=>{e>0&&r.debug(`[Background] active agentafter reconnect loaded: ${e} RAG tool`)}).catch(()=>{}))}catch(e){r.warn(`[Background] refreshactive agentstate failed:`,e.message)}}function ss(e,t,n){chrome.runtime.sendMessage({type:`AGENT_STATUS_CHANGE`,connected:e,status:t,agentId:n}).catch(()=>{})}function cs(){ls(),r.debug(`[Background] start Agent health check (30s interval)`),ns(),Xo=setInterval(ns,3e4),ds()}function ls(){Xo&&(clearInterval(Xo),Xo=null,$o.clear()),fs()}async function us(){try{let e=await Be();if(!e||e.disabled)return;let t=new AbortController,n=setTimeout(()=>t.abort(),5e3);try{await fetch(`${e.url}/api/heartbeat`,{headers:{Authorization:`Bearer ${e.token}`},signal:t.signal,cache:`no-cache`})}finally{clearTimeout(n)}}catch{}}function ds(){fs(),us(),Zo=setInterval(us,6e4)}function fs(){Zo&&=(clearInterval(Zo),null)}cs();
423
- //# sourceMappingURL=background-ulzvUlX3.js.map
423
+ //# sourceMappingURL=background-IYYaT9BE.js.map