@pageops/sdk 0.1.15 → 0.1.16

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/index.d.ts CHANGED
@@ -64,6 +64,7 @@ declare class PageOpsSDKController {
64
64
  private upsertStep;
65
65
  private loadAgentRun;
66
66
  private copyAgentRunId;
67
+ private updateCopyFeedback;
67
68
  private clearCopyFeedback;
68
69
  private latestAnalysisStatus;
69
70
  private isProjectMemoryUpdating;
@@ -6,7 +6,7 @@ class K {
6
6
  this.options = e;
7
7
  }
8
8
  async createContext(e = ((r) => (r = ((t) => ((s) => (s = (t = this.options).getPageContext) == null ? void 0 : s.call(t))())()) != null ? r : {})()) {
9
- var n, l, p;
9
+ var n, c, p;
10
10
  return this.request("/context/session", {
11
11
  method: "POST",
12
12
  body: JSON.stringify({
@@ -14,7 +14,7 @@ class K {
14
14
  env: this.options.env,
15
15
  route: e.route,
16
16
  url: (n = e.url) != null ? n : location.href,
17
- title: (l = e.title) != null ? l : document.title,
17
+ title: (c = e.title) != null ? c : document.title,
18
18
  menu_path: (p = e.menuPath) != null ? p : [],
19
19
  tenant_id: e.tenantId,
20
20
  user_role: e.userRole,
@@ -58,8 +58,8 @@ class K {
58
58
  });
59
59
  }
60
60
  async request(e, t) {
61
- var l, p;
62
- const s = (t == null ? void 0 : t.body) instanceof FormData ? t.headers : { "content-type": "application/json", ...(l = t == null ? void 0 : t.headers) != null ? l : {} }, r = await fetch(`${this.base()}${e}`, { ...t, headers: s });
61
+ var c, p;
62
+ 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 });
63
63
  if (r.status === 204) return;
64
64
  const n = await r.json();
65
65
  if (!r.ok) throw new Error((p = n.message) != null ? p : "PageOps 请求失败");
@@ -74,11 +74,11 @@ async function H(a, e) {
74
74
  const t = await a.json().catch(() => null);
75
75
  return typeof (t == null ? void 0 : t.message) == "string" && t.message.trim() ? t.message : e;
76
76
  }
77
- function M(a) {
77
+ function D(a) {
78
78
  return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
79
79
  }
80
80
  function v(a) {
81
- return M(a).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
81
+ return D(a).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
82
82
  }
83
83
  function N(a, e) {
84
84
  const t = a[e], s = a[e + 1];
@@ -87,19 +87,19 @@ function N(a, e) {
87
87
  let n = e;
88
88
  for (; n < a.length && a[n].includes("|") && a[n].trim(); )
89
89
  r.push(a[n]), n += 1;
90
- const l = (g) => g.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((f) => v(f.trim())), p = l(r[0]).map((g) => `<th>${g}</th>`).join(""), o = r.slice(2).map((g) => `<tr>${l(g).map((f) => `<td>${f}</td>`).join("")}</tr>`).join("");
91
- return { html: `<table><thead><tr>${p}</tr></thead><tbody>${o}</tbody></table>`, next: n };
90
+ const c = (g) => g.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((o) => v(o.trim())), p = c(r[0]).map((g) => `<th>${g}</th>`).join(""), m = r.slice(2).map((g) => `<tr>${c(g).map((o) => `<td>${o}</td>`).join("")}</tr>`).join("");
91
+ return { html: `<table><thead><tr>${p}</tr></thead><tbody>${m}</tbody></table>`, next: n };
92
92
  }
93
- function R(a) {
93
+ function T(a) {
94
94
  const e = a.split(`
95
95
  `), t = [];
96
96
  for (let s = 0; s < e.length; s += 1) {
97
97
  const r = e[s];
98
98
  if (r.trim().startsWith("```")) {
99
- const l = [];
99
+ const c = [];
100
100
  for (s += 1; s < e.length && !e[s].trim().startsWith("```"); )
101
- l.push(e[s]), s += 1;
102
- t.push(`<pre><code>${M(l.join(`
101
+ c.push(e[s]), s += 1;
102
+ t.push(`<pre><code>${D(c.join(`
103
103
  `))}</code></pre>`);
104
104
  continue;
105
105
  }
@@ -117,15 +117,15 @@ async function J(a, e) {
117
117
  const t = a.getReader(), s = new TextDecoder();
118
118
  let r = "";
119
119
  for (; ; ) {
120
- const { done: l, value: p } = await t.read();
121
- if (l) {
120
+ const { done: c, value: p } = await t.read();
121
+ if (c) {
122
122
  r += s.decode();
123
123
  break;
124
124
  }
125
125
  r += s.decode(p, { stream: !0 });
126
- const o = r.split(/\r?\n\r?\n/);
127
- r = (n = o.pop()) != null ? n : "";
128
- for (const g of o) j(g, e);
126
+ const m = r.split(/\r?\n\r?\n/);
127
+ r = (n = m.pop()) != null ? n : "";
128
+ for (const g of m) j(g, e);
129
129
  }
130
130
  r.trim() && j(r, e);
131
131
  }
@@ -162,7 +162,7 @@ class Q {
162
162
  for (const e of this.drainWaiters.splice(0)) e();
163
163
  }
164
164
  }
165
- const T = [
165
+ const C = [
166
166
  { value: "product", label: "产品" },
167
167
  { value: "business", label: "业务" },
168
168
  { value: "developer", label: "研发" },
@@ -250,7 +250,7 @@ class V {
250
250
  loadAnswerAudience(e) {
251
251
  try {
252
252
  const t = localStorage.getItem(this.answerAudienceStorageKey(e));
253
- return T.some((s) => s.value === t) ? t : "business";
253
+ return C.some((s) => s.value === t) ? t : "business";
254
254
  } catch (t) {
255
255
  return "business";
256
256
  }
@@ -265,7 +265,7 @@ class V {
265
265
  changeAnswerAudience(e) {
266
266
  var s;
267
267
  if (this.asking) return;
268
- const t = (s = T.find((r) => r.value === e)) == null ? void 0 : s.value;
268
+ const t = (s = C.find((r) => r.value === e)) == null ? void 0 : s.value;
269
269
  !t || t === this.answerAudience || (this.answerAudience = t, this.saveAnswerAudience(), this.renderPanel());
270
270
  }
271
271
  getPageContextKey(e) {
@@ -346,10 +346,10 @@ class V {
346
346
  const n = this.getPageContextKey(this.getPageContext());
347
347
  if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== n && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) throw new Error("无法创建问答会话,请稍后重试。");
348
348
  this.messages.push({ id: `local-${Date.now()}`, role: "user", content: e, metadata_json: {} }), this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.renderPanel();
349
- const l = await this.client.streamQuestion(this.currentThread.id, e, this.answerAudience, r.signal);
350
- if (!l.ok) throw new Error(await H(l, "服务暂时无法回答,请稍后重试。"));
351
- if (!l.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
352
- if (await J(l.body, (p, o) => this.handleStreamEvent(p, o)), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
349
+ const c = await this.client.streamQuestion(this.currentThread.id, e, this.answerAudience, r.signal);
350
+ if (!c.ok) throw new Error(await H(c, "服务暂时无法回答,请稍后重试。"));
351
+ if (!c.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
352
+ if (await J(c.body, (p, m) => this.handleStreamEvent(p, m)), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
353
353
  if (this.streamFailure) throw new Error(this.streamFailure);
354
354
  if (!this.streamDone) throw new Error("服务响应意外中断,请稍后重试。");
355
355
  if (await this.typewriter.drain(), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
@@ -395,7 +395,7 @@ class V {
395
395
  this.renderPanel();
396
396
  return;
397
397
  }
398
- e.innerHTML = R(this.streaming);
398
+ e.innerHTML = T(this.streaming);
399
399
  const t = (r = this.panel) == null ? void 0 : r.querySelector(".po-messages");
400
400
  t && (t.scrollTop = t.scrollHeight);
401
401
  }
@@ -437,10 +437,18 @@ class V {
437
437
  this.copiedAgentRunId = `error:${e}`;
438
438
  }
439
439
  this.clearCopyFeedback(!1), this.copyFeedbackTimer = setTimeout(() => {
440
- this.copiedAgentRunId = "", this.copyFeedbackTimer = null, this.renderPanel();
441
- }, 1800), this.renderPanel();
440
+ this.copiedAgentRunId = "", this.copyFeedbackTimer = null, this.updateCopyFeedback();
441
+ }, 1800), this.updateCopyFeedback();
442
442
  }
443
443
  }
444
+ updateCopyFeedback() {
445
+ var e;
446
+ (e = this.panel) == null || e.querySelectorAll("[data-copy-run]").forEach((t) => {
447
+ var r;
448
+ const s = (r = t.dataset.copyRun) != null ? r : "";
449
+ t.textContent = this.copiedAgentRunId === s ? "已复制" : this.copiedAgentRunId === `error:${s}` ? "复制失败" : "复制流水号";
450
+ });
451
+ }
444
452
  clearCopyFeedback(e = !0) {
445
453
  this.copyFeedbackTimer && clearTimeout(this.copyFeedbackTimer), this.copyFeedbackTimer = null, e && (this.copiedAgentRunId = "");
446
454
  }
@@ -461,8 +469,9 @@ class V {
461
469
  this.sourceRefreshTimer && clearTimeout(this.sourceRefreshTimer), this.sourceRefreshTimer = null;
462
470
  }
463
471
  renderPanel(e = this.asking, t = !1) {
472
+ var g;
464
473
  if (!this.panel) return;
465
- const s = this.questionUnavailableReason(), r = s || (this.asking ? "回答生成中,请稍候" : "请输入页面分析问题,Enter 发送,Shift + Enter 换行"), n = !!(s || this.asking), l = s ? '<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>', p = T.map((o) => `
474
+ 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>', m = C.map((o) => `
466
475
  <button type="button" data-audience="${o.value}" aria-pressed="${o.value === this.answerAudience}" ${this.asking ? "disabled" : ""}>${o.label}</button>
467
476
  `).join("");
468
477
  if (this.panel.innerHTML = `
@@ -470,30 +479,33 @@ class V {
470
479
  <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
471
480
  <button class="po-new" data-action="new" ${this.asking ? "disabled" : ""}>+ 新建问答</button>
472
481
  <input class="po-search" placeholder="搜索问答" />
473
- ${this.conversationError ? `<p class="po-conversation-error" role="alert">${c(this.conversationError)}</p>` : ""}
482
+ ${this.conversationError ? `<p class="po-conversation-error" role="alert">${l(this.conversationError)}</p>` : ""}
474
483
  <div class="po-thread-list">${this.conversations.map((o) => {
475
- var g;
484
+ var y;
476
485
  return `
477
- <div class="po-thread-row ${o.id === ((g = this.currentThread) == null ? void 0 : g.id) ? "active" : ""}">
478
- <button class="po-thread" data-thread="${c(o.id)}" ${this.asking ? "disabled" : ""}>
479
- <strong>${c(o.title)}</strong><span>${D(o.created_at)}</span>
486
+ <div class="po-thread-row ${o.id === ((y = this.currentThread) == null ? void 0 : y.id) ? "active" : ""}">
487
+ <button class="po-thread" data-thread="${l(o.id)}" ${this.asking ? "disabled" : ""}>
488
+ <strong>${l(o.title)}</strong><span>${M(o.created_at)}</span>
480
489
  </button>
481
- <button class="po-thread-delete" type="button" data-delete-thread="${c(o.id)}" aria-label="删除会话:${c(o.title)}" title="删除会话" ${this.asking || this.deletingThreadId === o.id ? "disabled" : ""}><span class="po-trash-icon" aria-hidden="true"></span></button>
490
+ <button class="po-thread-delete" type="button" data-delete-thread="${l(o.id)}" aria-label="删除会话:${l(o.title)}" title="删除会话" ${this.asking || this.deletingThreadId === o.id ? "disabled" : ""}><span class="po-trash-icon" aria-hidden="true"></span></button>
482
491
  </div>`;
483
492
  }).join("")}</div>
484
493
  </aside>
485
494
  <main class="po-chat">
486
- <header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread ? c(this.currentThread.title) : "未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${p}</div></div></header>
495
+ <header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread ? l(this.currentThread.title) : "未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${m}</div></div></header>
487
496
  <section class="po-messages">
488
497
  ${this.messages.map((o) => this.renderMessage(o)).join("")}
489
498
  ${this.renderAnswerState()}
490
499
  </section>
491
- <form class="po-composer"><textarea ${n ? "disabled" : ""} placeholder="${c(r)}"></textarea>${l}</form>
500
+ <form class="po-composer"><textarea ${c ? "disabled" : ""} placeholder="${l(n)}"></textarea>${p}</form>
492
501
  </main>
493
502
  <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
494
503
  `, this.bindPanelEvents(), e) {
495
504
  const o = this.panel.querySelector(".po-messages");
496
505
  o && (o.scrollTop = o.scrollHeight);
506
+ } else if (s !== void 0) {
507
+ const o = this.panel.querySelector(".po-messages");
508
+ o && (o.scrollTop = s);
497
509
  }
498
510
  if (t) {
499
511
  const o = this.panel.querySelector(".po-trace > section");
@@ -501,19 +513,19 @@ class V {
501
513
  }
502
514
  }
503
515
  renderAnswerState() {
504
- 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>${R(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>${c(this.answerError)}</div></article>` : "", r = this.answerStopped ? '<div class="po-stream-stopped" role="status">已停止输出</div>' : "";
516
+ 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>${T(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>` : "", r = this.answerStopped ? '<div class="po-stream-stopped" role="status">已停止输出</div>' : "";
505
517
  return `${e}${t}${r}${s}`;
506
518
  }
507
519
  renderMessage(e) {
508
- const t = O(e), s = t && t === this.selectedAgentRunId, r = this.copiedAgentRunId === t, n = this.copiedAgentRunId === `error:${t}`, l = e.role === "assistant" && t ? `<footer class="po-answer-meta ${s ? "selected" : ""}">
509
- <span class="po-run-id" title="${c(t)}">问答流水号 <code>${c(t)}</code></span>
510
- <button type="button" data-copy-run="${c(t)}">${r ? "已复制" : n ? "复制失败" : "复制流水号"}</button>
511
- <button type="button" data-view-run="${c(t)}" aria-pressed="${s}">${s ? "正在查看" : "查看执行过程"}</button>
520
+ const t = O(e), s = t && t === this.selectedAgentRunId, r = this.copiedAgentRunId === t, n = this.copiedAgentRunId === `error:${t}`, c = e.role === "assistant" && t ? `<footer class="po-answer-meta ${s ? "selected" : ""}">
521
+ <span class="po-run-id" title="${l(t)}">问答流水号 <code>${l(t)}</code></span>
522
+ <button type="button" data-copy-run="${l(t)}">${r ? "已复制" : n ? "复制失败" : "复制流水号"}</button>
523
+ <button type="button" data-view-run="${l(t)}" aria-pressed="${s}">${s ? "正在查看" : "查看执行过程"}</button>
512
524
  </footer>` : "";
513
- return `<article class="po-message ${e.role} ${s ? "run-selected" : ""}" data-message="${c(e.id)}">
525
+ return `<article class="po-message ${e.role} ${s ? "run-selected" : ""}" data-message="${l(e.id)}">
514
526
  <b>${e.role === "user" ? "你" : "PageOps 分析"}</b>
515
- <div>${e.role === "assistant" ? R(e.content) : c(e.content)}</div>
516
- ${l}
527
+ <div>${e.role === "assistant" ? T(e.content) : l(e.content)}</div>
528
+ ${c}
517
529
  </article>`;
518
530
  }
519
531
  renderSourceUploader() {
@@ -532,26 +544,26 @@ class V {
532
544
  <span>${this.sourceUploading ? "上传中..." : "选择代码包"}</span>
533
545
  <input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading ? "disabled" : ""} />
534
546
  </label>
535
- ${this.sourceUploadStatus ? `<p class="po-upload-status">${c(this.sourceUploadStatus)}</p>` : ""}
547
+ ${this.sourceUploadStatus ? `<p class="po-upload-status">${l(this.sourceUploadStatus)}</p>` : ""}
536
548
  ${this.sourceSnapshots.length ? `<div class="po-source-list">${this.sourceSnapshots.map((t) => this.renderSourceItem(t)).join("")}</div>` : `<p class="po-upload-empty">${e}</p>`}
537
- ${this.sourceLoadError ? `<p class="po-upload-error">${c(this.sourceLoadError)}</p>` : ""}
538
- ${this.sourceUploadError ? `<p class="po-upload-error">${c(this.sourceUploadError)}</p>` : ""}
549
+ ${this.sourceLoadError ? `<p class="po-upload-error">${l(this.sourceLoadError)}</p>` : ""}
550
+ ${this.sourceUploadError ? `<p class="po-upload-error">${l(this.sourceUploadError)}</p>` : ""}
539
551
  </div>
540
552
  `;
541
553
  }
542
554
  renderSourceItem(e) {
543
- var y, w, b, $, S, E, A;
544
- const t = e.filename || "未命名代码包", s = e.created_at ? D(e.created_at) : "刚刚上传", r = G(e.archive_bytes || e.total_bytes || 0), n = String((w = (y = e.metadata) == null ? void 0 : y.analysis_status) != null ? w : "unknown"), l = typeof ((b = e.metadata) == null ? void 0 : b.tag) == "string" ? e.metadata.tag : "", p = typeof (($ = e.metadata) == null ? void 0 : $.branch) == "string" ? e.metadata.branch : "", o = l ? `Tag: ${l}` : p ? `Branch: ${p}` : "未记录代码引用", g = typeof ((S = e.metadata) == null ? void 0 : S.remark) == "string" && e.metadata.remark ? e.metadata.remark : "无备注", f = typeof ((E = e.metadata) == null ? void 0 : E.uploader) == "string" ? e.metadata.uploader : "未知用户", P = (A = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[n]) != null ? A : "项目记忆状态未知";
545
- return `<article class="po-source-item"><strong>${c(t)}</strong><span>${c(o)}</span><span>备注:${c(g)}</span><span>上传人:${c(f)} · ${c(s)} · ${c(r)}</span><span>${c(P)}</span></article>`;
555
+ var w, b, $, S, E, A, R;
556
+ const t = e.filename || "未命名代码包", s = e.created_at ? M(e.created_at) : "刚刚上传", r = G(e.archive_bytes || e.total_bytes || 0), n = String((b = (w = e.metadata) == null ? void 0 : w.analysis_status) != null ? b : "unknown"), c = typeof (($ = e.metadata) == null ? void 0 : $.tag) == "string" ? e.metadata.tag : "", p = typeof ((S = e.metadata) == null ? void 0 : S.branch) == "string" ? e.metadata.branch : "", m = c ? `Tag: ${c}` : p ? `Branch: ${p}` : "未记录代码引用", g = typeof ((E = e.metadata) == null ? void 0 : E.remark) == "string" && e.metadata.remark ? e.metadata.remark : "无备注", o = typeof ((A = e.metadata) == null ? void 0 : A.uploader) == "string" ? e.metadata.uploader : "未知用户", y = (R = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[n]) != null ? R : "项目记忆状态未知";
557
+ return `<article class="po-source-item"><strong>${l(t)}</strong><span>${l(m)}</span><span>备注:${l(g)}</span><span>上传人:${l(o)} · ${l(s)} · ${l(r)}</span><span>${l(y)}</span></article>`;
546
558
  }
547
559
  renderSteps() {
548
- 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">${c(this.runLoadError)}</div>` : (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", summary: "发送问题后,这里会展示完整分析过程。" }]).map((t) => {
549
- var l, p, o;
550
- const s = (l = t.metrics) != null && l.length ? `<div class="po-step-metrics">${t.metrics.map((g) => `<span>${c(g)}</span>`).join("")}</div>` : "", r = (p = t.details) != null && p.length ? `<div class="po-step-details">${t.details.map((g) => `<div><span>${c(g.label)}</span><p>${c(g.value)}</p></div>`).join("")}</div>` : "", n = !!(s || r);
560
+ 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) => {
561
+ var c, p, m;
562
+ const s = (c = t.metrics) != null && c.length ? `<div class="po-step-metrics">${t.metrics.map((g) => `<span>${l(g)}</span>`).join("")}</div>` : "", r = (p = t.details) != null && p.length ? `<div class="po-step-details">${t.details.map((g) => `<div><span>${l(g.label)}</span><p>${l(g.value)}</p></div>`).join("")}</div>` : "", n = !!(s || r);
551
563
  return `<details class="po-step ${t.status}" ${t.status === "running" || t.status === "failed" ? "open" : ""} ${n ? "" : "data-static"}>
552
564
  <summary>
553
565
  <span class="po-step-dot" aria-hidden="true"></span>
554
- <span class="po-step-copy"><strong>${c(t.title)}</strong><small>${c((o = t.summary) != null ? o : "")}</small></span>
566
+ <span class="po-step-copy"><strong>${l(t.title)}</strong><small>${l((m = t.summary) != null ? m : "")}</small></span>
555
567
  <span class="po-step-status">${Z(t.status)}</span>
556
568
  </summary>
557
569
  ${s}${r}
@@ -559,62 +571,62 @@ class V {
559
571
  }).join("");
560
572
  }
561
573
  bindPanelEvents() {
562
- var e, t, s, r, n, l, p, o, g, f, P, y, w, b, $, S, E, A;
563
- (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()), (l = (n = this.panel) == null ? void 0 : n.querySelector('[data-action="stop-answer"]')) == null || l.addEventListener("click", () => this.cancelActiveAnswer(!0)), (p = this.panel) == null || p.querySelectorAll("[data-audience]").forEach((d) => {
564
- d.addEventListener("click", () => {
565
- var h;
566
- return this.changeAnswerAudience((h = d.dataset.audience) != null ? h : "");
574
+ var e, t, s, r, n, c, p, m, g, o, y, w, b, $, S, E, A, R;
575
+ (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) => {
576
+ h.addEventListener("click", () => {
577
+ var d;
578
+ return this.changeAnswerAudience((d = h.dataset.audience) != null ? d : "");
567
579
  });
568
- }), (g = (o = this.panel) == null ? void 0 : o.querySelector('[data-action="upload-source"]')) == null || g.addEventListener("change", (d) => {
569
- var C, k, I, x, q, L, U, F, _;
570
- const h = (C = d.target.files) == null ? void 0 : C[0];
571
- if (!h) return;
572
- const u = (I = (k = this.panel) == null ? void 0 : k.querySelector('[name="source-reference"]:checked')) == null ? void 0 : I.value, m = (L = (q = (x = this.panel) == null ? void 0 : x.querySelector(".po-source-reference-value")) == null ? void 0 : q.value.trim()) != null ? L : "", B = (_ = (F = (U = this.panel) == null ? void 0 : U.querySelector(".po-source-remark")) == null ? void 0 : F.value.trim()) != null ? _ : "";
573
- if (!m || u !== "tag" && u !== "branch") {
580
+ }), (g = (m = this.panel) == null ? void 0 : m.querySelector('[data-action="upload-source"]')) == null || g.addEventListener("change", (h) => {
581
+ var k, P, I, x, q, L, F, U, _;
582
+ const d = (k = h.target.files) == null ? void 0 : k[0];
583
+ if (!d) return;
584
+ const u = (I = (P = this.panel) == null ? void 0 : P.querySelector('[name="source-reference"]:checked')) == null ? void 0 : I.value, f = (L = (q = (x = this.panel) == null ? void 0 : x.querySelector(".po-source-reference-value")) == null ? void 0 : q.value.trim()) != null ? L : "", B = (_ = (U = (F = this.panel) == null ? void 0 : F.querySelector(".po-source-remark")) == null ? void 0 : U.value.trim()) != null ? _ : "";
585
+ if (!f || u !== "tag" && u !== "branch") {
574
586
  this.sourceUploadError = "请选择 Tag 或 Branch,并填写对应名称。", this.renderPanel();
575
587
  return;
576
588
  }
577
- this.uploadSource(h, { [u]: m, remark: B });
578
- }), (f = this.panel) == null || f.querySelectorAll('[name="source-reference"]').forEach((d) => {
579
- d.addEventListener("change", () => {
589
+ this.uploadSource(d, { [u]: f, remark: B });
590
+ }), (o = this.panel) == null || o.querySelectorAll('[name="source-reference"]').forEach((h) => {
591
+ h.addEventListener("change", () => {
580
592
  var u;
581
- const h = (u = this.panel) == null ? void 0 : u.querySelector(".po-source-reference-value");
582
- h && (h.placeholder = `请输入 ${d.value === "tag" ? "Tag" : "Branch"} 名称`);
593
+ const d = (u = this.panel) == null ? void 0 : u.querySelector(".po-source-reference-value");
594
+ d && (d.placeholder = `请输入 ${h.value === "tag" ? "Tag" : "Branch"} 名称`);
583
595
  });
584
- }), (P = this.panel) == null || P.querySelectorAll("[data-thread]").forEach((d) => {
585
- d.addEventListener("click", () => {
586
- const h = this.conversations.find((u) => u.id === d.dataset.thread);
587
- h && this.selectThread(h);
596
+ }), (y = this.panel) == null || y.querySelectorAll("[data-thread]").forEach((h) => {
597
+ h.addEventListener("click", () => {
598
+ const d = this.conversations.find((u) => u.id === h.dataset.thread);
599
+ d && this.selectThread(d);
588
600
  });
589
- }), (y = this.panel) == null || y.querySelectorAll("[data-delete-thread]").forEach((d) => {
590
- d.addEventListener("click", (h) => {
591
- h.stopPropagation();
592
- const u = this.conversations.find((m) => m.id === d.dataset.deleteThread);
601
+ }), (w = this.panel) == null || w.querySelectorAll("[data-delete-thread]").forEach((h) => {
602
+ h.addEventListener("click", (d) => {
603
+ d.stopPropagation();
604
+ const u = this.conversations.find((f) => f.id === h.dataset.deleteThread);
593
605
  u && this.deleteConversation(u);
594
606
  });
595
- }), (w = this.panel) == null || w.querySelectorAll("[data-view-run]").forEach((d) => {
596
- d.addEventListener("click", (h) => {
607
+ }), (b = this.panel) == null || b.querySelectorAll("[data-view-run]").forEach((h) => {
608
+ h.addEventListener("click", (d) => {
597
609
  var u;
598
- h.stopPropagation(), this.loadAgentRun((u = d.dataset.viewRun) != null ? u : "");
610
+ d.stopPropagation(), this.loadAgentRun((u = h.dataset.viewRun) != null ? u : "");
599
611
  });
600
- }), (b = this.panel) == null || b.querySelectorAll("[data-copy-run]").forEach((d) => {
601
- d.addEventListener("click", (h) => {
612
+ }), ($ = this.panel) == null || $.querySelectorAll("[data-copy-run]").forEach((h) => {
613
+ h.addEventListener("click", (d) => {
602
614
  var u;
603
- h.stopPropagation(), this.copyAgentRunId((u = d.dataset.copyRun) != null ? u : "");
615
+ d.stopPropagation(), this.copyAgentRunId((u = h.dataset.copyRun) != null ? u : "");
604
616
  });
605
- }), (S = ($ = this.panel) == null ? void 0 : $.querySelector("form")) == null || S.addEventListener("submit", (d) => {
606
- var m;
607
- d.preventDefault();
608
- const h = (m = this.panel) == null ? void 0 : m.querySelector("textarea"), u = h == null ? void 0 : h.value.trim();
609
- u && (h.value = "", this.ask(u));
610
- }), (A = (E = this.panel) == null ? void 0 : E.querySelector("textarea")) == null || A.addEventListener("keydown", (d) => {
611
- var u, m;
612
- const h = d;
613
- h.key === "Enter" && !h.shiftKey && (h.preventDefault(), (m = (u = this.panel) == null ? void 0 : u.querySelector("form")) == null || m.requestSubmit());
617
+ }), (E = (S = this.panel) == null ? void 0 : S.querySelector("form")) == null || E.addEventListener("submit", (h) => {
618
+ var f;
619
+ h.preventDefault();
620
+ const d = (f = this.panel) == null ? void 0 : f.querySelector("textarea"), u = d == null ? void 0 : d.value.trim();
621
+ u && (d.value = "", this.ask(u));
622
+ }), (R = (A = this.panel) == null ? void 0 : A.querySelector("textarea")) == null || R.addEventListener("keydown", (h) => {
623
+ var u, f;
624
+ const d = h;
625
+ d.key === "Enter" && !d.shiftKey && (d.preventDefault(), (f = (u = this.panel) == null ? void 0 : u.querySelector("form")) == null || f.requestSubmit());
614
626
  });
615
627
  }
616
628
  }
617
- function c(a) {
629
+ function l(a) {
618
630
  return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
619
631
  }
620
632
  function O(a) {
@@ -622,7 +634,7 @@ function O(a) {
622
634
  const e = (t = a.metadata_json) == null ? void 0 : t.agent_run_id;
623
635
  return typeof e == "string" ? e : "";
624
636
  }
625
- function D(a) {
637
+ function M(a) {
626
638
  return new Intl.DateTimeFormat("zh-CN", {
627
639
  timeZone: "Asia/Shanghai",
628
640
  month: "2-digit",
@@ -1,38 +1,38 @@
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 X=Object.defineProperty;var Y=(f,m,w)=>m in f?X(f,m,{enumerable:!0,configurable:!0,writable:!0,value:w}):f[m]=w;var i=(f,m,w)=>Y(f,typeof m!="symbol"?m+"":m,w);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,l,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:(l=e.title)!=null?l: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 l,p;const s=(t==null?void 0:t.body)instanceof FormData?t.headers:{"content-type":"application/json",...(l=t==null?void 0:t.headers)!=null?l:{}},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:`${e}/api`}}async function w(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 x(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function b(o){return x(o).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function z(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 r=[];let n=e;for(;n<o.length&&o[n].includes("|")&&o[n].trim();)r.push(o[n]),n+=1;const l=g=>g.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(y=>b(y.trim())),p=l(r[0]).map(g=>`<th>${g}</th>`).join(""),a=r.slice(2).map(g=>`<tr>${l(g).map(y=>`<td>${y}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${p}</tr></thead><tbody>${a}</tbody></table>`,next:n}}function k(o){const e=o.split(`
2
- `),t=[];for(let s=0;s<e.length;s+=1){const r=e[s];if(r.trim().startsWith("```")){const l=[];for(s+=1;s<e.length&&!e[s].trim().startsWith("```");)l.push(e[s]),s+=1;t.push(`<pre><code>${x(l.join(`
3
- `))}</code></pre>`);continue}const n=z(e,s);if(n){t.push(n.html),s=n.next-1;continue}r.startsWith("### ")?t.push(`<h4>${b(r.slice(4))}</h4>`):r.startsWith("## ")?t.push(`<h3>${b(r.slice(3))}</h3>`):r.startsWith("# ")?t.push(`<h2>${b(r.slice(2))}</h2>`):r.startsWith("- ")?t.push(`<li>${b(r.slice(2))}</li>`):r.trim()?t.push(`<p>${b(r)}</p>`):t.push("<br>")}return t.join("")}async function H(o,e){var n;const t=o.getReader(),s=new TextDecoder;let r="";for(;;){const{done:l,value:p}=await t.read();if(l){r+=s.decode();break}r+=s.decode(p,{stream:!0});const a=r.split(/\r?\n\r?\n/);r=(n=a.pop())!=null?n:"";for(const g of a)q(g,e)}r.trim()&&q(r,e)}function q(o,e){var r,n;const t=(r=o.match(/^event:\s*(.+)$/m))==null?void 0:r[1],s=(n=o.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 l=await this.client.streamQuestion(this.currentThread.id,e,this.answerAudience,r.signal);if(!l.ok)throw new Error(await w(l,"服务暂时无法回答,请稍后重试。"));if(!l.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await H(l.body,(p,a)=>this.handleStreamEvent(p,a)),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.renderPanel(!1,!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.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,t=!1){if(!this.panel)return;const s=this.questionUnavailableReason(),r=s||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),n=!!(s||this.asking),l=s?'<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>',p=I.map(a=>`
4
- <button type="button" data-audience="${a.value}" aria-pressed="${a.value===this.answerAudience}" ${this.asking?"disabled":""}>${a.label}</button>
1
+ (function(y,f){typeof exports=="object"&&typeof module!="undefined"?f(exports):typeof define=="function"&&define.amd?define(["exports"],f):(y=typeof globalThis!="undefined"?globalThis:y||self,f(y.PageOpsSDK={}))})(this,(function(y){"use strict";var X=Object.defineProperty;var Y=(y,f,b)=>f in y?X(y,f,{enumerable:!0,configurable:!0,writable:!0,value:b}):y[f]=b;var i=(y,f,b)=>Y(y,typeof f!="symbol"?f+"":f,b);class f{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:`${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 z(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(""),m=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>${m}</tbody></table>`,next:n}}function k(a){const e=a.split(`
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
+ `))}</code></pre>`);continue}const n=z(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 H(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 m=r.split(/\r?\n\r?\n/);r=(n=m.pop())!=null?n:"";for(const g of m)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 f(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 f(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 H(c.body,(p,m)=>this.handleStreamEvent(p,m)),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.renderPanel(!1,!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>',m=I.map(o=>`
4
+ <button type="button" data-audience="${o.value}" aria-pressed="${o.value===this.answerAudience}" ${this.asking?"disabled":""}>${o.label}</button>
5
5
  `).join("");if(this.panel.innerHTML=`
6
6
  <aside class="po-sidebar">
7
7
  <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
8
8
  <button class="po-new" data-action="new" ${this.asking?"disabled":""}>+ 新建问答</button>
9
9
  <input class="po-search" placeholder="搜索问答" />
10
- ${this.conversationError?`<p class="po-conversation-error" role="alert">${c(this.conversationError)}</p>`:""}
11
- <div class="po-thread-list">${this.conversations.map(a=>{var g;return`
12
- <div class="po-thread-row ${a.id===((g=this.currentThread)==null?void 0:g.id)?"active":""}">
13
- <button class="po-thread" data-thread="${c(a.id)}" ${this.asking?"disabled":""}>
14
- <strong>${c(a.title)}</strong><span>${U(a.created_at)}</span>
10
+ ${this.conversationError?`<p class="po-conversation-error" role="alert">${l(this.conversationError)}</p>`:""}
11
+ <div class="po-thread-list">${this.conversations.map(o=>{var w;return`
12
+ <div class="po-thread-row ${o.id===((w=this.currentThread)==null?void 0:w.id)?"active":""}">
13
+ <button class="po-thread" data-thread="${l(o.id)}" ${this.asking?"disabled":""}>
14
+ <strong>${l(o.title)}</strong><span>${F(o.created_at)}</span>
15
15
  </button>
16
- <button class="po-thread-delete" type="button" data-delete-thread="${c(a.id)}" aria-label="删除会话:${c(a.title)}" title="删除会话" ${this.asking||this.deletingThreadId===a.id?"disabled":""}><span class="po-trash-icon" aria-hidden="true"></span></button>
16
+ <button class="po-thread-delete" type="button" data-delete-thread="${l(o.id)}" aria-label="删除会话:${l(o.title)}" title="删除会话" ${this.asking||this.deletingThreadId===o.id?"disabled":""}><span class="po-trash-icon" aria-hidden="true"></span></button>
17
17
  </div>`}).join("")}</div>
18
18
  </aside>
19
19
  <main class="po-chat">
20
- <header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread?c(this.currentThread.title):"未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${p}</div></div></header>
20
+ <header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread?l(this.currentThread.title):"未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${m}</div></div></header>
21
21
  <section class="po-messages">
22
- ${this.messages.map(a=>this.renderMessage(a)).join("")}
22
+ ${this.messages.map(o=>this.renderMessage(o)).join("")}
23
23
  ${this.renderAnswerState()}
24
24
  </section>
25
- <form class="po-composer"><textarea ${n?"disabled":""} placeholder="${c(r)}"></textarea>${l}</form>
25
+ <form class="po-composer"><textarea ${c?"disabled":""} placeholder="${l(n)}"></textarea>${p}</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)}if(t){const a=this.panel.querySelector(".po-trace > section");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>${k(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>${c(this.answerError)}</div></article>`:"",r=this.answerStopped?'<div class="po-stream-stopped" role="status">已停止输出</div>':"";return`${e}${t}${r}${s}`}renderMessage(e){const t=L(e),s=t&&t===this.selectedAgentRunId,r=this.copiedAgentRunId===t,n=this.copiedAgentRunId===`error:${t}`,l=e.role==="assistant"&&t?`<footer class="po-answer-meta ${s?"selected":""}">
29
- <span class="po-run-id" title="${c(t)}">问答流水号 <code>${c(t)}</code></span>
30
- <button type="button" data-copy-run="${c(t)}">${r?"已复制":n?"复制失败":"复制流水号"}</button>
31
- <button type="button" data-view-run="${c(t)}" aria-pressed="${s}">${s?"正在查看":"查看执行过程"}</button>
32
- </footer>`:"";return`<article class="po-message ${e.role} ${s?"run-selected":""}" data-message="${c(e.id)}">
28
+ `,this.bindPanelEvents(),e){const o=this.panel.querySelector(".po-messages");o&&(o.scrollTop=o.scrollHeight)}else if(s!==void 0){const o=this.panel.querySelector(".po-messages");o&&(o.scrollTop=s)}if(t){const o=this.panel.querySelector(".po-trace > section");o&&(o.scrollTop=o.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>${k(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>`:"",r=this.answerStopped?'<div class="po-stream-stopped" role="status">已停止输出</div>':"";return`${e}${t}${r}${s}`}renderMessage(e){const t=L(e),s=t&&t===this.selectedAgentRunId,r=this.copiedAgentRunId===t,n=this.copiedAgentRunId===`error:${t}`,c=e.role==="assistant"&&t?`<footer class="po-answer-meta ${s?"selected":""}">
29
+ <span class="po-run-id" title="${l(t)}">问答流水号 <code>${l(t)}</code></span>
30
+ <button type="button" data-copy-run="${l(t)}">${r?"已复制":n?"复制失败":"复制流水号"}</button>
31
+ <button type="button" data-view-run="${l(t)}" aria-pressed="${s}">${s?"正在查看":"查看执行过程"}</button>
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>
34
- <div>${e.role==="assistant"?k(e.content):c(e.content)}</div>
35
- ${l}
34
+ <div>${e.role==="assistant"?k(e.content):l(e.content)}</div>
35
+ ${c}
36
36
  </article>`}renderSourceUploader(){const e=this.sourceLoadError?"暂时无法读取项目共享代码包,连接恢复后将自动重试。":"当前项目暂无代码包,请先上传后再提问。";return`
37
37
  <div class="po-source-uploader">
38
38
  <strong>源码包</strong>
@@ -47,16 +47,16 @@
47
47
  <span>${this.sourceUploading?"上传中...":"选择代码包"}</span>
48
48
  <input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
49
49
  </label>
50
- ${this.sourceUploadStatus?`<p class="po-upload-status">${c(this.sourceUploadStatus)}</p>`:""}
50
+ ${this.sourceUploadStatus?`<p class="po-upload-status">${l(this.sourceUploadStatus)}</p>`:""}
51
51
  ${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(t=>this.renderSourceItem(t)).join("")}</div>`:`<p class="po-upload-empty">${e}</p>`}
52
- ${this.sourceLoadError?`<p class="po-upload-error">${c(this.sourceLoadError)}</p>`:""}
53
- ${this.sourceUploadError?`<p class="po-upload-error">${c(this.sourceUploadError)}</p>`:""}
52
+ ${this.sourceLoadError?`<p class="po-upload-error">${l(this.sourceLoadError)}</p>`:""}
53
+ ${this.sourceUploadError?`<p class="po-upload-error">${l(this.sourceUploadError)}</p>`:""}
54
54
  </div>
55
- `}renderSourceItem(e){var $,S,E,A,P,T,R;const t=e.filename||"未命名代码包",s=e.created_at?U(e.created_at):"刚刚上传",r=Q(e.archive_bytes||e.total_bytes||0),n=String((S=($=e.metadata)==null?void 0:$.analysis_status)!=null?S:"unknown"),l=typeof((E=e.metadata)==null?void 0:E.tag)=="string"?e.metadata.tag:"",p=typeof((A=e.metadata)==null?void 0:A.branch)=="string"?e.metadata.branch:"",a=l?`Tag: ${l}`:p?`Branch: ${p}`:"未记录代码引用",g=typeof((P=e.metadata)==null?void 0:P.remark)=="string"&&e.metadata.remark?e.metadata.remark:"无备注",y=typeof((T=e.metadata)==null?void 0:T.uploader)=="string"?e.metadata.uploader:"未知用户",C=(R={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[n])!=null?R:"项目记忆状态未知";return`<article class="po-source-item"><strong>${c(t)}</strong><span>${c(a)}</span><span>备注:${c(g)}</span><span>上传人:${c(y)} · ${c(s)} · ${c(r)}</span><span>${c(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">${c(this.runLoadError)}</div>`:(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",summary:"发送问题后,这里会展示完整分析过程。"}]).map(t=>{var l,p,a;const s=(l=t.metrics)!=null&&l.length?`<div class="po-step-metrics">${t.metrics.map(g=>`<span>${c(g)}</span>`).join("")}</div>`:"",r=(p=t.details)!=null&&p.length?`<div class="po-step-details">${t.details.map(g=>`<div><span>${c(g.label)}</span><p>${c(g.value)}</p></div>`).join("")}</div>`:"",n=!!(s||r);return`<details class="po-step ${t.status}" ${t.status==="running"||t.status==="failed"?"open":""} ${n?"":"data-static"}>
55
+ `}renderSourceItem(e){var $,E,A,T,R,C,P;const t=e.filename||"未命名代码包",s=e.created_at?F(e.created_at):"刚刚上传",r=Q(e.archive_bytes||e.total_bytes||0),n=String((E=($=e.metadata)==null?void 0:$.analysis_status)!=null?E:"unknown"),c=typeof((A=e.metadata)==null?void 0:A.tag)=="string"?e.metadata.tag:"",p=typeof((T=e.metadata)==null?void 0:T.branch)=="string"?e.metadata.branch:"",m=c?`Tag: ${c}`:p?`Branch: ${p}`:"未记录代码引用",g=typeof((R=e.metadata)==null?void 0:R.remark)=="string"&&e.metadata.remark?e.metadata.remark:"无备注",o=typeof((C=e.metadata)==null?void 0:C.uploader)=="string"?e.metadata.uploader:"未知用户",w=(P={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[n])!=null?P:"项目记忆状态未知";return`<article class="po-source-item"><strong>${l(t)}</strong><span>${l(m)}</span><span>备注:${l(g)}</span><span>上传人:${l(o)} · ${l(s)} · ${l(r)}</span><span>${l(w)}</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,p,m;const s=(c=t.metrics)!=null&&c.length?`<div class="po-step-metrics">${t.metrics.map(g=>`<span>${l(g)}</span>`).join("")}</div>`:"",r=(p=t.details)!=null&&p.length?`<div class="po-step-details">${t.details.map(g=>`<div><span>${l(g.label)}</span><p>${l(g.value)}</p></div>`).join("")}</div>`:"",n=!!(s||r);return`<details class="po-step ${t.status}" ${t.status==="running"||t.status==="failed"?"open":""} ${n?"":"data-static"}>
56
56
  <summary>
57
57
  <span class="po-step-dot" aria-hidden="true"></span>
58
- <span class="po-step-copy"><strong>${c(t.title)}</strong><small>${c((a=t.summary)!=null?a:"")}</small></span>
58
+ <span class="po-step-copy"><strong>${l(t.title)}</strong><small>${l((m=t.summary)!=null?m:"")}</small></span>
59
59
  <span class="po-step-status">${V(t.status)}</span>
60
60
  </summary>
61
61
  ${s}${r}
62
- </details>`}).join("")}bindPanelEvents(){var e,t,s,r,n,l,p,a,g,y,C,$,S,E,A,P,T,R;(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()),(l=(n=this.panel)==null?void 0:n.querySelector('[data-action="stop-answer"]'))==null||l.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=(a=this.panel)==null?void 0:a.querySelector('[data-action="upload-source"]'))==null||g.addEventListener("change",h=>{var F,_,K,j,O,D,M,B,W;const d=(F=h.target.files)==null?void 0:F[0];if(!d)return;const u=(K=(_=this.panel)==null?void 0:_.querySelector('[name="source-reference"]:checked'))==null?void 0:K.value,v=(D=(O=(j=this.panel)==null?void 0:j.querySelector(".po-source-reference-value"))==null?void 0:O.value.trim())!=null?D:"",Z=(W=(B=(M=this.panel)==null?void 0:M.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})}),(y=this.panel)==null||y.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"} 名称`)})}),(C=this.panel)==null||C.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)})}),(S=this.panel)==null||S.querySelectorAll("[data-view-run]").forEach(h=>{h.addEventListener("click",d=>{var u;d.stopPropagation(),this.loadAgentRun((u=h.dataset.viewRun)!=null?u:"")})}),(E=this.panel)==null||E.querySelectorAll("[data-copy-run]").forEach(h=>{h.addEventListener("click",d=>{var u;d.stopPropagation(),this.copyAgentRunId((u=h.dataset.copyRun)!=null?u:"")})}),(P=(A=this.panel)==null?void 0:A.querySelector("form"))==null||P.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))}),(R=(T=this.panel)==null?void 0:T.querySelector("textarea"))==null||R.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 c(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function L(o){var t;const e=(t=o.metadata_json)==null?void 0:t.agent_run_id;return typeof e=="string"?e:""}function U(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 Q(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 V(o){return{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",cancelled:"已停止"}[o]}const G=new J;f.PageOpsSDK=G,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
62
+ </details>`}).join("")}bindPanelEvents(){var e,t,s,r,n,c,p,m,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=(m=this.panel)==null?void 0:m.querySelector('[data-action="upload-source"]'))==null||g.addEventListener("change",h=>{var U,_,K,j,O,D,M,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=(D=(O=(j=this.panel)==null?void 0:j.querySelector(".po-source-reference-value"))==null?void 0:O.value.trim())!=null?D:"",Z=(W=(B=(M=this.panel)==null?void 0:M.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"})}));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pageops/sdk",
3
- "version": "0.1.15",
3
+ "version": "0.1.16",
4
4
  "description": "PageOps embeddable frontend SDK",
5
5
  "type": "module",
6
6
  "main": "dist/pageops-sdk.umd.cjs",