@pageops/sdk 0.1.13 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/pageops-sdk.es.js
CHANGED
|
@@ -112,7 +112,7 @@ function y(a) {
|
|
|
112
112
|
}
|
|
113
113
|
return t.join("");
|
|
114
114
|
}
|
|
115
|
-
async function
|
|
115
|
+
async function _(a, e) {
|
|
116
116
|
var n;
|
|
117
117
|
const t = a.getReader(), s = new TextDecoder();
|
|
118
118
|
let i = "";
|
|
@@ -134,7 +134,7 @@ function I(a, e) {
|
|
|
134
134
|
const t = (i = a.match(/^event:\s*(.+)$/m)) == null ? void 0 : i[1], s = (n = a.match(/^data:\s*(.+)$/m)) == null ? void 0 : n[1];
|
|
135
135
|
t && s && e(t, JSON.parse(s));
|
|
136
136
|
}
|
|
137
|
-
class
|
|
137
|
+
class K {
|
|
138
138
|
constructor(e, t = 16) {
|
|
139
139
|
r(this, "queue", []);
|
|
140
140
|
r(this, "timer", null);
|
|
@@ -206,7 +206,7 @@ class j {
|
|
|
206
206
|
r(this, "streamDone", null);
|
|
207
207
|
r(this, "answerAudience", "business");
|
|
208
208
|
r(this, "audienceChanging", !1);
|
|
209
|
-
r(this, "typewriter", new
|
|
209
|
+
r(this, "typewriter", new K((e) => {
|
|
210
210
|
this.streaming += e, this.updateStreamingMessage();
|
|
211
211
|
}));
|
|
212
212
|
}
|
|
@@ -359,7 +359,7 @@ class j {
|
|
|
359
359
|
const c = await this.client.streamQuestion(this.currentThread.id, e, i.signal);
|
|
360
360
|
if (!c.ok) throw new Error(await U(c, "服务暂时无法回答,请稍后重试。"));
|
|
361
361
|
if (!c.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
|
|
362
|
-
if (await
|
|
362
|
+
if (await _(c.body, (o, p) => this.handleStreamEvent(o, p)), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
363
363
|
if (this.streamFailure) throw new Error(this.streamFailure);
|
|
364
364
|
if (!this.streamDone) throw new Error("服务响应意外中断,请稍后重试。");
|
|
365
365
|
if (await this.typewriter.drain(), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
@@ -439,7 +439,8 @@ class j {
|
|
|
439
439
|
await navigator.clipboard.writeText(e);
|
|
440
440
|
else {
|
|
441
441
|
const s = document.createElement("textarea");
|
|
442
|
-
s.value = e, s.style.position = "fixed", s.style.opacity = "0", document.body.appendChild(s), s.select(), document.execCommand("copy")
|
|
442
|
+
if (s.value = e, s.style.position = "fixed", s.style.opacity = "0", document.body.appendChild(s), s.select(), !document.execCommand("copy")) throw new Error("copy_not_supported");
|
|
443
|
+
s.remove();
|
|
443
444
|
}
|
|
444
445
|
this.copiedAgentRunId = e;
|
|
445
446
|
} catch (s) {
|
package/dist/pageops-sdk.umd.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
(function(f,m){typeof exports=="object"&&typeof module!="undefined"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(f=typeof globalThis!="undefined"?globalThis:f||self,m(f.PageOpsSDK={}))})(this,(function(f){"use strict";var M=Object.defineProperty;var W=(f,m,y)=>m in f?M(f,m,{enumerable:!0,configurable:!0,writable:!0,value:y}):f[m]=y;var r=(f,m,y)=>W(f,typeof m!="symbol"?m+"":m,y);class m{constructor(e){this.options=e}async createContext(e=(
|
|
2
|
-
`),t=[];for(let s=0;s<e.length;s+=1){const
|
|
3
|
-
`))}</code></pre>`);continue}const n=U(e,s);if(n){t.push(n.html),s=n.next-1;continue}i.startsWith("### ")?t.push(`<h4>${w(i.slice(4))}</h4>`):i.startsWith("## ")?t.push(`<h3>${w(i.slice(3))}</h3>`):i.startsWith("# ")?t.push(`<h2>${w(i.slice(2))}</h2>`):i.startsWith("- ")?t.push(`<li>${w(i.slice(2))}</li>`):i.trim()?t.push(`<p>${w(i)}</p>`):t.push("<br>")}return t.join("")}async function F(o,e){var n;const t=o.getReader(),s=new TextDecoder;let i="";for(;;){const{done:c,value:a}=await t.read();if(c){i+=s.decode();break}i+=s.decode(a,{stream:!0});const p=i.split(/\r?\n\r?\n/);i=(n=p.pop())!=null?n:"";for(const g of p)A(g,e)}i.trim()&&A(i,e)}function A(o,e){var i,n;const t=(i=o.match(/^event:\s*(.+)$/m))==null?void 0:i[1],s=(n=o.match(/^data:\s*(.+)$/m))==null?void 0:n[1];t&&s&&e(t,JSON.parse(s))}class K{constructor(e,t=16){r(this,"queue",[]);r(this,"timer",null);r(this,"drainWaiters",[]);this.onChunk=e,this.interval=t}enqueue(e){this.queue.push(...Array.from(e)),this.timer||this.tick()}async drain(){!this.timer&&!this.queue.length||await new Promise(e=>this.drainWaiters.push(e))}clear(){this.timer&&clearTimeout(this.timer),this.timer=null,this.queue=[],this.resolveDrainWaiters()}tick(){const e=Math.max(1,Math.ceil(this.queue.length/90)),t=this.queue.splice(0,e).join("");if(t&&this.onChunk(t),!this.queue.length){this.timer=null,this.resolveDrainWaiters();return}this.timer=setTimeout(()=>this.tick(),this.interval)}resolveDrainWaiters(){for(const e of this.drainWaiters.splice(0))e()}}const S=[{value:"product",label:"产品"},{value:"business",label:"业务"},{value:"developer",label:"研发"},{value:"tester",label:"测试"}];class _{constructor(){r(this,"client",null);r(this,"options",null);r(this,"root",null);r(this,"panel",null);r(this,"context",null);r(this,"contextKey","");r(this,"selectedPageKey","");r(this,"currentThread",null);r(this,"conversations",[]);r(this,"messages",[]);r(this,"steps",[]);r(this,"selectedAgentRunId","");r(this,"runLoading",!1);r(this,"runLoadError","");r(this,"copiedAgentRunId","");r(this,"copyFeedbackTimer",null);r(this,"sourceSnapshots",[]);r(this,"sourceUploadStatus","");r(this,"sourceUploadError","");r(this,"sourceLoadError","");r(this,"sourceUploading",!1);r(this,"sourceRefreshTimer",null);r(this,"streaming","");r(this,"asking",!1);r(this,"waitingForFirstContent",!1);r(this,"abortController",null);r(this,"activeRunId",0);r(this,"stoppedRunId",-1);r(this,"answerStopped",!1);r(this,"answerError","");r(this,"conversationError","");r(this,"deletingThreadId","");r(this,"streamFailure","");r(this,"streamDone",null);r(this,"answerAudience","business");r(this,"audienceChanging",!1);r(this,"typewriter",new K(e=>{this.streaming+=e,this.updateStreamingMessage()}))}mount(e){var t;this.unmount(),this.options=e,this.client=new m(e),this.answerAudience=this.loadAnswerAudience(e.appId),this.root=document.createElement("div"),this.root.className="pageops-sdk",((t=e.container)!=null?t:document.body).appendChild(this.root),this.renderClosed()}unmount(){var e;this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.resetAnswerState(),(e=this.root)==null||e.remove(),this.root=null,this.panel=null,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoading=!1,this.runLoadError="",this.clearCopyFeedback(),this.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceLoadError="",this.sourceUploading=!1,this.answerAudience="business",this.audienceChanging=!1}open(){this.root&&(this.root.innerHTML="",this.panel=document.createElement("div"),this.panel.className="po-panel",this.root.appendChild(this.panel),this.loadSources(),this.loadConversations(),this.renderPanel())}close(){this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.renderClosed()}updateContext(e){if(!this.options)return;const t=this.options.appId;this.options={...this.options,...e},this.client=new m(this.options),this.options.appId!==t&&(this.answerAudience=this.loadAnswerAudience(this.options.appId),this.currentThread=null,this.selectedPageKey="",this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError=""),this.context=null,this.contextKey="",this.renderPanel()}renderClosed(){var e;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(e=this.root.querySelector("button"))==null||e.addEventListener("click",()=>this.open()))}async ensureContext(){if(!this.client||!this.options)throw new Error("PageOps SDK 未初始化");const e=this.getPageContext(),t=this.getPageContextKey(e);return this.context&&this.contextKey===t?this.context:(this.context=await this.client.createContext(e),this.contextKey=t,this.context)}getPageContext(){var e,t,s;return{...(s=(t=(e=this.options)==null?void 0:e.getPageContext)==null?void 0:t.call(e))!=null?s:{},userRole:this.answerAudience}}answerAudienceStorageKey(e){return`pageops:answer-audience:${e}`}loadAnswerAudience(e){try{const t=localStorage.getItem(this.answerAudienceStorageKey(e));return S.some(s=>s.value===t)?t:"business"}catch(t){return"business"}}saveAnswerAudience(){if(this.options)try{localStorage.setItem(this.answerAudienceStorageKey(this.options.appId),this.answerAudience)}catch(e){}}async changeAnswerAudience(e){var s;if(this.asking||this.audienceChanging)return;const t=(s=S.find(i=>i.value===e))==null?void 0:s.value;if(!(!t||t===this.answerAudience)){this.answerAudience=t,this.saveAnswerAudience(),this.audienceChanging=!0,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1,this.conversationError="",this.renderPanel();try{await this.newConversation()}catch(i){this.conversationError=i instanceof Error?i.message:"切换回答角色失败,请稍后重试。"}finally{this.audienceChanging=!1,this.renderPanel()}}}getPageContextKey(e){var t,s,i,n,c;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(i=e.title)!=null?i:document.title,(n=e.menuPath)!=null?n:[],(c=e.userRole)!=null?c:""])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceLoadError=""}catch(e){this.sourceLoadError="源码包状态加载失败,连接恢复后将自动重试。"}this.scheduleSourceRefresh(),this.renderPanel()}}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){var s;if(!this.client)return;const e=await this.ensureContext(),t=(s=e.menu_path)!=null&&s.length?e.menu_path.join(" / "):e.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(e.id,t),this.selectedPageKey=this.contextKey,this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel()}async selectThread(e){if(!this.client)return;this.currentThread=e,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(e.id),this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel();const t=[...this.messages].reverse().map(P).find(Boolean);t&&await this.loadAgentRun(t)}async deleteConversation(e){var t;if(!(!this.client||this.asking||this.deletingThreadId)&&window.confirm(`确定删除会话“${e.title}”吗?此操作无法撤销。`)){this.deletingThreadId=e.id,this.conversationError="",this.renderPanel();try{if(await this.client.deleteConversation(e.id),this.conversations=this.conversations.filter(s=>s.id!==e.id),((t=this.currentThread)==null?void 0:t.id)===e.id){this.currentThread=null,this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1;const s=this.conversations[0];s&&await this.selectThread(s)}}catch(s){this.conversationError=s instanceof Error?s.message:"删除问答会话失败"}finally{this.deletingThreadId="",this.renderPanel()}}}async uploadSource(e){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(e),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(e){if(!this.client||this.asking)return;const t=this.questionUnavailableReason();if(t){this.sourceUploadError=t,this.renderPanel();return}this.resetAnswerState();const s=++this.activeRunId,i=new AbortController;this.abortController=i,this.stoppedRunId=-1,this.asking=!0,this.waitingForFirstContent=!0,this.renderPanel();try{const n=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==n&&(this.currentThread=null),this.currentThread||await this.newConversation(),!this.currentThread)throw new Error("无法创建问答会话,请稍后重试。");this.messages.push({id:`local-${Date.now()}`,role:"user",content:e,metadata_json:{}}),this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.renderPanel();const c=await this.client.streamQuestion(this.currentThread.id,e,i.signal);if(!c.ok)throw new Error(await y(c,"服务暂时无法回答,请稍后重试。"));if(!c.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await F(c.body,(a,p)=>this.handleStreamEvent(a,p)),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");if(this.streamFailure)throw new Error(this.streamFailure);if(!this.streamDone)throw new Error("服务响应意外中断,请稍后重试。");if(await this.typewriter.drain(),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");await this.selectThread(this.currentThread)}catch(n){if(s!==this.activeRunId)return;this.typewriter.clear(),this.waitingForFirstContent=!1,s===this.stoppedRunId?this.answerStopped=!0:(this.answerError=n instanceof Error?n.message:"服务异常,请稍后重试。",this.upsertStep({id:"error",title:"执行失败",status:"failed",summary:this.answerError}))}finally{if(s!==this.activeRunId)return;this.asking=!1,this.waitingForFirstContent=!1,this.abortController===i&&(this.abortController=null),this.renderPanel(!0)}}cancelActiveAnswer(e){var t;if(!(!this.asking&&!this.abortController)){if(e){this.stoppedRunId=this.activeRunId,this.answerStopped=!0;const s=this.steps.map(i=>i.status==="running"?{...i,status:"cancelled"}:i);this.steps=s.some(i=>i.status==="cancelled")?s:[...s,{id:"stopped",title:"已停止",status:"cancelled"}]}else this.activeRunId+=1,this.asking=!1;this.typewriter.clear(),this.waitingForFirstContent=!1,(t=this.abortController)==null||t.abort(),this.abortController=null,e&&this.renderPanel()}}handleStreamEvent(e,t){var s,i;if(e==="step"){this.upsertStep(t),this.renderPanel();return}if(e==="delta"){const n=String((s=t.content)!=null?s:"");if(!n)return;this.waitingForFirstContent=!1,this.typewriter.enqueue(n);return}e==="done"&&(this.streamDone=t),e==="error"&&(this.streamFailure=String((i=t.message)!=null?i:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,i;const e=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!e){this.renderPanel();return}e.innerHTML=$(this.streaming);const t=(i=this.panel)==null?void 0:i.querySelector(".po-messages");t&&(t.scrollTop=t.scrollHeight)}resetAnswerState(){this.typewriter.clear(),this.asking=!1,this.waitingForFirstContent=!1,this.answerError="",this.answerStopped=!1,this.streamFailure="",this.streamDone=null,this.streaming=""}upsertStep(e){const t=this.steps.findIndex(s=>s.id===e.id);this.steps=t===-1?[...this.steps,e]:this.steps.map(s=>s.id===e.id?{...s,...e}:s)}async loadAgentRun(e){if(!(!this.client||!e)){this.selectedAgentRunId=e,this.runLoading=!0,this.runLoadError="",this.renderPanel();try{const t=await this.client.getAgentRun(e);if(this.selectedAgentRunId!==e)return;this.steps=t.steps}catch(t){if(this.selectedAgentRunId!==e)return;this.steps=[],this.runLoadError=t instanceof Error?t.message:"执行过程加载失败"}finally{this.selectedAgentRunId===e&&(this.runLoading=!1,this.renderPanel())}}}async copyAgentRunId(e){var t;if(e){try{if((t=navigator.clipboard)!=null&&t.writeText)await navigator.clipboard.writeText(e);else{const s=document.createElement("textarea");s.value=e,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.select(),document.execCommand("copy"),s.remove()}this.copiedAgentRunId=e}catch(s){this.copiedAgentRunId=`error:${e}`}this.clearCopyFeedback(!1),this.copyFeedbackTimer=setTimeout(()=>{this.copiedAgentRunId="",this.copyFeedbackTimer=null,this.renderPanel()},1800),this.renderPanel()}}clearCopyFeedback(e=!0){this.copyFeedbackTimer&&clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=null,e&&(this.copiedAgentRunId="")}latestAnalysisStatus(){var e,t,s;return String((s=(t=(e=this.sourceSnapshots[0])==null?void 0:e.metadata)==null?void 0:t.analysis_status)!=null?s:"")}isProjectMemoryUpdating(){return["pending","running"].includes(this.latestAnalysisStatus())}questionUnavailableReason(){return this.sourceLoadError&&!this.sourceSnapshots.length?"暂时无法读取项目共享代码包,请检查 PageOps 服务连接。":this.sourceSnapshots.length?this.isProjectMemoryUpdating()?"项目记忆正在更新,完成前暂不能问答。":this.latestAnalysisStatus()==="failed"?"项目记忆更新失败,请重新上传或重新索引。":"":"请先上传代码包后再提问。"}scheduleSourceRefresh(){this.stopSourceRefresh(),!(!this.sourceLoadError&&!this.isProjectMemoryUpdating())&&(this.sourceRefreshTimer=setTimeout(()=>void this.loadSources(),1500))}stopSourceRefresh(){this.sourceRefreshTimer&&clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null}renderPanel(e=this.asking){if(!this.panel)return;const t=this.questionUnavailableReason(),s=t||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),i=!!(t||this.asking),n=t?'<button type="submit" disabled>暂不可提问</button>':this.asking?'<button class="po-stop" type="button" data-action="stop-answer" aria-label="停止输出" title="停止输出"><span aria-hidden="true"></span></button>':'<button type="submit">发送</button>',c=S.map(a=>`
|
|
1
|
+
(function(f,m){typeof exports=="object"&&typeof module!="undefined"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(f=typeof globalThis!="undefined"?globalThis:f||self,m(f.PageOpsSDK={}))})(this,(function(f){"use strict";var M=Object.defineProperty;var W=(f,m,y)=>m in f?M(f,m,{enumerable:!0,configurable:!0,writable:!0,value:y}):f[m]=y;var r=(f,m,y)=>W(f,typeof m!="symbol"?m+"":m,y);class m{constructor(e){this.options=e}async createContext(e=(n=>(n=(t=>(s=>(s=(t=this.options).getPageContext)==null?void 0:s.call(t))())())!=null?n:{})()){var i,c,a;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:e.route,url:(i=e.url)!=null?i:location.href,title:(c=e.title)!=null?c:document.title,menu_path:(a=e.menuPath)!=null?a:[],tenant_id:e.tenantId,user_role:e.userRole,build_version:e.buildVersion})})}async listConversations(){return(await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations}async createConversation(e,t){return this.request("/conversations",{method:"POST",body:JSON.stringify({app_id:this.options.appId,context_session_id:e,title:t})})}async deleteConversation(e){return this.request(`/conversations/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`,{method:"DELETE"})}async listMessages(e){return(await this.request(`/conversations/${encodeURIComponent(e)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages}async getAgentRun(e){return this.request(`/question/runs/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`)}async listSources(){return(await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources}uploadSource(e){const t=new FormData;return t.append("file",e),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:t,headers:{}})}streamQuestion(e,t,s){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:this.options.appId,thread_id:e,question:t}),signal:s})}async request(e,t){var c,a;const s=(t==null?void 0:t.body)instanceof FormData?t.headers:{"content-type":"application/json",...(c=t==null?void 0:t.headers)!=null?c:{}},n=await fetch(`${this.base()}${e}`,{...t,headers:s});if(n.status===204)return;const i=await n.json();if(!n.ok)throw new Error((a=i.message)!=null?a:"PageOps 请求失败");return i}base(){const e=this.options.apiBase.replace(/\/$/,"");return e.endsWith("/api")?e:`${e}/api`}}async function y(o,e){const t=await o.json().catch(()=>null);return typeof(t==null?void 0:t.message)=="string"&&t.message.trim()?t.message:e}function E(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function w(o){return E(o).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function U(o,e){const t=o[e],s=o[e+1];if(!(t!=null&&t.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const n=[];let i=e;for(;i<o.length&&o[i].includes("|")&&o[i].trim();)n.push(o[i]),i+=1;const c=g=>g.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(b=>w(b.trim())),a=c(n[0]).map(g=>`<th>${g}</th>`).join(""),p=n.slice(2).map(g=>`<tr>${c(g).map(b=>`<td>${b}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${a}</tr></thead><tbody>${p}</tbody></table>`,next:i}}function $(o){const e=o.split(`
|
|
2
|
+
`),t=[];for(let s=0;s<e.length;s+=1){const n=e[s];if(n.trim().startsWith("```")){const c=[];for(s+=1;s<e.length&&!e[s].trim().startsWith("```");)c.push(e[s]),s+=1;t.push(`<pre><code>${E(c.join(`
|
|
3
|
+
`))}</code></pre>`);continue}const i=U(e,s);if(i){t.push(i.html),s=i.next-1;continue}n.startsWith("### ")?t.push(`<h4>${w(n.slice(4))}</h4>`):n.startsWith("## ")?t.push(`<h3>${w(n.slice(3))}</h3>`):n.startsWith("# ")?t.push(`<h2>${w(n.slice(2))}</h2>`):n.startsWith("- ")?t.push(`<li>${w(n.slice(2))}</li>`):n.trim()?t.push(`<p>${w(n)}</p>`):t.push("<br>")}return t.join("")}async function F(o,e){var i;const t=o.getReader(),s=new TextDecoder;let n="";for(;;){const{done:c,value:a}=await t.read();if(c){n+=s.decode();break}n+=s.decode(a,{stream:!0});const p=n.split(/\r?\n\r?\n/);n=(i=p.pop())!=null?i:"";for(const g of p)A(g,e)}n.trim()&&A(n,e)}function A(o,e){var n,i;const t=(n=o.match(/^event:\s*(.+)$/m))==null?void 0:n[1],s=(i=o.match(/^data:\s*(.+)$/m))==null?void 0:i[1];t&&s&&e(t,JSON.parse(s))}class K{constructor(e,t=16){r(this,"queue",[]);r(this,"timer",null);r(this,"drainWaiters",[]);this.onChunk=e,this.interval=t}enqueue(e){this.queue.push(...Array.from(e)),this.timer||this.tick()}async drain(){!this.timer&&!this.queue.length||await new Promise(e=>this.drainWaiters.push(e))}clear(){this.timer&&clearTimeout(this.timer),this.timer=null,this.queue=[],this.resolveDrainWaiters()}tick(){const e=Math.max(1,Math.ceil(this.queue.length/90)),t=this.queue.splice(0,e).join("");if(t&&this.onChunk(t),!this.queue.length){this.timer=null,this.resolveDrainWaiters();return}this.timer=setTimeout(()=>this.tick(),this.interval)}resolveDrainWaiters(){for(const e of this.drainWaiters.splice(0))e()}}const S=[{value:"product",label:"产品"},{value:"business",label:"业务"},{value:"developer",label:"研发"},{value:"tester",label:"测试"}];class _{constructor(){r(this,"client",null);r(this,"options",null);r(this,"root",null);r(this,"panel",null);r(this,"context",null);r(this,"contextKey","");r(this,"selectedPageKey","");r(this,"currentThread",null);r(this,"conversations",[]);r(this,"messages",[]);r(this,"steps",[]);r(this,"selectedAgentRunId","");r(this,"runLoading",!1);r(this,"runLoadError","");r(this,"copiedAgentRunId","");r(this,"copyFeedbackTimer",null);r(this,"sourceSnapshots",[]);r(this,"sourceUploadStatus","");r(this,"sourceUploadError","");r(this,"sourceLoadError","");r(this,"sourceUploading",!1);r(this,"sourceRefreshTimer",null);r(this,"streaming","");r(this,"asking",!1);r(this,"waitingForFirstContent",!1);r(this,"abortController",null);r(this,"activeRunId",0);r(this,"stoppedRunId",-1);r(this,"answerStopped",!1);r(this,"answerError","");r(this,"conversationError","");r(this,"deletingThreadId","");r(this,"streamFailure","");r(this,"streamDone",null);r(this,"answerAudience","business");r(this,"audienceChanging",!1);r(this,"typewriter",new K(e=>{this.streaming+=e,this.updateStreamingMessage()}))}mount(e){var t;this.unmount(),this.options=e,this.client=new m(e),this.answerAudience=this.loadAnswerAudience(e.appId),this.root=document.createElement("div"),this.root.className="pageops-sdk",((t=e.container)!=null?t:document.body).appendChild(this.root),this.renderClosed()}unmount(){var e;this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.resetAnswerState(),(e=this.root)==null||e.remove(),this.root=null,this.panel=null,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoading=!1,this.runLoadError="",this.clearCopyFeedback(),this.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceLoadError="",this.sourceUploading=!1,this.answerAudience="business",this.audienceChanging=!1}open(){this.root&&(this.root.innerHTML="",this.panel=document.createElement("div"),this.panel.className="po-panel",this.root.appendChild(this.panel),this.loadSources(),this.loadConversations(),this.renderPanel())}close(){this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.renderClosed()}updateContext(e){if(!this.options)return;const t=this.options.appId;this.options={...this.options,...e},this.client=new m(this.options),this.options.appId!==t&&(this.answerAudience=this.loadAnswerAudience(this.options.appId),this.currentThread=null,this.selectedPageKey="",this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError=""),this.context=null,this.contextKey="",this.renderPanel()}renderClosed(){var e;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(e=this.root.querySelector("button"))==null||e.addEventListener("click",()=>this.open()))}async ensureContext(){if(!this.client||!this.options)throw new Error("PageOps SDK 未初始化");const e=this.getPageContext(),t=this.getPageContextKey(e);return this.context&&this.contextKey===t?this.context:(this.context=await this.client.createContext(e),this.contextKey=t,this.context)}getPageContext(){var e,t,s;return{...(s=(t=(e=this.options)==null?void 0:e.getPageContext)==null?void 0:t.call(e))!=null?s:{},userRole:this.answerAudience}}answerAudienceStorageKey(e){return`pageops:answer-audience:${e}`}loadAnswerAudience(e){try{const t=localStorage.getItem(this.answerAudienceStorageKey(e));return S.some(s=>s.value===t)?t:"business"}catch(t){return"business"}}saveAnswerAudience(){if(this.options)try{localStorage.setItem(this.answerAudienceStorageKey(this.options.appId),this.answerAudience)}catch(e){}}async changeAnswerAudience(e){var s;if(this.asking||this.audienceChanging)return;const t=(s=S.find(n=>n.value===e))==null?void 0:s.value;if(!(!t||t===this.answerAudience)){this.answerAudience=t,this.saveAnswerAudience(),this.audienceChanging=!0,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1,this.conversationError="",this.renderPanel();try{await this.newConversation()}catch(n){this.conversationError=n instanceof Error?n.message:"切换回答角色失败,请稍后重试。"}finally{this.audienceChanging=!1,this.renderPanel()}}}getPageContextKey(e){var t,s,n,i,c;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(n=e.title)!=null?n:document.title,(i=e.menuPath)!=null?i:[],(c=e.userRole)!=null?c:""])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceLoadError=""}catch(e){this.sourceLoadError="源码包状态加载失败,连接恢复后将自动重试。"}this.scheduleSourceRefresh(),this.renderPanel()}}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){var s;if(!this.client)return;const e=await this.ensureContext(),t=(s=e.menu_path)!=null&&s.length?e.menu_path.join(" / "):e.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(e.id,t),this.selectedPageKey=this.contextKey,this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel()}async selectThread(e){if(!this.client)return;this.currentThread=e,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(e.id),this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel();const t=[...this.messages].reverse().map(P).find(Boolean);t&&await this.loadAgentRun(t)}async deleteConversation(e){var t;if(!(!this.client||this.asking||this.deletingThreadId)&&window.confirm(`确定删除会话“${e.title}”吗?此操作无法撤销。`)){this.deletingThreadId=e.id,this.conversationError="",this.renderPanel();try{if(await this.client.deleteConversation(e.id),this.conversations=this.conversations.filter(s=>s.id!==e.id),((t=this.currentThread)==null?void 0:t.id)===e.id){this.currentThread=null,this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1;const s=this.conversations[0];s&&await this.selectThread(s)}}catch(s){this.conversationError=s instanceof Error?s.message:"删除问答会话失败"}finally{this.deletingThreadId="",this.renderPanel()}}}async uploadSource(e){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(e),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(e){if(!this.client||this.asking)return;const t=this.questionUnavailableReason();if(t){this.sourceUploadError=t,this.renderPanel();return}this.resetAnswerState();const s=++this.activeRunId,n=new AbortController;this.abortController=n,this.stoppedRunId=-1,this.asking=!0,this.waitingForFirstContent=!0,this.renderPanel();try{const i=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==i&&(this.currentThread=null),this.currentThread||await this.newConversation(),!this.currentThread)throw new Error("无法创建问答会话,请稍后重试。");this.messages.push({id:`local-${Date.now()}`,role:"user",content:e,metadata_json:{}}),this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.renderPanel();const c=await this.client.streamQuestion(this.currentThread.id,e,n.signal);if(!c.ok)throw new Error(await y(c,"服务暂时无法回答,请稍后重试。"));if(!c.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await F(c.body,(a,p)=>this.handleStreamEvent(a,p)),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");if(this.streamFailure)throw new Error(this.streamFailure);if(!this.streamDone)throw new Error("服务响应意外中断,请稍后重试。");if(await this.typewriter.drain(),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");await this.selectThread(this.currentThread)}catch(i){if(s!==this.activeRunId)return;this.typewriter.clear(),this.waitingForFirstContent=!1,s===this.stoppedRunId?this.answerStopped=!0:(this.answerError=i instanceof Error?i.message:"服务异常,请稍后重试。",this.upsertStep({id:"error",title:"执行失败",status:"failed",summary:this.answerError}))}finally{if(s!==this.activeRunId)return;this.asking=!1,this.waitingForFirstContent=!1,this.abortController===n&&(this.abortController=null),this.renderPanel(!0)}}cancelActiveAnswer(e){var t;if(!(!this.asking&&!this.abortController)){if(e){this.stoppedRunId=this.activeRunId,this.answerStopped=!0;const s=this.steps.map(n=>n.status==="running"?{...n,status:"cancelled"}:n);this.steps=s.some(n=>n.status==="cancelled")?s:[...s,{id:"stopped",title:"已停止",status:"cancelled"}]}else this.activeRunId+=1,this.asking=!1;this.typewriter.clear(),this.waitingForFirstContent=!1,(t=this.abortController)==null||t.abort(),this.abortController=null,e&&this.renderPanel()}}handleStreamEvent(e,t){var s,n;if(e==="step"){this.upsertStep(t),this.renderPanel();return}if(e==="delta"){const i=String((s=t.content)!=null?s:"");if(!i)return;this.waitingForFirstContent=!1,this.typewriter.enqueue(i);return}e==="done"&&(this.streamDone=t),e==="error"&&(this.streamFailure=String((n=t.message)!=null?n:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,n;const e=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!e){this.renderPanel();return}e.innerHTML=$(this.streaming);const t=(n=this.panel)==null?void 0:n.querySelector(".po-messages");t&&(t.scrollTop=t.scrollHeight)}resetAnswerState(){this.typewriter.clear(),this.asking=!1,this.waitingForFirstContent=!1,this.answerError="",this.answerStopped=!1,this.streamFailure="",this.streamDone=null,this.streaming=""}upsertStep(e){const t=this.steps.findIndex(s=>s.id===e.id);this.steps=t===-1?[...this.steps,e]:this.steps.map(s=>s.id===e.id?{...s,...e}:s)}async loadAgentRun(e){if(!(!this.client||!e)){this.selectedAgentRunId=e,this.runLoading=!0,this.runLoadError="",this.renderPanel();try{const t=await this.client.getAgentRun(e);if(this.selectedAgentRunId!==e)return;this.steps=t.steps}catch(t){if(this.selectedAgentRunId!==e)return;this.steps=[],this.runLoadError=t instanceof Error?t.message:"执行过程加载失败"}finally{this.selectedAgentRunId===e&&(this.runLoading=!1,this.renderPanel())}}}async copyAgentRunId(e){var t;if(e){try{if((t=navigator.clipboard)!=null&&t.writeText)await navigator.clipboard.writeText(e);else{const s=document.createElement("textarea");if(s.value=e,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.select(),!document.execCommand("copy"))throw new Error("copy_not_supported");s.remove()}this.copiedAgentRunId=e}catch(s){this.copiedAgentRunId=`error:${e}`}this.clearCopyFeedback(!1),this.copyFeedbackTimer=setTimeout(()=>{this.copiedAgentRunId="",this.copyFeedbackTimer=null,this.renderPanel()},1800),this.renderPanel()}}clearCopyFeedback(e=!0){this.copyFeedbackTimer&&clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=null,e&&(this.copiedAgentRunId="")}latestAnalysisStatus(){var e,t,s;return String((s=(t=(e=this.sourceSnapshots[0])==null?void 0:e.metadata)==null?void 0:t.analysis_status)!=null?s:"")}isProjectMemoryUpdating(){return["pending","running"].includes(this.latestAnalysisStatus())}questionUnavailableReason(){return this.sourceLoadError&&!this.sourceSnapshots.length?"暂时无法读取项目共享代码包,请检查 PageOps 服务连接。":this.sourceSnapshots.length?this.isProjectMemoryUpdating()?"项目记忆正在更新,完成前暂不能问答。":this.latestAnalysisStatus()==="failed"?"项目记忆更新失败,请重新上传或重新索引。":"":"请先上传代码包后再提问。"}scheduleSourceRefresh(){this.stopSourceRefresh(),!(!this.sourceLoadError&&!this.isProjectMemoryUpdating())&&(this.sourceRefreshTimer=setTimeout(()=>void this.loadSources(),1500))}stopSourceRefresh(){this.sourceRefreshTimer&&clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null}renderPanel(e=this.asking){if(!this.panel)return;const t=this.questionUnavailableReason(),s=t||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),n=!!(t||this.asking),i=t?'<button type="submit" disabled>暂不可提问</button>':this.asking?'<button class="po-stop" type="button" data-action="stop-answer" aria-label="停止输出" title="停止输出"><span aria-hidden="true"></span></button>':'<button type="submit">发送</button>',c=S.map(a=>`
|
|
4
4
|
<button type="button" data-audience="${a.value}" aria-pressed="${a.value===this.answerAudience}" ${this.asking||this.audienceChanging?"disabled":""}>${a.label}</button>
|
|
5
5
|
`).join("");if(this.panel.innerHTML=`
|
|
6
6
|
<aside class="po-sidebar">
|
|
@@ -22,12 +22,12 @@
|
|
|
22
22
|
${this.messages.map(a=>this.renderMessage(a)).join("")}
|
|
23
23
|
${this.renderAnswerState()}
|
|
24
24
|
</section>
|
|
25
|
-
<form class="po-composer"><textarea ${
|
|
25
|
+
<form class="po-composer"><textarea ${n?"disabled":""} placeholder="${l(s)}"></textarea>${i}</form>
|
|
26
26
|
</main>
|
|
27
27
|
<aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
|
|
28
|
-
`,this.bindPanelEvents(),e){const a=this.panel.querySelector(".po-messages");a&&(a.scrollTop=a.scrollHeight)}}renderAnswerState(){const e=this.asking&&this.waitingForFirstContent?'<article class="po-message assistant waiting" role="status" aria-live="polite"><b>PageOps 分析</b><div class="po-ai-waiting"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在理解问题并检索证据</span></div></article>':"",t=this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div><span data-streaming-content>${$(this.streaming)}</span>${this.asking?'<span class="po-typing-cursor" aria-hidden="true"></span>':""}</div></article>`:"",s=this.answerError?`<article class="po-message assistant answer-error" role="alert"><b>PageOps 分析</b><strong>本次回答失败</strong><div>${l(this.answerError)}</div></article>`:"",
|
|
28
|
+
`,this.bindPanelEvents(),e){const a=this.panel.querySelector(".po-messages");a&&(a.scrollTop=a.scrollHeight)}}renderAnswerState(){const e=this.asking&&this.waitingForFirstContent?'<article class="po-message assistant waiting" role="status" aria-live="polite"><b>PageOps 分析</b><div class="po-ai-waiting"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在理解问题并检索证据</span></div></article>':"",t=this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div><span data-streaming-content>${$(this.streaming)}</span>${this.asking?'<span class="po-typing-cursor" aria-hidden="true"></span>':""}</div></article>`:"",s=this.answerError?`<article class="po-message assistant answer-error" role="alert"><b>PageOps 分析</b><strong>本次回答失败</strong><div>${l(this.answerError)}</div></article>`:"",n=this.answerStopped?'<div class="po-stream-stopped" role="status">已停止输出</div>':"";return`${e}${t}${n}${s}`}renderMessage(e){const t=P(e),s=t&&t===this.selectedAgentRunId,n=this.copiedAgentRunId===t,i=this.copiedAgentRunId===`error:${t}`,c=e.role==="assistant"&&t?`<footer class="po-answer-meta ${s?"selected":""}">
|
|
29
29
|
<span class="po-run-id" title="${l(t)}">问答流水号 <code>${l(t)}</code></span>
|
|
30
|
-
<button type="button" data-copy-run="${l(t)}">${
|
|
30
|
+
<button type="button" data-copy-run="${l(t)}">${n?"已复制":i?"复制失败":"复制流水号"}</button>
|
|
31
31
|
<button type="button" data-view-run="${l(t)}" aria-pressed="${s}">${s?"正在查看":"查看执行过程"}</button>
|
|
32
32
|
</footer>`:"";return`<article class="po-message ${e.role} ${s?"run-selected":""}" data-message="${l(e.id)}">
|
|
33
33
|
<b>${e.role==="user"?"你":"PageOps 分析"}</b>
|
|
@@ -46,11 +46,11 @@
|
|
|
46
46
|
${this.sourceLoadError?`<p class="po-upload-error">${l(this.sourceLoadError)}</p>`:""}
|
|
47
47
|
${this.sourceUploadError?`<p class="po-upload-error">${l(this.sourceUploadError)}</p>`:""}
|
|
48
48
|
</div>
|
|
49
|
-
`}renderSourceItem(e){var a,p,g;const t=e.filename||"未命名代码包",s=e.created_at?C(e.created_at):"刚刚上传",
|
|
49
|
+
`}renderSourceItem(e){var a,p,g;const t=e.filename||"未命名代码包",s=e.created_at?C(e.created_at):"刚刚上传",n=j(e.archive_bytes||e.total_bytes||0),i=String((p=(a=e.metadata)==null?void 0:a.analysis_status)!=null?p:"unknown"),c=(g={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[i])!=null?g:"项目记忆状态未知";return`<article class="po-source-item"><strong>${l(t)}</strong><span>${l(s)} · ${l(n)}</span><span>${l(c)}</span></article>`}renderSteps(){return this.runLoading?'<div class="po-trace-state"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在恢复本次执行过程</span></div>':this.runLoadError?`<div class="po-trace-state failed" role="alert">${l(this.runLoadError)}</div>`:(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",summary:"发送问题后,这里会展示完整分析过程。"}]).map(t=>{var c,a,p;const s=(c=t.metrics)!=null&&c.length?`<div class="po-step-metrics">${t.metrics.map(g=>`<span>${l(g)}</span>`).join("")}</div>`:"",n=(a=t.details)!=null&&a.length?`<div class="po-step-details">${t.details.map(g=>`<div><span>${l(g.label)}</span><p>${l(g.value)}</p></div>`).join("")}</div>`:"",i=!!(s||n);return`<details class="po-step ${t.status}" ${t.status==="running"||t.status==="failed"?"open":""} ${i?"":"data-static"}>
|
|
50
50
|
<summary>
|
|
51
51
|
<span class="po-step-dot" aria-hidden="true"></span>
|
|
52
52
|
<span class="po-step-copy"><strong>${l(t.title)}</strong><small>${l((p=t.summary)!=null?p:"")}</small></span>
|
|
53
53
|
<span class="po-step-status">${O(t.status)}</span>
|
|
54
54
|
</summary>
|
|
55
|
-
${s}${
|
|
56
|
-
</details>`}).join("")}bindPanelEvents(){var e,t,s,i,
|
|
55
|
+
${s}${n}
|
|
56
|
+
</details>`}).join("")}bindPanelEvents(){var e,t,s,n,i,c,a,p,g,b,R,T,I,k,x,L,q;(t=(e=this.panel)==null?void 0:e.querySelector('[data-action="new"]'))==null||t.addEventListener("click",()=>void this.newConversation()),(n=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||n.addEventListener("click",()=>this.close()),(c=(i=this.panel)==null?void 0:i.querySelector('[data-action="stop-answer"]'))==null||c.addEventListener("click",()=>this.cancelActiveAnswer(!0)),(a=this.panel)==null||a.querySelectorAll("[data-audience]").forEach(d=>{d.addEventListener("click",()=>{var h;return void this.changeAnswerAudience((h=d.dataset.audience)!=null?h:"")})}),(g=(p=this.panel)==null?void 0:p.querySelector('[data-action="upload-source"]'))==null||g.addEventListener("change",d=>{var u;const h=(u=d.target.files)==null?void 0:u[0];h&&this.uploadSource(h)}),(b=this.panel)==null||b.querySelectorAll("[data-thread]").forEach(d=>{d.addEventListener("click",()=>{const h=this.conversations.find(u=>u.id===d.dataset.thread);h&&this.selectThread(h)})}),(R=this.panel)==null||R.querySelectorAll("[data-delete-thread]").forEach(d=>{d.addEventListener("click",h=>{h.stopPropagation();const u=this.conversations.find(v=>v.id===d.dataset.deleteThread);u&&this.deleteConversation(u)})}),(T=this.panel)==null||T.querySelectorAll("[data-view-run]").forEach(d=>{d.addEventListener("click",h=>{var u;h.stopPropagation(),this.loadAgentRun((u=d.dataset.viewRun)!=null?u:"")})}),(I=this.panel)==null||I.querySelectorAll("[data-copy-run]").forEach(d=>{d.addEventListener("click",h=>{var u;h.stopPropagation(),this.copyAgentRunId((u=d.dataset.copyRun)!=null?u:"")})}),(x=(k=this.panel)==null?void 0:k.querySelector("form"))==null||x.addEventListener("submit",d=>{var v;d.preventDefault();const h=(v=this.panel)==null?void 0:v.querySelector("textarea"),u=h==null?void 0:h.value.trim();u&&(h.value="",this.ask(u))}),(q=(L=this.panel)==null?void 0:L.querySelector("textarea"))==null||q.addEventListener("keydown",d=>{var u,v;const h=d;h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),(v=(u=this.panel)==null?void 0:u.querySelector("form"))==null||v.requestSubmit())})}}function l(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function P(o){var t;const e=(t=o.metadata_json)==null?void 0:t.agent_run_id;return typeof e=="string"?e:""}function C(o){return new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(new Date(o))}function j(o){if(!o)return"0 B";const e=["B","KB","MB","GB"];let t=o,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s+=1;return`${t>=10||s===0?t.toFixed(0):t.toFixed(1)} ${e[s]}`}function O(o){return{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",cancelled:"已停止"}[o]}const D=new _;f.PageOpsSDK=D,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
|