@pageops/sdk 0.1.9 → 0.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/pageops-sdk.es.js +105 -105
- package/dist/pageops-sdk.umd.cjs +16 -16
- package/package.json +1 -1
package/dist/pageops-sdk.es.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
var x = Object.defineProperty;
|
|
2
|
-
var k = (
|
|
3
|
-
var
|
|
2
|
+
var k = (a, t, e) => t in a ? x(a, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : a[t] = e;
|
|
3
|
+
var o = (a, t, e) => k(a, typeof t != "symbol" ? t + "" : t, e);
|
|
4
4
|
class E {
|
|
5
5
|
constructor(t) {
|
|
6
6
|
this.options = t;
|
|
7
7
|
}
|
|
8
8
|
async createContext(t = ((i) => (i = ((e) => ((s) => (s = (e = this.options).getPageContext) == null ? void 0 : s.call(e))())()) != null ? i : {})()) {
|
|
9
|
-
var
|
|
9
|
+
var n, r, l;
|
|
10
10
|
return this.request("/context/session", {
|
|
11
11
|
method: "POST",
|
|
12
12
|
body: JSON.stringify({
|
|
13
13
|
app_id: this.options.appId,
|
|
14
14
|
env: this.options.env,
|
|
15
15
|
route: t.route,
|
|
16
|
-
url: (
|
|
17
|
-
title: (
|
|
16
|
+
url: (n = t.url) != null ? n : location.href,
|
|
17
|
+
title: (r = t.title) != null ? r : document.title,
|
|
18
18
|
menu_path: (l = t.menuPath) != null ? l : [],
|
|
19
19
|
tenant_id: t.tenantId,
|
|
20
20
|
user_role: t.userRole,
|
|
@@ -55,87 +55,87 @@ class E {
|
|
|
55
55
|
});
|
|
56
56
|
}
|
|
57
57
|
async request(t, e) {
|
|
58
|
-
var
|
|
59
|
-
const s = (e == null ? void 0 : e.body) instanceof FormData ? e.headers : { "content-type": "application/json", ...(
|
|
58
|
+
var r, l;
|
|
59
|
+
const s = (e == null ? void 0 : e.body) instanceof FormData ? e.headers : { "content-type": "application/json", ...(r = e == null ? void 0 : e.headers) != null ? r : {} }, i = await fetch(`${this.base()}${t}`, { ...e, headers: s });
|
|
60
60
|
if (i.status === 204) return;
|
|
61
|
-
const
|
|
62
|
-
if (!i.ok) throw new Error((l =
|
|
63
|
-
return
|
|
61
|
+
const n = await i.json();
|
|
62
|
+
if (!i.ok) throw new Error((l = n.message) != null ? l : "PageOps 请求失败");
|
|
63
|
+
return n;
|
|
64
64
|
}
|
|
65
65
|
base() {
|
|
66
66
|
const t = this.options.apiBase.replace(/\/$/, "");
|
|
67
67
|
return t.endsWith("/api") ? t : `${t}/api`;
|
|
68
68
|
}
|
|
69
69
|
}
|
|
70
|
-
async function I(
|
|
71
|
-
const e = await
|
|
70
|
+
async function I(a, t) {
|
|
71
|
+
const e = await a.json().catch(() => null);
|
|
72
72
|
return typeof (e == null ? void 0 : e.message) == "string" && e.message.trim() ? e.message : t;
|
|
73
73
|
}
|
|
74
|
-
function T(
|
|
75
|
-
return
|
|
74
|
+
function T(a) {
|
|
75
|
+
return a.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
76
76
|
}
|
|
77
|
-
function v(
|
|
78
|
-
return T(
|
|
77
|
+
function v(a) {
|
|
78
|
+
return T(a).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
|
79
79
|
}
|
|
80
|
-
function R(
|
|
81
|
-
const e =
|
|
80
|
+
function R(a, t) {
|
|
81
|
+
const e = a[t], s = a[t + 1];
|
|
82
82
|
if (!(e != null && e.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
|
|
83
83
|
const i = [];
|
|
84
|
-
let
|
|
85
|
-
for (;
|
|
86
|
-
i.push(n
|
|
87
|
-
const
|
|
88
|
-
return { html: `<table><thead><tr>${l}</tr></thead><tbody>${p}</tbody></table>`, next:
|
|
84
|
+
let n = t;
|
|
85
|
+
for (; n < a.length && a[n].includes("|") && a[n].trim(); )
|
|
86
|
+
i.push(a[n]), n += 1;
|
|
87
|
+
const r = (d) => d.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((f) => v(f.trim())), l = r(i[0]).map((d) => `<th>${d}</th>`).join(""), p = i.slice(2).map((d) => `<tr>${r(d).map((f) => `<td>${f}</td>`).join("")}</tr>`).join("");
|
|
88
|
+
return { html: `<table><thead><tr>${l}</tr></thead><tbody>${p}</tbody></table>`, next: n };
|
|
89
89
|
}
|
|
90
|
-
function w(
|
|
91
|
-
const t =
|
|
90
|
+
function w(a) {
|
|
91
|
+
const t = a.split(`
|
|
92
92
|
`), e = [];
|
|
93
93
|
for (let s = 0; s < t.length; s += 1) {
|
|
94
94
|
const i = t[s];
|
|
95
95
|
if (i.trim().startsWith("```")) {
|
|
96
|
-
const
|
|
96
|
+
const r = [];
|
|
97
97
|
for (s += 1; s < t.length && !t[s].trim().startsWith("```"); )
|
|
98
|
-
|
|
99
|
-
e.push(`<pre><code>${T(
|
|
98
|
+
r.push(t[s]), s += 1;
|
|
99
|
+
e.push(`<pre><code>${T(r.join(`
|
|
100
100
|
`))}</code></pre>`);
|
|
101
101
|
continue;
|
|
102
102
|
}
|
|
103
|
-
const
|
|
104
|
-
if (
|
|
105
|
-
e.push(
|
|
103
|
+
const n = R(t, s);
|
|
104
|
+
if (n) {
|
|
105
|
+
e.push(n.html), s = n.next - 1;
|
|
106
106
|
continue;
|
|
107
107
|
}
|
|
108
108
|
i.startsWith("### ") ? e.push(`<h4>${v(i.slice(4))}</h4>`) : i.startsWith("## ") ? e.push(`<h3>${v(i.slice(3))}</h3>`) : i.startsWith("# ") ? e.push(`<h2>${v(i.slice(2))}</h2>`) : i.startsWith("- ") ? e.push(`<li>${v(i.slice(2))}</li>`) : i.trim() ? e.push(`<p>${v(i)}</p>`) : e.push("<br>");
|
|
109
109
|
}
|
|
110
110
|
return e.join("");
|
|
111
111
|
}
|
|
112
|
-
async function U(
|
|
113
|
-
var
|
|
114
|
-
const e =
|
|
112
|
+
async function U(a, t) {
|
|
113
|
+
var n;
|
|
114
|
+
const e = a.getReader(), s = new TextDecoder();
|
|
115
115
|
let i = "";
|
|
116
116
|
for (; ; ) {
|
|
117
|
-
const { done:
|
|
118
|
-
if (
|
|
117
|
+
const { done: r, value: l } = await e.read();
|
|
118
|
+
if (r) {
|
|
119
119
|
i += s.decode();
|
|
120
120
|
break;
|
|
121
121
|
}
|
|
122
122
|
i += s.decode(l, { stream: !0 });
|
|
123
123
|
const p = i.split(/\r?\n\r?\n/);
|
|
124
|
-
i = (
|
|
124
|
+
i = (n = p.pop()) != null ? n : "";
|
|
125
125
|
for (const d of p) C(d, t);
|
|
126
126
|
}
|
|
127
127
|
i.trim() && C(i, t);
|
|
128
128
|
}
|
|
129
|
-
function C(
|
|
130
|
-
var i,
|
|
131
|
-
const e = (i =
|
|
129
|
+
function C(a, t) {
|
|
130
|
+
var i, n;
|
|
131
|
+
const e = (i = a.match(/^event:\s*(.+)$/m)) == null ? void 0 : i[1], s = (n = a.match(/^data:\s*(.+)$/m)) == null ? void 0 : n[1];
|
|
132
132
|
e && s && t(e, JSON.parse(s));
|
|
133
133
|
}
|
|
134
134
|
class q {
|
|
135
135
|
constructor(t, e = 16) {
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
136
|
+
o(this, "queue", []);
|
|
137
|
+
o(this, "timer", null);
|
|
138
|
+
o(this, "drainWaiters", []);
|
|
139
139
|
this.onChunk = t, this.interval = e;
|
|
140
140
|
}
|
|
141
141
|
enqueue(t) {
|
|
@@ -161,35 +161,35 @@ class q {
|
|
|
161
161
|
}
|
|
162
162
|
class F {
|
|
163
163
|
constructor() {
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
164
|
+
o(this, "client", null);
|
|
165
|
+
o(this, "options", null);
|
|
166
|
+
o(this, "root", null);
|
|
167
|
+
o(this, "panel", null);
|
|
168
|
+
o(this, "context", null);
|
|
169
|
+
o(this, "contextKey", "");
|
|
170
|
+
o(this, "selectedPageKey", "");
|
|
171
|
+
o(this, "currentThread", null);
|
|
172
|
+
o(this, "conversations", []);
|
|
173
|
+
o(this, "messages", []);
|
|
174
|
+
o(this, "steps", []);
|
|
175
|
+
o(this, "sourceSnapshots", []);
|
|
176
|
+
o(this, "sourceUploadStatus", "");
|
|
177
|
+
o(this, "sourceUploadError", "");
|
|
178
|
+
o(this, "sourceUploading", !1);
|
|
179
|
+
o(this, "sourceRefreshTimer", null);
|
|
180
|
+
o(this, "streaming", "");
|
|
181
|
+
o(this, "asking", !1);
|
|
182
|
+
o(this, "waitingForFirstContent", !1);
|
|
183
|
+
o(this, "abortController", null);
|
|
184
|
+
o(this, "activeRunId", 0);
|
|
185
|
+
o(this, "stoppedRunId", -1);
|
|
186
|
+
o(this, "answerStopped", !1);
|
|
187
|
+
o(this, "answerError", "");
|
|
188
|
+
o(this, "conversationError", "");
|
|
189
|
+
o(this, "deletingThreadId", "");
|
|
190
|
+
o(this, "streamFailure", "");
|
|
191
|
+
o(this, "streamDone", null);
|
|
192
|
+
o(this, "typewriter", new q((t) => {
|
|
193
193
|
this.streaming += t, this.updateStreamingMessage();
|
|
194
194
|
}));
|
|
195
195
|
}
|
|
@@ -224,12 +224,12 @@ class F {
|
|
|
224
224
|
return (s = (e = (t = this.options) == null ? void 0 : t.getPageContext) == null ? void 0 : e.call(t)) != null ? s : {};
|
|
225
225
|
}
|
|
226
226
|
getPageContextKey(t) {
|
|
227
|
-
var e, s, i,
|
|
227
|
+
var e, s, i, n;
|
|
228
228
|
return JSON.stringify([
|
|
229
229
|
(e = t.route) != null ? e : "",
|
|
230
230
|
(s = t.url) != null ? s : location.href,
|
|
231
231
|
(i = t.title) != null ? i : document.title,
|
|
232
|
-
(
|
|
232
|
+
(n = t.menuPath) != null ? n : []
|
|
233
233
|
]);
|
|
234
234
|
}
|
|
235
235
|
async loadSources() {
|
|
@@ -294,23 +294,23 @@ class F {
|
|
|
294
294
|
const s = ++this.activeRunId, i = new AbortController();
|
|
295
295
|
this.abortController = i, this.stoppedRunId = -1, this.asking = !0, this.waitingForFirstContent = !0, this.renderPanel();
|
|
296
296
|
try {
|
|
297
|
-
const
|
|
298
|
-
if (this.currentThread && this.selectedPageKey && this.selectedPageKey !==
|
|
297
|
+
const n = this.getPageContextKey(this.getPageContext());
|
|
298
|
+
if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== n && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) throw new Error("无法创建问答会话,请稍后重试。");
|
|
299
299
|
this.messages.push({ id: `local-${Date.now()}`, role: "user", content: t, metadata_json: {} }), this.steps = [], this.renderPanel();
|
|
300
|
-
const
|
|
301
|
-
if (!
|
|
302
|
-
if (!
|
|
303
|
-
if (await U(
|
|
300
|
+
const r = await this.client.streamQuestion(this.currentThread.id, t, i.signal);
|
|
301
|
+
if (!r.ok) throw new Error(await I(r, "服务暂时无法回答,请稍后重试。"));
|
|
302
|
+
if (!r.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
|
|
303
|
+
if (await U(r.body, (l, p) => this.handleStreamEvent(l, p)), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
304
304
|
if (this.streamFailure) throw new Error(this.streamFailure);
|
|
305
305
|
if (!this.streamDone) throw new Error("服务响应意外中断,请稍后重试。");
|
|
306
306
|
if (await this.typewriter.drain(), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
307
307
|
await this.selectThread(this.currentThread);
|
|
308
|
-
} catch (
|
|
308
|
+
} catch (n) {
|
|
309
309
|
if (s !== this.activeRunId) return;
|
|
310
|
-
this.typewriter.clear(), this.waitingForFirstContent = !1, s === this.stoppedRunId ? this.answerStopped = !0 : (this.answerError =
|
|
310
|
+
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", details: { message: this.answerError } }));
|
|
311
311
|
} finally {
|
|
312
312
|
if (s !== this.activeRunId) return;
|
|
313
|
-
this.asking = !1, this.waitingForFirstContent = !1, this.abortController === i && (this.abortController = null), this.renderPanel();
|
|
313
|
+
this.asking = !1, this.waitingForFirstContent = !1, this.abortController === i && (this.abortController = null), this.renderPanel(!0);
|
|
314
314
|
}
|
|
315
315
|
}
|
|
316
316
|
cancelActiveAnswer(t) {
|
|
@@ -332,9 +332,9 @@ class F {
|
|
|
332
332
|
return;
|
|
333
333
|
}
|
|
334
334
|
if (t === "delta") {
|
|
335
|
-
const
|
|
336
|
-
if (!
|
|
337
|
-
this.waitingForFirstContent = !1, this.typewriter.enqueue(
|
|
335
|
+
const n = String((s = e.content) != null ? s : "");
|
|
336
|
+
if (!n) return;
|
|
337
|
+
this.waitingForFirstContent = !1, this.typewriter.enqueue(n);
|
|
338
338
|
return;
|
|
339
339
|
}
|
|
340
340
|
t === "done" && (this.streamDone = e), t === "error" && (this.streamFailure = String((i = e.message) != null ? i : "服务异常,请稍后重试。"));
|
|
@@ -373,9 +373,9 @@ class F {
|
|
|
373
373
|
stopSourceRefresh() {
|
|
374
374
|
this.sourceRefreshTimer && clearTimeout(this.sourceRefreshTimer), this.sourceRefreshTimer = null;
|
|
375
375
|
}
|
|
376
|
-
renderPanel() {
|
|
376
|
+
renderPanel(t = this.asking) {
|
|
377
377
|
if (!this.panel) return;
|
|
378
|
-
const
|
|
378
|
+
const e = this.questionUnavailableReason(), s = e || (this.asking ? "回答生成中,请稍候" : "请输入页面分析问题,Enter 发送,Shift + Enter 换行"), i = !!(e || this.asking), n = e ? '<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>';
|
|
379
379
|
if (this.panel.innerHTML = `
|
|
380
380
|
<aside class="po-sidebar">
|
|
381
381
|
<div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
|
|
@@ -383,9 +383,9 @@ class F {
|
|
|
383
383
|
<input class="po-search" placeholder="搜索问答" />
|
|
384
384
|
${this.conversationError ? `<p class="po-conversation-error" role="alert">${h(this.conversationError)}</p>` : ""}
|
|
385
385
|
<div class="po-thread-list">${this.conversations.map((r) => {
|
|
386
|
-
var
|
|
386
|
+
var l;
|
|
387
387
|
return `
|
|
388
|
-
<div class="po-thread-row ${r.id === ((
|
|
388
|
+
<div class="po-thread-row ${r.id === ((l = this.currentThread) == null ? void 0 : l.id) ? "active" : ""}">
|
|
389
389
|
<button class="po-thread" data-thread="${h(r.id)}" ${this.asking ? "disabled" : ""}>
|
|
390
390
|
<strong>${h(r.title)}</strong><span>${P(r.created_at)}</span>
|
|
391
391
|
</button>
|
|
@@ -399,10 +399,10 @@ class F {
|
|
|
399
399
|
${this.messages.map((r) => `<article class="po-message ${r.role}"><b>${r.role === "user" ? "你" : "PageOps 分析"}</b><div>${r.role === "assistant" ? w(r.content) : h(r.content)}</div></article>`).join("")}
|
|
400
400
|
${this.renderAnswerState()}
|
|
401
401
|
</section>
|
|
402
|
-
<form class="po-composer"><textarea ${
|
|
402
|
+
<form class="po-composer"><textarea ${i ? "disabled" : ""} placeholder="${h(s)}"></textarea>${n}</form>
|
|
403
403
|
</main>
|
|
404
404
|
<aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
|
|
405
|
-
`, this.bindPanelEvents(),
|
|
405
|
+
`, this.bindPanelEvents(), t) {
|
|
406
406
|
const r = this.panel.querySelector(".po-messages");
|
|
407
407
|
r && (r.scrollTop = r.scrollHeight);
|
|
408
408
|
}
|
|
@@ -428,8 +428,8 @@ class F {
|
|
|
428
428
|
}
|
|
429
429
|
renderSourceItem(t) {
|
|
430
430
|
var l, p, d;
|
|
431
|
-
const e = t.filename || "未命名代码包", s = t.created_at ? P(t.created_at) : "刚刚上传", i = _(t.archive_bytes || t.total_bytes || 0),
|
|
432
|
-
return `<article class="po-source-item"><strong>${h(e)}</strong><span>${h(s)} · ${h(i)}</span><span>${h(
|
|
431
|
+
const e = t.filename || "未命名代码包", s = t.created_at ? P(t.created_at) : "刚刚上传", i = _(t.archive_bytes || t.total_bytes || 0), n = String((p = (l = t.metadata) == null ? void 0 : l.analysis_status) != null ? p : "unknown"), r = (d = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[n]) != null ? d : "项目记忆状态未知";
|
|
432
|
+
return `<article class="po-source-item"><strong>${h(e)}</strong><span>${h(s)} · ${h(i)}</span><span>${h(r)}</span></article>`;
|
|
433
433
|
}
|
|
434
434
|
renderSteps() {
|
|
435
435
|
return (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", details: { message: "发送消息后展示执行过程。" } }]).map((e) => {
|
|
@@ -438,8 +438,8 @@ class F {
|
|
|
438
438
|
}).join("");
|
|
439
439
|
}
|
|
440
440
|
bindPanelEvents() {
|
|
441
|
-
var t, e, s, i,
|
|
442
|
-
(e = (t = this.panel) == null ? void 0 : t.querySelector('[data-action="new"]')) == null || e.addEventListener("click", () => void this.newConversation()), (i = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || i.addEventListener("click", () => this.close()), (
|
|
441
|
+
var t, e, s, i, n, r, l, p, d, f, y, S, b, $;
|
|
442
|
+
(e = (t = this.panel) == null ? void 0 : t.querySelector('[data-action="new"]')) == null || e.addEventListener("click", () => void this.newConversation()), (i = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || i.addEventListener("click", () => this.close()), (r = (n = this.panel) == null ? void 0 : n.querySelector('[data-action="stop-answer"]')) == null || r.addEventListener("click", () => this.cancelActiveAnswer(!0)), (p = (l = this.panel) == null ? void 0 : l.querySelector('[data-action="upload-source"]')) == null || p.addEventListener("change", (g) => {
|
|
443
443
|
var u;
|
|
444
444
|
const c = (u = g.target.files) == null ? void 0 : u[0];
|
|
445
445
|
c && this.uploadSource(c);
|
|
@@ -466,22 +466,22 @@ class F {
|
|
|
466
466
|
});
|
|
467
467
|
}
|
|
468
468
|
}
|
|
469
|
-
function h(
|
|
470
|
-
return
|
|
469
|
+
function h(a) {
|
|
470
|
+
return a.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
471
471
|
}
|
|
472
|
-
function P(
|
|
473
|
-
return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(
|
|
472
|
+
function P(a) {
|
|
473
|
+
return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(a));
|
|
474
474
|
}
|
|
475
|
-
function _(
|
|
476
|
-
if (!
|
|
475
|
+
function _(a) {
|
|
476
|
+
if (!a) return "0 B";
|
|
477
477
|
const t = ["B", "KB", "MB", "GB"];
|
|
478
|
-
let e =
|
|
478
|
+
let e = a, s = 0;
|
|
479
479
|
for (; e >= 1024 && s < t.length - 1; )
|
|
480
480
|
e /= 1024, s += 1;
|
|
481
481
|
return `${e >= 10 || s === 0 ? e.toFixed(0) : e.toFixed(1)} ${t[s]}`;
|
|
482
482
|
}
|
|
483
|
-
function A(
|
|
484
|
-
return { pending: "等待中", running: "执行中", completed: "已完成", failed: "失败", cancelled: "已停止" }[
|
|
483
|
+
function A(a) {
|
|
484
|
+
return { pending: "等待中", running: "执行中", completed: "已完成", failed: "失败", cancelled: "已停止" }[a];
|
|
485
485
|
}
|
|
486
486
|
const O = new F();
|
|
487
487
|
export {
|
package/dist/pageops-sdk.umd.cjs
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
(function(g,d){typeof exports=="object"&&typeof module!="undefined"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(g=typeof globalThis!="undefined"?globalThis:g||self,d(g.PageOpsSDK={}))})(this,(function(g){"use strict";var _=Object.defineProperty;var j=(g,d,w)=>d in g?_(g,d,{enumerable:!0,configurable:!0,writable:!0,value:w}):g[d]=w;var
|
|
2
|
-
`),e=[];for(let s=0;s<t.length;s+=1){const i=t[s];if(i.trim().startsWith("```")){const
|
|
3
|
-
`))}</code></pre>`);continue}const r=I(t,s);if(r){e.push(r.html),s=r.next-1;continue}i.startsWith("### ")?e.push(`<h4>${y(i.slice(4))}</h4>`):i.startsWith("## ")?e.push(`<h3>${y(i.slice(3))}</h3>`):i.startsWith("# ")?e.push(`<h2>${y(i.slice(2))}</h2>`):i.startsWith("- ")?e.push(`<li>${y(i.slice(2))}</li>`):i.trim()?e.push(`<p>${y(i)}</p>`):e.push("<br>")}return e.join("")}async function R(a,t){var r;const e=a.getReader(),s=new TextDecoder;let i="";for(;;){const{done:o,value:h}=await e.read();if(o){i+=s.decode();break}i+=s.decode(h,{stream:!0});const f=i.split(/\r?\n\r?\n/);i=(r=f.pop())!=null?r:"";for(const u of f)E(u,t)}i.trim()&&E(i,t)}function E(a,t){var i,r;const e=(i=a.match(/^event:\s*(.+)$/m))==null?void 0:i[1],s=(r=a.match(/^data:\s*(.+)$/m))==null?void 0:r[1];e&&s&&t(e,JSON.parse(s))}class U{constructor(t,e=16){n(this,"queue",[]);n(this,"timer",null);n(this,"drainWaiters",[]);this.onChunk=t,this.interval=e}enqueue(t){this.queue.push(...Array.from(t)),this.timer||this.tick()}async drain(){!this.timer&&!this.queue.length||await new Promise(t=>this.drainWaiters.push(t))}clear(){this.timer&&clearTimeout(this.timer),this.timer=null,this.queue=[],this.resolveDrainWaiters()}tick(){const t=Math.max(1,Math.ceil(this.queue.length/90)),e=this.queue.splice(0,t).join("");if(e&&this.onChunk(e),!this.queue.length){this.timer=null,this.resolveDrainWaiters();return}this.timer=setTimeout(()=>this.tick(),this.interval)}resolveDrainWaiters(){for(const t of this.drainWaiters.splice(0))t()}}class q{constructor(){n(this,"client",null);n(this,"options",null);n(this,"root",null);n(this,"panel",null);n(this,"context",null);n(this,"contextKey","");n(this,"selectedPageKey","");n(this,"currentThread",null);n(this,"conversations",[]);n(this,"messages",[]);n(this,"steps",[]);n(this,"sourceSnapshots",[]);n(this,"sourceUploadStatus","");n(this,"sourceUploadError","");n(this,"sourceUploading",!1);n(this,"sourceRefreshTimer",null);n(this,"streaming","");n(this,"asking",!1);n(this,"waitingForFirstContent",!1);n(this,"abortController",null);n(this,"activeRunId",0);n(this,"stoppedRunId",-1);n(this,"answerStopped",!1);n(this,"answerError","");n(this,"conversationError","");n(this,"deletingThreadId","");n(this,"streamFailure","");n(this,"streamDone",null);n(this,"typewriter",new U(t=>{this.streaming+=t,this.updateStreamingMessage()}))}mount(t){var e;this.unmount(),this.options=t,this.client=new d(t),this.root=document.createElement("div"),this.root.className="pageops-sdk",((e=t.container)!=null?e:document.body).appendChild(this.root),this.renderClosed()}unmount(){var t;this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.resetAnswerState(),(t=this.root)==null||t.remove(),this.root=null,this.panel=null,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceUploading=!1}open(){this.root&&(this.root.innerHTML="",this.panel=document.createElement("div"),this.panel.className="po-panel",this.root.appendChild(this.panel),this.loadSources(),this.loadConversations(),this.renderPanel())}close(){this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.renderClosed()}updateContext(t){this.options&&(this.options={...this.options,...t},this.client=new d(this.options),this.context=null,this.contextKey="")}renderClosed(){var t;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(t=this.root.querySelector("button"))==null||t.addEventListener("click",()=>this.open()))}async ensureContext(){if(!this.client||!this.options)throw new Error("PageOps SDK 未初始化");const t=this.getPageContext(),e=this.getPageContextKey(t);return this.context&&this.contextKey===e?this.context:(this.context=await this.client.createContext(t),this.contextKey=e,this.context)}getPageContext(){var t,e,s;return(s=(e=(t=this.options)==null?void 0:t.getPageContext)==null?void 0:e.call(t))!=null?s:{}}getPageContextKey(t){var e,s,i,r;return JSON.stringify([(e=t.route)!=null?e:"",(s=t.url)!=null?s:location.href,(i=t.title)!=null?i:document.title,(r=t.menuPath)!=null?r:[]])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceUploadError=""}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包状态加载失败"}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 t=await this.ensureContext(),e=(s=t.menu_path)!=null&&s.length?t.menu_path.join(" / "):t.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(t.id,e),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(t){this.client&&(this.currentThread=t,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(t.id),this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel())}async deleteConversation(t){var e;if(!(!this.client||this.asking||this.deletingThreadId)&&window.confirm(`确定删除会话“${t.title}”吗?此操作无法撤销。`)){this.deletingThreadId=t.id,this.conversationError="",this.renderPanel();try{if(await this.client.deleteConversation(t.id),this.conversations=this.conversations.filter(s=>s.id!==t.id),((e=this.currentThread)==null?void 0:e.id)===t.id){this.currentThread=null,this.messages=[],this.steps=[],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(t){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(t),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(e){this.sourceUploadError=e instanceof Error?e.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(t){if(!this.client||this.asking)return;const e=this.questionUnavailableReason();if(e){this.sourceUploadError=e,this.renderPanel();return}this.resetAnswerState();const s=++this.activeRunId,i=new AbortController;this.abortController=i,this.stoppedRunId=-1,this.asking=!0,this.waitingForFirstContent=!0,this.renderPanel();try{const r=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==r&&(this.currentThread=null),this.currentThread||await this.newConversation(),!this.currentThread)throw new Error("无法创建问答会话,请稍后重试。");this.messages.push({id:`local-${Date.now()}`,role:"user",content:t,metadata_json:{}}),this.steps=[],this.renderPanel();const o=await this.client.streamQuestion(this.currentThread.id,t,i.signal);if(!o.ok)throw new Error(await w(o,"服务暂时无法回答,请稍后重试。"));if(!o.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await R(o.body,(h,f)=>this.handleStreamEvent(h,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(r){if(s!==this.activeRunId)return;this.typewriter.clear(),this.waitingForFirstContent=!1,s===this.stoppedRunId?this.answerStopped=!0:(this.answerError=r instanceof Error?r.message:"服务异常,请稍后重试。",this.upsertStep({id:"error",title:"执行失败",status:"failed",details:{message:this.answerError}}))}finally{if(s!==this.activeRunId)return;this.asking=!1,this.waitingForFirstContent=!1,this.abortController===i&&(this.abortController=null),this.renderPanel()}}cancelActiveAnswer(t){var e;if(!(!this.asking&&!this.abortController)){if(t){this.stoppedRunId=this.activeRunId,this.answerStopped=!0;const s=this.steps.map(i=>i.status==="running"?{...i,status:"cancelled"}:i);this.steps=s.some(i=>i.status==="cancelled")?s:[...s,{id:"stopped",title:"已停止",status:"cancelled"}]}else this.activeRunId+=1,this.asking=!1;this.typewriter.clear(),this.waitingForFirstContent=!1,(e=this.abortController)==null||e.abort(),this.abortController=null,t&&this.renderPanel()}}handleStreamEvent(t,e){var s,i;if(t==="step"){this.upsertStep(e),this.renderPanel();return}if(t==="delta"){const r=String((s=e.content)!=null?s:"");if(!r)return;this.waitingForFirstContent=!1,this.typewriter.enqueue(r);return}t==="done"&&(this.streamDone=e),t==="error"&&(this.streamFailure=String((i=e.message)!=null?i:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,i;const t=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!t){this.renderPanel();return}t.innerHTML=b(this.streaming);const e=(i=this.panel)==null?void 0:i.querySelector(".po-messages");e&&(e.scrollTop=e.scrollHeight)}resetAnswerState(){this.typewriter.clear(),this.asking=!1,this.waitingForFirstContent=!1,this.answerError="",this.answerStopped=!1,this.streamFailure="",this.streamDone=null,this.streaming=""}upsertStep(t){const e=this.steps.findIndex(s=>s.id===t.id);this.steps=e===-1?[...this.steps,t]:this.steps.map(s=>s.id===t.id?{...s,...t}:s)}latestAnalysisStatus(){var t,e,s;return String((s=(e=(t=this.sourceSnapshots[0])==null?void 0:t.metadata)==null?void 0:e.analysis_status)!=null?s:"")}isProjectMemoryUpdating(){return["pending","running"].includes(this.latestAnalysisStatus())}questionUnavailableReason(){return this.sourceSnapshots.length?this.isProjectMemoryUpdating()?"项目记忆正在更新,完成前暂不能问答。":this.latestAnalysisStatus()==="failed"?"项目记忆更新失败,请重新上传或重新索引。":"":"请先上传代码包后再提问。"}scheduleSourceRefresh(){this.stopSourceRefresh(),this.isProjectMemoryUpdating()&&(this.sourceRefreshTimer=setTimeout(()=>void this.loadSources(),1500))}stopSourceRefresh(){this.sourceRefreshTimer&&clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null}renderPanel(){if(!this.panel)return;const t=this.questionUnavailableReason(),e=t||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),s=!!(t||this.asking),i=t?'<button type="submit" disabled>暂不可提问</button>':this.asking?'<button class="po-stop" type="button" data-action="stop-answer" aria-label="停止输出" title="停止输出"><span aria-hidden="true"></span></button>':'<button type="submit">发送</button>';if(this.panel.innerHTML=`
|
|
1
|
+
(function(g,d){typeof exports=="object"&&typeof module!="undefined"?d(exports):typeof define=="function"&&define.amd?define(["exports"],d):(g=typeof globalThis!="undefined"?globalThis:g||self,d(g.PageOpsSDK={}))})(this,(function(g){"use strict";var _=Object.defineProperty;var j=(g,d,w)=>d in g?_(g,d,{enumerable:!0,configurable:!0,writable:!0,value:w}):g[d]=w;var a=(g,d,w)=>j(g,typeof d!="symbol"?d+"":d,w);class d{constructor(t){this.options=t}async createContext(t=(i=>(i=(e=>(s=>(s=(e=this.options).getPageContext)==null?void 0:s.call(e))())())!=null?i:{})()){var n,r,l;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:t.route,url:(n=t.url)!=null?n:location.href,title:(r=t.title)!=null?r:document.title,menu_path:(l=t.menuPath)!=null?l:[],tenant_id:t.tenantId,user_role:t.userRole,build_version:t.buildVersion})})}async listConversations(){return(await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations}async createConversation(t,e){return this.request("/conversations",{method:"POST",body:JSON.stringify({app_id:this.options.appId,context_session_id:t,title:e})})}async deleteConversation(t){return this.request(`/conversations/${encodeURIComponent(t)}?app_id=${encodeURIComponent(this.options.appId)}`,{method:"DELETE"})}async listMessages(t){return(await this.request(`/conversations/${encodeURIComponent(t)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages}async listSources(){return(await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources}uploadSource(t){const e=new FormData;return e.append("file",t),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:e,headers:{}})}streamQuestion(t,e,s){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:this.options.appId,thread_id:t,question:e}),signal:s})}async request(t,e){var r,l;const s=(e==null?void 0:e.body)instanceof FormData?e.headers:{"content-type":"application/json",...(r=e==null?void 0:e.headers)!=null?r:{}},i=await fetch(`${this.base()}${t}`,{...e,headers:s});if(i.status===204)return;const n=await i.json();if(!i.ok)throw new Error((l=n.message)!=null?l:"PageOps 请求失败");return n}base(){const t=this.options.apiBase.replace(/\/$/,"");return t.endsWith("/api")?t:`${t}/api`}}async function w(o,t){const e=await o.json().catch(()=>null);return typeof(e==null?void 0:e.message)=="string"&&e.message.trim()?e.message:t}function $(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function y(o){return $(o).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function I(o,t){const e=o[t],s=o[t+1];if(!(e!=null&&e.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const i=[];let n=t;for(;n<o.length&&o[n].includes("|")&&o[n].trim();)i.push(o[n]),n+=1;const r=u=>u.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(S=>y(S.trim())),l=r(i[0]).map(u=>`<th>${u}</th>`).join(""),f=i.slice(2).map(u=>`<tr>${r(u).map(S=>`<td>${S}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${l}</tr></thead><tbody>${f}</tbody></table>`,next:n}}function b(o){const t=o.split(`
|
|
2
|
+
`),e=[];for(let s=0;s<t.length;s+=1){const i=t[s];if(i.trim().startsWith("```")){const r=[];for(s+=1;s<t.length&&!t[s].trim().startsWith("```");)r.push(t[s]),s+=1;e.push(`<pre><code>${$(r.join(`
|
|
3
|
+
`))}</code></pre>`);continue}const n=I(t,s);if(n){e.push(n.html),s=n.next-1;continue}i.startsWith("### ")?e.push(`<h4>${y(i.slice(4))}</h4>`):i.startsWith("## ")?e.push(`<h3>${y(i.slice(3))}</h3>`):i.startsWith("# ")?e.push(`<h2>${y(i.slice(2))}</h2>`):i.startsWith("- ")?e.push(`<li>${y(i.slice(2))}</li>`):i.trim()?e.push(`<p>${y(i)}</p>`):e.push("<br>")}return e.join("")}async function R(o,t){var n;const e=o.getReader(),s=new TextDecoder;let i="";for(;;){const{done:r,value:l}=await e.read();if(r){i+=s.decode();break}i+=s.decode(l,{stream:!0});const f=i.split(/\r?\n\r?\n/);i=(n=f.pop())!=null?n:"";for(const u of f)E(u,t)}i.trim()&&E(i,t)}function E(o,t){var i,n;const e=(i=o.match(/^event:\s*(.+)$/m))==null?void 0:i[1],s=(n=o.match(/^data:\s*(.+)$/m))==null?void 0:n[1];e&&s&&t(e,JSON.parse(s))}class U{constructor(t,e=16){a(this,"queue",[]);a(this,"timer",null);a(this,"drainWaiters",[]);this.onChunk=t,this.interval=e}enqueue(t){this.queue.push(...Array.from(t)),this.timer||this.tick()}async drain(){!this.timer&&!this.queue.length||await new Promise(t=>this.drainWaiters.push(t))}clear(){this.timer&&clearTimeout(this.timer),this.timer=null,this.queue=[],this.resolveDrainWaiters()}tick(){const t=Math.max(1,Math.ceil(this.queue.length/90)),e=this.queue.splice(0,t).join("");if(e&&this.onChunk(e),!this.queue.length){this.timer=null,this.resolveDrainWaiters();return}this.timer=setTimeout(()=>this.tick(),this.interval)}resolveDrainWaiters(){for(const t of this.drainWaiters.splice(0))t()}}class q{constructor(){a(this,"client",null);a(this,"options",null);a(this,"root",null);a(this,"panel",null);a(this,"context",null);a(this,"contextKey","");a(this,"selectedPageKey","");a(this,"currentThread",null);a(this,"conversations",[]);a(this,"messages",[]);a(this,"steps",[]);a(this,"sourceSnapshots",[]);a(this,"sourceUploadStatus","");a(this,"sourceUploadError","");a(this,"sourceUploading",!1);a(this,"sourceRefreshTimer",null);a(this,"streaming","");a(this,"asking",!1);a(this,"waitingForFirstContent",!1);a(this,"abortController",null);a(this,"activeRunId",0);a(this,"stoppedRunId",-1);a(this,"answerStopped",!1);a(this,"answerError","");a(this,"conversationError","");a(this,"deletingThreadId","");a(this,"streamFailure","");a(this,"streamDone",null);a(this,"typewriter",new U(t=>{this.streaming+=t,this.updateStreamingMessage()}))}mount(t){var e;this.unmount(),this.options=t,this.client=new d(t),this.root=document.createElement("div"),this.root.className="pageops-sdk",((e=t.container)!=null?e:document.body).appendChild(this.root),this.renderClosed()}unmount(){var t;this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.resetAnswerState(),(t=this.root)==null||t.remove(),this.root=null,this.panel=null,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceUploading=!1}open(){this.root&&(this.root.innerHTML="",this.panel=document.createElement("div"),this.panel.className="po-panel",this.root.appendChild(this.panel),this.loadSources(),this.loadConversations(),this.renderPanel())}close(){this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.renderClosed()}updateContext(t){this.options&&(this.options={...this.options,...t},this.client=new d(this.options),this.context=null,this.contextKey="")}renderClosed(){var t;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(t=this.root.querySelector("button"))==null||t.addEventListener("click",()=>this.open()))}async ensureContext(){if(!this.client||!this.options)throw new Error("PageOps SDK 未初始化");const t=this.getPageContext(),e=this.getPageContextKey(t);return this.context&&this.contextKey===e?this.context:(this.context=await this.client.createContext(t),this.contextKey=e,this.context)}getPageContext(){var t,e,s;return(s=(e=(t=this.options)==null?void 0:t.getPageContext)==null?void 0:e.call(t))!=null?s:{}}getPageContextKey(t){var e,s,i,n;return JSON.stringify([(e=t.route)!=null?e:"",(s=t.url)!=null?s:location.href,(i=t.title)!=null?i:document.title,(n=t.menuPath)!=null?n:[]])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceUploadError=""}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包状态加载失败"}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 t=await this.ensureContext(),e=(s=t.menu_path)!=null&&s.length?t.menu_path.join(" / "):t.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(t.id,e),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(t){this.client&&(this.currentThread=t,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(t.id),this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel())}async deleteConversation(t){var e;if(!(!this.client||this.asking||this.deletingThreadId)&&window.confirm(`确定删除会话“${t.title}”吗?此操作无法撤销。`)){this.deletingThreadId=t.id,this.conversationError="",this.renderPanel();try{if(await this.client.deleteConversation(t.id),this.conversations=this.conversations.filter(s=>s.id!==t.id),((e=this.currentThread)==null?void 0:e.id)===t.id){this.currentThread=null,this.messages=[],this.steps=[],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(t){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(t),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(e){this.sourceUploadError=e instanceof Error?e.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(t){if(!this.client||this.asking)return;const e=this.questionUnavailableReason();if(e){this.sourceUploadError=e,this.renderPanel();return}this.resetAnswerState();const s=++this.activeRunId,i=new AbortController;this.abortController=i,this.stoppedRunId=-1,this.asking=!0,this.waitingForFirstContent=!0,this.renderPanel();try{const n=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==n&&(this.currentThread=null),this.currentThread||await this.newConversation(),!this.currentThread)throw new Error("无法创建问答会话,请稍后重试。");this.messages.push({id:`local-${Date.now()}`,role:"user",content:t,metadata_json:{}}),this.steps=[],this.renderPanel();const r=await this.client.streamQuestion(this.currentThread.id,t,i.signal);if(!r.ok)throw new Error(await w(r,"服务暂时无法回答,请稍后重试。"));if(!r.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await R(r.body,(l,f)=>this.handleStreamEvent(l,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",details:{message:this.answerError}}))}finally{if(s!==this.activeRunId)return;this.asking=!1,this.waitingForFirstContent=!1,this.abortController===i&&(this.abortController=null),this.renderPanel(!0)}}cancelActiveAnswer(t){var e;if(!(!this.asking&&!this.abortController)){if(t){this.stoppedRunId=this.activeRunId,this.answerStopped=!0;const s=this.steps.map(i=>i.status==="running"?{...i,status:"cancelled"}:i);this.steps=s.some(i=>i.status==="cancelled")?s:[...s,{id:"stopped",title:"已停止",status:"cancelled"}]}else this.activeRunId+=1,this.asking=!1;this.typewriter.clear(),this.waitingForFirstContent=!1,(e=this.abortController)==null||e.abort(),this.abortController=null,t&&this.renderPanel()}}handleStreamEvent(t,e){var s,i;if(t==="step"){this.upsertStep(e),this.renderPanel();return}if(t==="delta"){const n=String((s=e.content)!=null?s:"");if(!n)return;this.waitingForFirstContent=!1,this.typewriter.enqueue(n);return}t==="done"&&(this.streamDone=e),t==="error"&&(this.streamFailure=String((i=e.message)!=null?i:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,i;const t=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!t){this.renderPanel();return}t.innerHTML=b(this.streaming);const e=(i=this.panel)==null?void 0:i.querySelector(".po-messages");e&&(e.scrollTop=e.scrollHeight)}resetAnswerState(){this.typewriter.clear(),this.asking=!1,this.waitingForFirstContent=!1,this.answerError="",this.answerStopped=!1,this.streamFailure="",this.streamDone=null,this.streaming=""}upsertStep(t){const e=this.steps.findIndex(s=>s.id===t.id);this.steps=e===-1?[...this.steps,t]:this.steps.map(s=>s.id===t.id?{...s,...t}:s)}latestAnalysisStatus(){var t,e,s;return String((s=(e=(t=this.sourceSnapshots[0])==null?void 0:t.metadata)==null?void 0:e.analysis_status)!=null?s:"")}isProjectMemoryUpdating(){return["pending","running"].includes(this.latestAnalysisStatus())}questionUnavailableReason(){return this.sourceSnapshots.length?this.isProjectMemoryUpdating()?"项目记忆正在更新,完成前暂不能问答。":this.latestAnalysisStatus()==="failed"?"项目记忆更新失败,请重新上传或重新索引。":"":"请先上传代码包后再提问。"}scheduleSourceRefresh(){this.stopSourceRefresh(),this.isProjectMemoryUpdating()&&(this.sourceRefreshTimer=setTimeout(()=>void this.loadSources(),1500))}stopSourceRefresh(){this.sourceRefreshTimer&&clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null}renderPanel(t=this.asking){if(!this.panel)return;const e=this.questionUnavailableReason(),s=e||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),i=!!(e||this.asking),n=e?'<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>';if(this.panel.innerHTML=`
|
|
4
4
|
<aside class="po-sidebar">
|
|
5
5
|
<div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
|
|
6
6
|
<button class="po-new" data-action="new" ${this.asking?"disabled":""}>+ 新建问答</button>
|
|
7
7
|
<input class="po-search" placeholder="搜索问答" />
|
|
8
|
-
${this.conversationError?`<p class="po-conversation-error" role="alert">${
|
|
9
|
-
<div class="po-thread-list">${this.conversations.map(r=>{var
|
|
10
|
-
<div class="po-thread-row ${r.id===((
|
|
11
|
-
<button class="po-thread" data-thread="${
|
|
12
|
-
<strong>${
|
|
8
|
+
${this.conversationError?`<p class="po-conversation-error" role="alert">${h(this.conversationError)}</p>`:""}
|
|
9
|
+
<div class="po-thread-list">${this.conversations.map(r=>{var l;return`
|
|
10
|
+
<div class="po-thread-row ${r.id===((l=this.currentThread)==null?void 0:l.id)?"active":""}">
|
|
11
|
+
<button class="po-thread" data-thread="${h(r.id)}" ${this.asking?"disabled":""}>
|
|
12
|
+
<strong>${h(r.title)}</strong><span>${P(r.created_at)}</span>
|
|
13
13
|
</button>
|
|
14
|
-
<button class="po-thread-delete" type="button" data-delete-thread="${
|
|
14
|
+
<button class="po-thread-delete" type="button" data-delete-thread="${h(r.id)}" aria-label="删除会话:${h(r.title)}" title="删除会话" ${this.asking||this.deletingThreadId===r.id?"disabled":""}><span class="po-trash-icon" aria-hidden="true"></span></button>
|
|
15
15
|
</div>`}).join("")}</div>
|
|
16
16
|
</aside>
|
|
17
17
|
<main class="po-chat">
|
|
18
|
-
<header><div><p>问数回答</p><h2>${this.currentThread?
|
|
18
|
+
<header><div><p>问数回答</p><h2>${this.currentThread?h(this.currentThread.title):"未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
|
|
19
19
|
<section class="po-messages">
|
|
20
|
-
${this.messages.map(r=>`<article class="po-message ${r.role}"><b>${r.role==="user"?"你":"PageOps 分析"}</b><div>${r.role==="assistant"?b(r.content):
|
|
20
|
+
${this.messages.map(r=>`<article class="po-message ${r.role}"><b>${r.role==="user"?"你":"PageOps 分析"}</b><div>${r.role==="assistant"?b(r.content):h(r.content)}</div></article>`).join("")}
|
|
21
21
|
${this.renderAnswerState()}
|
|
22
22
|
</section>
|
|
23
|
-
<form class="po-composer"><textarea ${
|
|
23
|
+
<form class="po-composer"><textarea ${i?"disabled":""} placeholder="${h(s)}"></textarea>${n}</form>
|
|
24
24
|
</main>
|
|
25
25
|
<aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
|
|
26
|
-
`,this.bindPanelEvents(),
|
|
26
|
+
`,this.bindPanelEvents(),t){const r=this.panel.querySelector(".po-messages");r&&(r.scrollTop=r.scrollHeight)}}renderAnswerState(){const t=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>':"",e=this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div><span data-streaming-content>${b(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>${h(this.answerError)}</div></article>`:"",i=this.answerStopped?'<div class="po-stream-stopped" role="status">已停止输出</div>':"";return`${t}${e}${i}${s}`}renderSourceUploader(){return`
|
|
27
27
|
<div class="po-source-uploader">
|
|
28
28
|
<strong>源码包</strong>
|
|
29
29
|
<p>上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
|
|
@@ -31,8 +31,8 @@
|
|
|
31
31
|
<span>${this.sourceUploading?"上传中...":"选择代码包"}</span>
|
|
32
32
|
<input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
|
|
33
33
|
</label>
|
|
34
|
-
${this.sourceUploadStatus?`<p class="po-upload-status">${
|
|
34
|
+
${this.sourceUploadStatus?`<p class="po-upload-status">${h(this.sourceUploadStatus)}</p>`:""}
|
|
35
35
|
${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(t=>this.renderSourceItem(t)).join("")}</div>`:'<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
|
|
36
|
-
${this.sourceUploadError?`<p class="po-upload-error">${
|
|
36
|
+
${this.sourceUploadError?`<p class="po-upload-error">${h(this.sourceUploadError)}</p>`:""}
|
|
37
37
|
</div>
|
|
38
|
-
`}renderSourceItem(t){var
|
|
38
|
+
`}renderSourceItem(t){var l,f,u;const e=t.filename||"未命名代码包",s=t.created_at?P(t.created_at):"刚刚上传",i=F(t.archive_bytes||t.total_bytes||0),n=String((f=(l=t.metadata)==null?void 0:l.analysis_status)!=null?f:"unknown"),r=(u={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[n])!=null?u:"项目记忆状态未知";return`<article class="po-source-item"><strong>${h(e)}</strong><span>${h(s)} · ${h(i)}</span><span>${h(r)}</span></article>`}renderSteps(){return(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",details:{message:"发送消息后展示执行过程。"}}]).map(e=>{var s;return`<details class="po-step ${e.status}" ${e.status==="running"||e.status==="failed"?"open":""}><summary><strong>${h(e.title)}</strong><span>${O(e.status)}</span></summary><pre>${h(JSON.stringify((s=e.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var t,e,s,i,n,r,l,f,u,S,C,T,x,k;(e=(t=this.panel)==null?void 0:t.querySelector('[data-action="new"]'))==null||e.addEventListener("click",()=>void this.newConversation()),(i=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||i.addEventListener("click",()=>this.close()),(r=(n=this.panel)==null?void 0:n.querySelector('[data-action="stop-answer"]'))==null||r.addEventListener("click",()=>this.cancelActiveAnswer(!0)),(f=(l=this.panel)==null?void 0:l.querySelector('[data-action="upload-source"]'))==null||f.addEventListener("change",m=>{var p;const c=(p=m.target.files)==null?void 0:p[0];c&&this.uploadSource(c)}),(u=this.panel)==null||u.querySelectorAll("[data-thread]").forEach(m=>{m.addEventListener("click",()=>{const c=this.conversations.find(p=>p.id===m.dataset.thread);c&&this.selectThread(c)})}),(S=this.panel)==null||S.querySelectorAll("[data-delete-thread]").forEach(m=>{m.addEventListener("click",c=>{c.stopPropagation();const p=this.conversations.find(v=>v.id===m.dataset.deleteThread);p&&this.deleteConversation(p)})}),(T=(C=this.panel)==null?void 0:C.querySelector("form"))==null||T.addEventListener("submit",m=>{var v;m.preventDefault();const c=(v=this.panel)==null?void 0:v.querySelector("textarea"),p=c==null?void 0:c.value.trim();p&&(c.value="",this.ask(p))}),(k=(x=this.panel)==null?void 0:x.querySelector("textarea"))==null||k.addEventListener("keydown",m=>{var p,v;const c=m;c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),(v=(p=this.panel)==null?void 0:p.querySelector("form"))==null||v.requestSubmit())})}}function h(o){return o.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function P(o){return new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(o))}function F(o){if(!o)return"0 B";const t=["B","KB","MB","GB"];let e=o,s=0;for(;e>=1024&&s<t.length-1;)e/=1024,s+=1;return`${e>=10||s===0?e.toFixed(0):e.toFixed(1)} ${t[s]}`}function O(o){return{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",cancelled:"已停止"}[o]}const K=new q;g.PageOpsSDK=K,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
|