@pageops/sdk 0.1.20 → 0.1.22

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.
@@ -67,7 +67,7 @@ class K {
67
67
  }
68
68
  base() {
69
69
  const e = this.options.apiBase.replace(/\/$/, "");
70
- return e.endsWith("/api") || e.endsWith("/dc/ai") ? e : `${e}/api`;
70
+ return e.endsWith("/api") || e.endsWith("/dc/ai") ? e : `${e}/dc/ai`;
71
71
  }
72
72
  }
73
73
  async function z(a, e) {
@@ -75,7 +75,7 @@ async function z(a, e) {
75
75
  return typeof (t == null ? void 0 : t.message) == "string" && t.message.trim() ? t.message : e;
76
76
  }
77
77
  function D(a) {
78
- return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
78
+ return String(a == null ? "" : a).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
79
79
  }
80
80
  function v(a) {
81
81
  return D(a).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
@@ -635,7 +635,7 @@ class V {
635
635
  }
636
636
  }
637
637
  function l(a) {
638
- return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
638
+ return String(a == null ? "" : a).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
639
639
  }
640
640
  function M(a) {
641
641
  var t;
@@ -1,4 +1,4 @@
1
- (function(y,m){typeof exports=="object"&&typeof module!="undefined"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(y=typeof globalThis!="undefined"?globalThis:y||self,m(y.PageOpsSDK={}))})(this,(function(y){"use strict";var X=Object.defineProperty;var Y=(y,m,b)=>m in y?X(y,m,{enumerable:!0,configurable:!0,writable:!0,value:b}):y[m]=b;var i=(y,m,b)=>Y(y,typeof m!="symbol"?m+"":m,b);class m{constructor(e){this.options=e}async createContext(e=(r=>(r=(t=>(s=>(s=(t=this.options).getPageContext)==null?void 0:s.call(t))())())!=null?r:{})()){var n,c,p;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:e.route,url:(n=e.url)!=null?n:location.href,title:(c=e.title)!=null?c:document.title,menu_path:(p=e.menuPath)!=null?p:[],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,t){const s=new FormData;return s.append("file",e),t.tag&&s.append("tag",t.tag),t.branch&&s.append("branch",t.branch),t.remark&&s.append("remark",t.remark),s.append("uploader",t.uploader||"未知用户"),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:s,headers:{}})}streamQuestion(e,t,s,r){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,user_role:s}),signal:r})}async request(e,t){var c,p;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:{}},r=await fetch(`${this.base()}${e}`,{...t,headers:s});if(r.status===204)return;const n=await r.json();if(!r.ok)throw new Error((p=n.message)!=null?p:"PageOps 请求失败");return n}base(){const e=this.options.apiBase.replace(/\/$/,"");return e.endsWith("/api")||e.endsWith("/dc/ai")?e:`${e}/api`}}async function b(a,e){const t=await a.json().catch(()=>null);return typeof(t==null?void 0:t.message)=="string"&&t.message.trim()?t.message:e}function x(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function S(a){return x(a).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function H(a,e){const t=a[e],s=a[e+1];if(!(t!=null&&t.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const r=[];let n=e;for(;n<a.length&&a[n].includes("|")&&a[n].trim();)r.push(a[n]),n+=1;const c=g=>g.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(o=>S(o.trim())),p=c(r[0]).map(g=>`<th>${g}</th>`).join(""),f=r.slice(2).map(g=>`<tr>${c(g).map(o=>`<td>${o}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${p}</tr></thead><tbody>${f}</tbody></table>`,next:n}}function k(a){const e=a.split(`
1
+ (function(y,m){typeof exports=="object"&&typeof module!="undefined"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(y=typeof globalThis!="undefined"?globalThis:y||self,m(y.PageOpsSDK={}))})(this,(function(y){"use strict";var X=Object.defineProperty;var Y=(y,m,b)=>m in y?X(y,m,{enumerable:!0,configurable:!0,writable:!0,value:b}):y[m]=b;var i=(y,m,b)=>Y(y,typeof m!="symbol"?m+"":m,b);class m{constructor(e){this.options=e}async createContext(e=(r=>(r=(t=>(s=>(s=(t=this.options).getPageContext)==null?void 0:s.call(t))())())!=null?r:{})()){var n,c,p;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:e.route,url:(n=e.url)!=null?n:location.href,title:(c=e.title)!=null?c:document.title,menu_path:(p=e.menuPath)!=null?p:[],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,t){const s=new FormData;return s.append("file",e),t.tag&&s.append("tag",t.tag),t.branch&&s.append("branch",t.branch),t.remark&&s.append("remark",t.remark),s.append("uploader",t.uploader||"未知用户"),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:s,headers:{}})}streamQuestion(e,t,s,r){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,user_role:s}),signal:r})}async request(e,t){var c,p;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:{}},r=await fetch(`${this.base()}${e}`,{...t,headers:s});if(r.status===204)return;const n=await r.json();if(!r.ok)throw new Error((p=n.message)!=null?p:"PageOps 请求失败");return n}base(){const e=this.options.apiBase.replace(/\/$/,"");return e.endsWith("/api")||e.endsWith("/dc/ai")?e:`${e}/dc/ai`}}async function b(a,e){const t=await a.json().catch(()=>null);return typeof(t==null?void 0:t.message)=="string"&&t.message.trim()?t.message:e}function x(a){return String(a==null?"":a).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function S(a){return x(a).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function H(a,e){const t=a[e],s=a[e+1];if(!(t!=null&&t.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const r=[];let n=e;for(;n<a.length&&a[n].includes("|")&&a[n].trim();)r.push(a[n]),n+=1;const c=g=>g.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(o=>S(o.trim())),p=c(r[0]).map(g=>`<th>${g}</th>`).join(""),f=r.slice(2).map(g=>`<tr>${c(g).map(o=>`<td>${o}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${p}</tr></thead><tbody>${f}</tbody></table>`,next:n}}function k(a){const e=a.split(`
2
2
  `),t=[];for(let s=0;s<e.length;s+=1){const r=e[s];if(r.trim().startsWith("```")){const c=[];for(s+=1;s<e.length&&!e[s].trim().startsWith("```");)c.push(e[s]),s+=1;t.push(`<pre><code>${x(c.join(`
3
3
  `))}</code></pre>`);continue}const n=H(e,s);if(n){t.push(n.html),s=n.next-1;continue}r.startsWith("### ")?t.push(`<h4>${S(r.slice(4))}</h4>`):r.startsWith("## ")?t.push(`<h3>${S(r.slice(3))}</h3>`):r.startsWith("# ")?t.push(`<h2>${S(r.slice(2))}</h2>`):r.startsWith("- ")?t.push(`<li>${S(r.slice(2))}</li>`):r.trim()?t.push(`<p>${S(r)}</p>`):t.push("<br>")}return t.join("")}async function z(a,e){var n;const t=a.getReader(),s=new TextDecoder;let r="";for(;;){const{done:c,value:p}=await t.read();if(c){r+=s.decode();break}r+=s.decode(p,{stream:!0});const f=r.split(/\r?\n\r?\n/);r=(n=f.pop())!=null?n:"";for(const g of f)q(g,e)}r.trim()&&q(r,e)}function q(a,e){var r,n;const t=(r=a.match(/^event:\s*(.+)$/m))==null?void 0:r[1],s=(n=a.match(/^data:\s*(.+)$/m))==null?void 0:n[1];t&&s&&e(t,JSON.parse(s))}class N{constructor(e,t=16){i(this,"queue",[]);i(this,"timer",null);i(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 I=[{value:"product",label:"产品"},{value:"business",label:"业务"},{value:"developer",label:"研发"},{value:"tester",label:"测试"}];class J{constructor(){i(this,"client",null);i(this,"options",null);i(this,"root",null);i(this,"panel",null);i(this,"context",null);i(this,"contextKey","");i(this,"selectedPageKey","");i(this,"currentThread",null);i(this,"conversations",[]);i(this,"messages",[]);i(this,"steps",[]);i(this,"selectedAgentRunId","");i(this,"runLoading",!1);i(this,"runLoadError","");i(this,"copiedAgentRunId","");i(this,"copyFeedbackTimer",null);i(this,"sourceSnapshots",[]);i(this,"sourceUploadStatus","");i(this,"sourceUploadError","");i(this,"sourceLoadError","");i(this,"sourceUploading",!1);i(this,"sourceRefreshTimer",null);i(this,"streaming","");i(this,"asking",!1);i(this,"waitingForFirstContent",!1);i(this,"abortController",null);i(this,"activeRunId",0);i(this,"stoppedRunId",-1);i(this,"answerStopped",!1);i(this,"answerError","");i(this,"conversationError","");i(this,"deletingThreadId","");i(this,"streamFailure","");i(this,"streamDone",null);i(this,"answerAudience","business");i(this,"typewriter",new N(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"}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 I.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){}}changeAnswerAudience(e){var s;if(this.asking)return;const t=(s=I.find(r=>r.value===e))==null?void 0:s.value;!t||t===this.answerAudience||(this.answerAudience=t,this.saveAnswerAudience(),this.renderPanel())}getPageContextKey(e){var t,s,r,n;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(r=e.title)!=null?r:document.title,(n=e.menuPath)!=null?n:[]])}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(L).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,t){var s;if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(e,{...t,uploader:(s=this.options)==null?void 0:s.uploader}),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(r){this.sourceUploadError=r instanceof Error?r.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,r=new AbortController;this.abortController=r,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,this.answerAudience,r.signal);if(!c.ok)throw new Error(await b(c,"服务暂时无法回答,请稍后重试。"));if(!c.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await z(c.body,(p,f)=>this.handleStreamEvent(p,f)),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===r&&(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(r=>r.status==="running"?{...r,status:"cancelled"}:r);this.steps=s.some(r=>r.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,r;if(e==="step"){this.upsertStep(t),this.renderExecutionSteps(!0);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((r=t.message)!=null?r:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,r;const e=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!e){this.renderPanel();return}e.innerHTML=k(this.streaming);const t=(r=this.panel)==null?void 0:r.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.updateCopyFeedback()},1800),this.updateCopyFeedback()}}updateCopyFeedback(){var e;(e=this.panel)==null||e.querySelectorAll("[data-copy-run]").forEach(t=>{var r;const s=(r=t.dataset.copyRun)!=null?r:"";t.textContent=this.copiedAgentRunId===s?"已复制":this.copiedAgentRunId===`error:${s}`?"复制失败":"复制流水号"})}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,t=!1){var g;if(!this.panel)return;const s=(g=this.panel.querySelector(".po-messages"))==null?void 0:g.scrollTop,r=this.questionUnavailableReason(),n=r||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),c=!!(r||this.asking),p=r?'<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>',f=I.map(o=>`
4
4
  <button type="button" data-audience="${o.value}" aria-pressed="${o.value===this.answerAudience}" ${this.asking?"disabled":""}>${o.label}</button>
@@ -59,4 +59,4 @@
59
59
  <span class="po-step-status">${V(t.status)}</span>
60
60
  </summary>
61
61
  ${r}
62
- </details>`}).join("")}renderExecutionSteps(e=!1){var s,r;const t=(s=this.panel)==null?void 0:s.querySelector(".po-steps");if(t&&(t.innerHTML=this.renderSteps(),e)){const n=(r=this.panel)==null?void 0:r.querySelector(".po-trace > section");n&&(n.scrollTop=n.scrollHeight)}}bindPanelEvents(){var e,t,s,r,n,c,p,f,g,o,w,$,E,A,T,R,C,P;(t=(e=this.panel)==null?void 0:e.querySelector('[data-action="new"]'))==null||t.addEventListener("click",()=>void this.newConversation()),(r=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||r.addEventListener("click",()=>this.close()),(c=(n=this.panel)==null?void 0:n.querySelector('[data-action="stop-answer"]'))==null||c.addEventListener("click",()=>this.cancelActiveAnswer(!0)),(p=this.panel)==null||p.querySelectorAll("[data-audience]").forEach(h=>{h.addEventListener("click",()=>{var d;return this.changeAnswerAudience((d=h.dataset.audience)!=null?d:"")})}),(g=(f=this.panel)==null?void 0:f.querySelector('[data-action="upload-source"]'))==null||g.addEventListener("change",h=>{var U,_,K,j,O,M,D,B,W;const d=(U=h.target.files)==null?void 0:U[0];if(!d)return;const u=(K=(_=this.panel)==null?void 0:_.querySelector('[name="source-reference"]:checked'))==null?void 0:K.value,v=(M=(O=(j=this.panel)==null?void 0:j.querySelector(".po-source-reference-value"))==null?void 0:O.value.trim())!=null?M:"",Z=(W=(B=(D=this.panel)==null?void 0:D.querySelector(".po-source-remark"))==null?void 0:B.value.trim())!=null?W:"";if(!v||u!=="tag"&&u!=="branch"){this.sourceUploadError="请选择 Tag 或 Branch,并填写对应名称。",this.renderPanel();return}this.uploadSource(d,{[u]:v,remark:Z})}),(o=this.panel)==null||o.querySelectorAll('[name="source-reference"]').forEach(h=>{h.addEventListener("change",()=>{var u;const d=(u=this.panel)==null?void 0:u.querySelector(".po-source-reference-value");d&&(d.placeholder=`请输入 ${h.value==="tag"?"Tag":"Branch"} 名称`)})}),(w=this.panel)==null||w.querySelectorAll("[data-thread]").forEach(h=>{h.addEventListener("click",()=>{const d=this.conversations.find(u=>u.id===h.dataset.thread);d&&this.selectThread(d)})}),($=this.panel)==null||$.querySelectorAll("[data-delete-thread]").forEach(h=>{h.addEventListener("click",d=>{d.stopPropagation();const u=this.conversations.find(v=>v.id===h.dataset.deleteThread);u&&this.deleteConversation(u)})}),(E=this.panel)==null||E.querySelectorAll("[data-view-run]").forEach(h=>{h.addEventListener("click",d=>{var u;d.stopPropagation(),this.loadAgentRun((u=h.dataset.viewRun)!=null?u:"")})}),(A=this.panel)==null||A.querySelectorAll("[data-copy-run]").forEach(h=>{h.addEventListener("click",d=>{var u;d.stopPropagation(),this.copyAgentRunId((u=h.dataset.copyRun)!=null?u:"")})}),(R=(T=this.panel)==null?void 0:T.querySelector("form"))==null||R.addEventListener("submit",h=>{var v;h.preventDefault();const d=(v=this.panel)==null?void 0:v.querySelector("textarea"),u=d==null?void 0:d.value.trim();u&&(d.value="",this.ask(u))}),(P=(C=this.panel)==null?void 0:C.querySelector("textarea"))==null||P.addEventListener("keydown",h=>{var u,v;const d=h;d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),(v=(u=this.panel)==null?void 0:u.querySelector("form"))==null||v.requestSubmit())})}}function l(a){return a.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function L(a){var t;const e=(t=a.metadata_json)==null?void 0:t.agent_run_id;return typeof e=="string"?e:""}function F(a){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(a))}function Q(a){if(!a)return"0 B";const e=["B","KB","MB","GB"];let t=a,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 V(a){return{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",cancelled:"已停止"}[a]}const G=new J;y.PageOpsSDK=G,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));
62
+ </details>`}).join("")}renderExecutionSteps(e=!1){var s,r;const t=(s=this.panel)==null?void 0:s.querySelector(".po-steps");if(t&&(t.innerHTML=this.renderSteps(),e)){const n=(r=this.panel)==null?void 0:r.querySelector(".po-trace > section");n&&(n.scrollTop=n.scrollHeight)}}bindPanelEvents(){var e,t,s,r,n,c,p,f,g,o,w,$,E,A,T,R,C,P;(t=(e=this.panel)==null?void 0:e.querySelector('[data-action="new"]'))==null||t.addEventListener("click",()=>void this.newConversation()),(r=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||r.addEventListener("click",()=>this.close()),(c=(n=this.panel)==null?void 0:n.querySelector('[data-action="stop-answer"]'))==null||c.addEventListener("click",()=>this.cancelActiveAnswer(!0)),(p=this.panel)==null||p.querySelectorAll("[data-audience]").forEach(h=>{h.addEventListener("click",()=>{var d;return this.changeAnswerAudience((d=h.dataset.audience)!=null?d:"")})}),(g=(f=this.panel)==null?void 0:f.querySelector('[data-action="upload-source"]'))==null||g.addEventListener("change",h=>{var U,_,K,j,O,M,D,B,W;const d=(U=h.target.files)==null?void 0:U[0];if(!d)return;const u=(K=(_=this.panel)==null?void 0:_.querySelector('[name="source-reference"]:checked'))==null?void 0:K.value,v=(M=(O=(j=this.panel)==null?void 0:j.querySelector(".po-source-reference-value"))==null?void 0:O.value.trim())!=null?M:"",Z=(W=(B=(D=this.panel)==null?void 0:D.querySelector(".po-source-remark"))==null?void 0:B.value.trim())!=null?W:"";if(!v||u!=="tag"&&u!=="branch"){this.sourceUploadError="请选择 Tag 或 Branch,并填写对应名称。",this.renderPanel();return}this.uploadSource(d,{[u]:v,remark:Z})}),(o=this.panel)==null||o.querySelectorAll('[name="source-reference"]').forEach(h=>{h.addEventListener("change",()=>{var u;const d=(u=this.panel)==null?void 0:u.querySelector(".po-source-reference-value");d&&(d.placeholder=`请输入 ${h.value==="tag"?"Tag":"Branch"} 名称`)})}),(w=this.panel)==null||w.querySelectorAll("[data-thread]").forEach(h=>{h.addEventListener("click",()=>{const d=this.conversations.find(u=>u.id===h.dataset.thread);d&&this.selectThread(d)})}),($=this.panel)==null||$.querySelectorAll("[data-delete-thread]").forEach(h=>{h.addEventListener("click",d=>{d.stopPropagation();const u=this.conversations.find(v=>v.id===h.dataset.deleteThread);u&&this.deleteConversation(u)})}),(E=this.panel)==null||E.querySelectorAll("[data-view-run]").forEach(h=>{h.addEventListener("click",d=>{var u;d.stopPropagation(),this.loadAgentRun((u=h.dataset.viewRun)!=null?u:"")})}),(A=this.panel)==null||A.querySelectorAll("[data-copy-run]").forEach(h=>{h.addEventListener("click",d=>{var u;d.stopPropagation(),this.copyAgentRunId((u=h.dataset.copyRun)!=null?u:"")})}),(R=(T=this.panel)==null?void 0:T.querySelector("form"))==null||R.addEventListener("submit",h=>{var v;h.preventDefault();const d=(v=this.panel)==null?void 0:v.querySelector("textarea"),u=d==null?void 0:d.value.trim();u&&(d.value="",this.ask(u))}),(P=(C=this.panel)==null?void 0:C.querySelector("textarea"))==null||P.addEventListener("keydown",h=>{var u,v;const d=h;d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),(v=(u=this.panel)==null?void 0:u.querySelector("form"))==null||v.requestSubmit())})}}function l(a){return String(a==null?"":a).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function L(a){var t;const e=(t=a.metadata_json)==null?void 0:t.agent_run_id;return typeof e=="string"?e:""}function F(a){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(a))}function Q(a){if(!a)return"0 B";const e=["B","KB","MB","GB"];let t=a,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 V(a){return{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",cancelled:"已停止"}[a]}const G=new J;y.PageOpsSDK=G,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pageops/sdk",
3
- "version": "0.1.20",
3
+ "version": "0.1.22",
4
4
  "description": "PageOps embeddable frontend SDK",
5
5
  "type": "module",
6
6
  "main": "dist/pageops-sdk.umd.cjs",