@pageops/sdk 0.1.7 → 0.1.9
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/client.d.ts +3 -1
- package/dist/index.d.ts +18 -0
- package/dist/pageops-sdk.css +1 -1
- package/dist/pageops-sdk.es.js +279 -136
- package/dist/pageops-sdk.umd.cjs +21 -19
- package/dist/types.d.ts +1 -1
- package/dist/typewriter.d.ts +13 -0
- package/package.json +6 -3
package/dist/client.d.ts
CHANGED
|
@@ -5,10 +5,12 @@ export declare class PageOpsClient {
|
|
|
5
5
|
createContext(context?: PageOpsContext): Promise<ContextSession>;
|
|
6
6
|
listConversations(): Promise<ConversationThread[]>;
|
|
7
7
|
createConversation(contextSessionId: string, title?: string): Promise<ConversationThread>;
|
|
8
|
+
deleteConversation(threadId: string): Promise<void>;
|
|
8
9
|
listMessages(threadId: string): Promise<ConversationMessage[]>;
|
|
9
10
|
listSources(): Promise<SourceSnapshot[]>;
|
|
10
11
|
uploadSource(file: File): Promise<SourceSnapshot>;
|
|
11
|
-
streamQuestion(threadId: string, question: string): Promise<Response>;
|
|
12
|
+
streamQuestion(threadId: string, question: string, signal?: AbortSignal): Promise<Response>;
|
|
12
13
|
private request;
|
|
13
14
|
private base;
|
|
14
15
|
}
|
|
16
|
+
export declare function responseErrorMessage(response: Response, fallback: string): Promise<string>;
|
package/dist/index.d.ts
CHANGED
|
@@ -18,6 +18,18 @@ declare class PageOpsSDKController {
|
|
|
18
18
|
private sourceUploading;
|
|
19
19
|
private sourceRefreshTimer;
|
|
20
20
|
private streaming;
|
|
21
|
+
private asking;
|
|
22
|
+
private waitingForFirstContent;
|
|
23
|
+
private abortController;
|
|
24
|
+
private activeRunId;
|
|
25
|
+
private stoppedRunId;
|
|
26
|
+
private answerStopped;
|
|
27
|
+
private answerError;
|
|
28
|
+
private conversationError;
|
|
29
|
+
private deletingThreadId;
|
|
30
|
+
private streamFailure;
|
|
31
|
+
private streamDone;
|
|
32
|
+
private typewriter;
|
|
21
33
|
mount(options: PageOpsMountOptions): void;
|
|
22
34
|
unmount(): void;
|
|
23
35
|
open(): void;
|
|
@@ -31,8 +43,13 @@ declare class PageOpsSDKController {
|
|
|
31
43
|
private loadConversations;
|
|
32
44
|
private newConversation;
|
|
33
45
|
private selectThread;
|
|
46
|
+
private deleteConversation;
|
|
34
47
|
private uploadSource;
|
|
35
48
|
private ask;
|
|
49
|
+
private cancelActiveAnswer;
|
|
50
|
+
private handleStreamEvent;
|
|
51
|
+
private updateStreamingMessage;
|
|
52
|
+
private resetAnswerState;
|
|
36
53
|
private upsertStep;
|
|
37
54
|
private latestAnalysisStatus;
|
|
38
55
|
private isProjectMemoryUpdating;
|
|
@@ -40,6 +57,7 @@ declare class PageOpsSDKController {
|
|
|
40
57
|
private scheduleSourceRefresh;
|
|
41
58
|
private stopSourceRefresh;
|
|
42
59
|
private renderPanel;
|
|
60
|
+
private renderAnswerState;
|
|
43
61
|
private renderSourceUploader;
|
|
44
62
|
private renderSourceItem;
|
|
45
63
|
private renderSteps;
|
package/dist/pageops-sdk.css
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
.pageops-sdk{--po-text: #172033;--po-muted: #64748b;--po-border: #dbe5f5;--po-soft-border: #e2e8f0;--po-surface: #ffffff;--po-soft: #f8fafc;--po-panel: #fbfdff;--po-primary: #2563eb;--po-primary-dark: #1d4ed8;--po-shadow: 0 24px 70px rgb(15 23 42 / 18%);color:var(--po-text);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.pageops-sdk *,.pageops-sdk *:before,.pageops-sdk *:after{box-sizing:border-box}.pageops-sdk button,.pageops-sdk input,.pageops-sdk textarea{font:inherit}.pageops-sdk button{cursor:pointer}.po-fab{position:fixed;right:24px;bottom:24px;z-index:2147483000;border:0;border-radius:999px;padding:12px 18px;background:linear-gradient(135deg,#2563eb,#14b8a6);color:#fff;font-weight:800;box-shadow:0 18px 42px #2563eb47}.po-panel{position:fixed;inset:40px;z-index:2147483000;display:grid;grid-template-columns:250px minmax(0,1fr) 340px;min-height:520px;overflow:hidden;border:1px solid var(--po-border);border-radius:24px;background:var(--po-surface);box-shadow:var(--po-shadow)}.po-sidebar{display:flex;min-width:0;min-height:0;flex-direction:column;gap:12px;overflow:hidden;border-right:1px solid #dbeafe;background:#eef5ff;padding:16px}.po-brand{display:flex;align-items:center;gap:10px}.po-brand strong,.po-brand span{display:block}.po-brand span{margin-top:2px;color:var(--po-muted);font-size:12px}.po-logo{width:34px;height:34px;flex:0 0 auto;border-radius:12px;background:linear-gradient(135deg,#5eead4,#2563eb)}.po-new,.po-composer button{border:0;border-radius:10px;background:var(--po-primary);color:#fff;font-weight:750}.po-new{width:100%;padding:10px 12px}.po-search,.po-composer textarea{width:100%;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:var(--po-text);outline:none}.po-search{padding:9px 10px}.po-thread-list{display:grid;align-content:start;gap:8px;min-height:0;overflow:auto}.po-thread{display:grid;
|
|
1
|
+
.pageops-sdk{--po-text: #172033;--po-muted: #64748b;--po-border: #dbe5f5;--po-soft-border: #e2e8f0;--po-surface: #ffffff;--po-soft: #f8fafc;--po-panel: #fbfdff;--po-primary: #2563eb;--po-primary-dark: #1d4ed8;--po-shadow: 0 24px 70px rgb(15 23 42 / 18%);color:var(--po-text);font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.pageops-sdk *,.pageops-sdk *:before,.pageops-sdk *:after{box-sizing:border-box}.pageops-sdk button,.pageops-sdk input,.pageops-sdk textarea{font:inherit}.pageops-sdk button{cursor:pointer}.po-fab{position:fixed;right:24px;bottom:24px;z-index:2147483000;border:0;border-radius:999px;padding:12px 18px;background:linear-gradient(135deg,#2563eb,#14b8a6);color:#fff;font-weight:800;box-shadow:0 18px 42px #2563eb47}.po-panel{position:fixed;inset:40px;z-index:2147483000;display:grid;grid-template-columns:250px minmax(0,1fr) 340px;min-height:520px;overflow:hidden;border:1px solid var(--po-border);border-radius:24px;background:var(--po-surface);box-shadow:var(--po-shadow)}.po-sidebar{display:flex;min-width:0;min-height:0;flex-direction:column;gap:12px;overflow:hidden;border-right:1px solid #dbeafe;background:#eef5ff;padding:16px}.po-brand{display:flex;align-items:center;gap:10px}.po-brand strong,.po-brand span{display:block}.po-brand span{margin-top:2px;color:var(--po-muted);font-size:12px}.po-logo{width:34px;height:34px;flex:0 0 auto;border-radius:12px;background:linear-gradient(135deg,#5eead4,#2563eb)}.po-new,.po-composer button{border:0;border-radius:10px;background:var(--po-primary);color:#fff;font-weight:750}.po-new{width:100%;padding:10px 12px}.po-search,.po-composer textarea{width:100%;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:var(--po-text);outline:none}.po-search{padding:9px 10px}.po-thread-list{display:grid;align-content:start;gap:8px;min-height:0;overflow:auto}.po-thread-row{position:relative;display:grid;grid-template-columns:minmax(0,1fr) 32px;align-items:center;border:1px solid transparent;border-radius:10px}.po-thread-row.active{border-color:#bfdbfe;background:#fff}.po-thread{display:grid;gap:4px;width:100%;border:0;border-radius:10px;background:transparent;color:#334155;padding:9px 10px;text-align:left}.po-thread-row.active .po-thread{color:var(--po-text)}.po-thread span{color:#94a3b8;font-size:12px}.po-thread-delete{display:grid;width:28px;height:28px;place-items:center;border:0;border-radius:6px;background:transparent;color:#94a3b8;opacity:0}.po-thread-row:hover .po-thread-delete,.po-thread-row:focus-within .po-thread-delete{opacity:1}.po-thread-delete:hover{background:#fee2e2;color:#b91c1c}.po-thread-delete:disabled{cursor:not-allowed;opacity:.35}.po-trash-icon{position:relative;width:11px;height:12px;border:1.5px solid currentcolor;border-top:0;border-radius:0 0 2px 2px}.po-trash-icon:before{position:absolute;top:-4px;left:-2px;width:13px;border-top:1.5px solid currentcolor;content:""}.po-trash-icon:after{position:absolute;top:-6px;left:3px;width:4px;height:2px;border:1.5px solid currentcolor;border-bottom:0;border-radius:2px 2px 0 0;content:""}.po-conversation-error{margin:0;color:#b91c1c;font-size:12px}.po-chat{display:flex;min-width:0;min-height:0;flex-direction:column;background:linear-gradient(180deg,#fff,var(--po-panel));padding:22px 26px}.po-chat header,.po-trace header{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--po-soft-border);padding-bottom:14px}.po-chat header p,.po-chat header h2,.po-trace header h2{margin:0}.po-chat header p,.po-chat header span{color:var(--po-muted);font-size:12px}.po-chat header h2,.po-trace header h2{font-size:20px;letter-spacing:-.02em}.po-messages{display:grid;align-content:start;gap:14px;min-height:0;flex:1;overflow:auto;padding:18px 4px 18px 0}.po-message{display:grid;max-width:82%;gap:6px;border:1px solid var(--po-soft-border);border-radius:14px;padding:11px 13px;line-height:1.55;white-space:pre-wrap;word-break:break-word}.po-message b{font-size:12px;opacity:.78}.po-message.user{justify-self:end;border-color:var(--po-primary);background:var(--po-primary);color:#fff}.po-message.assistant{justify-self:start;background:var(--po-soft)}.po-message.streaming{border-color:#bfdbfe;background:#eff6ff}.po-message.answer-error{border-color:#fecaca;background:#fff7f7;color:#991b1b}.po-message.answer-error>strong{color:#7f1d1d}.po-stream-stopped{justify-self:start;color:var(--po-muted);font-size:12px}.po-ai-waiting{display:inline-flex;align-items:center;gap:9px;min-height:24px;color:#475569}.po-ai-spinner{width:16px;height:16px;flex:0 0 auto;border:2px solid #bfdbfe;border-top-color:var(--po-primary);border-radius:50%;animation:po-ai-spin .7s linear infinite}.po-typing-cursor{display:inline-block;width:2px;height:1em;margin-left:3px;background:var(--po-primary);vertical-align:-.12em;animation:po-typing-cursor .8s steps(1,end) infinite}@keyframes po-ai-spin{to{transform:rotate(360deg)}}@keyframes po-typing-cursor{50%{opacity:0}}.po-message code{border-radius:5px;background:#eaf0ff;color:var(--po-primary-dark);padding:1px 5px}.po-message pre{max-width:100%;margin:8px 0;overflow:auto;border:1px solid var(--po-border);border-radius:6px;background:#f8fafc;padding:10px 12px;white-space:pre}.po-message pre code{border-radius:0;background:transparent;color:#1f2937;padding:0}.po-message h2,.po-message h3,.po-message h4,.po-message p{margin:8px 0}.po-message table{width:100%;margin:12px 0;border-collapse:collapse;border-radius:10px;font-size:14px}.po-message th,.po-message td{border:1px solid var(--po-border);padding:8px 10px;text-align:left;vertical-align:top}.po-message th{background:#eef5ff;color:#334155;font-weight:800}.po-composer{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:end;gap:10px;border-top:1px solid var(--po-soft-border);padding-top:12px}.po-composer textarea{min-height:88px;resize:vertical;padding:10px}.po-composer button{min-height:44px;padding:0 16px}.po-composer .po-stop{display:grid;width:44px;height:44px;min-height:44px;place-items:center;border:1px solid #fecaca;background:#fff;color:#dc2626;padding:0}.po-stop span{width:12px;height:12px;border-radius:2px;background:currentcolor}.po-trace{display:flex;min-height:0;flex-direction:column;border-left:1px solid var(--po-soft-border);background:#fafbff}.po-trace header{padding:18px}.po-trace header button{width:32px;height:32px;border:1px solid #cbd5e1;border-radius:10px;background:#fff;color:#334155;font-size:20px;line-height:1}.po-trace section{display:grid;align-content:start;gap:12px;min-height:0;overflow:auto;padding:16px}.po-source-uploader{display:grid;gap:8px;border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-source-uploader p{margin:0;color:var(--po-muted);font-size:12px;line-height:1.5}.po-upload-button{display:inline-flex;justify-content:center;border:1px solid #bfdbfe;border-radius:10px;background:#eff6ff;color:var(--po-primary-dark);padding:8px 10px;font-weight:750;cursor:pointer}.po-upload-button input{display:none}.po-upload-status{color:#166534!important}.po-upload-empty{color:#92400e!important}.po-source-list{display:grid;gap:6px}.po-source-item{display:grid;gap:3px;border:1px solid #dbeafe;border-radius:10px;background:#f8fbff;padding:8px}.po-source-item strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.po-source-item span{color:var(--po-muted);font-size:12px}.po-composer textarea:disabled,.po-composer button:disabled{cursor:not-allowed;opacity:.62}.po-upload-error{color:#b91c1c!important}.po-step{border:1px solid var(--po-soft-border);border-radius:14px;background:#fff;padding:12px}.po-step.running{border-color:#bfdbfe;background:#eff6ff}.po-step.completed{border-color:#bbf7d0}.po-step.failed{border-color:#fecaca;background:#fff1f2}.po-step.cancelled{border-color:#cbd5e1;background:#f8fafc}.po-step summary{display:flex;justify-content:space-between;gap:8px;cursor:pointer}.po-step summary::marker{color:var(--po-muted)}.po-step pre{overflow:auto;margin:10px 0 0;border-radius:12px;background:#0f172a;color:#e2e8f0;padding:12px;font-size:12px;white-space:pre-wrap}@media(max-width:900px){.po-panel{inset:12px;grid-template-columns:1fr;overflow:auto}.po-sidebar,.po-trace{min-height:220px;border:0}.po-chat{min-height:520px}.po-message{max-width:94%}}@media(prefers-reduced-motion:reduce){.po-ai-spinner,.po-typing-cursor{animation:none}}
|
package/dist/pageops-sdk.es.js
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
var
|
|
2
|
-
var
|
|
3
|
-
var
|
|
4
|
-
class
|
|
1
|
+
var x = Object.defineProperty;
|
|
2
|
+
var k = (n, t, e) => t in n ? x(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
|
|
3
|
+
var a = (n, t, e) => k(n, typeof t != "symbol" ? t + "" : t, e);
|
|
4
|
+
class E {
|
|
5
5
|
constructor(t) {
|
|
6
6
|
this.options = t;
|
|
7
7
|
}
|
|
8
|
-
async createContext(t = ((
|
|
9
|
-
var
|
|
8
|
+
async createContext(t = ((i) => (i = ((e) => ((s) => (s = (e = this.options).getPageContext) == null ? void 0 : s.call(e))())()) != null ? i : {})()) {
|
|
9
|
+
var r, o, 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: (
|
|
16
|
+
url: (r = t.url) != null ? r : location.href,
|
|
17
17
|
title: (o = t.title) != null ? o : document.title,
|
|
18
|
-
menu_path: (
|
|
18
|
+
menu_path: (l = t.menuPath) != null ? l : [],
|
|
19
19
|
tenant_id: t.tenantId,
|
|
20
20
|
user_role: t.userRole,
|
|
21
21
|
build_version: t.buildVersion
|
|
@@ -31,6 +31,11 @@ class S {
|
|
|
31
31
|
body: JSON.stringify({ app_id: this.options.appId, context_session_id: t, title: e })
|
|
32
32
|
});
|
|
33
33
|
}
|
|
34
|
+
async deleteConversation(t) {
|
|
35
|
+
return this.request(`/conversations/${encodeURIComponent(t)}?app_id=${encodeURIComponent(this.options.appId)}`, {
|
|
36
|
+
method: "DELETE"
|
|
37
|
+
});
|
|
38
|
+
}
|
|
34
39
|
async listMessages(t) {
|
|
35
40
|
return (await this.request(`/conversations/${encodeURIComponent(t)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages;
|
|
36
41
|
}
|
|
@@ -41,116 +46,169 @@ class S {
|
|
|
41
46
|
const e = new FormData();
|
|
42
47
|
return e.append("file", t), this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`, { method: "POST", body: e, headers: {} });
|
|
43
48
|
}
|
|
44
|
-
streamQuestion(t, e) {
|
|
49
|
+
streamQuestion(t, e, s) {
|
|
45
50
|
return fetch(`${this.base()}/question/stream`, {
|
|
46
51
|
method: "POST",
|
|
47
52
|
headers: { "content-type": "application/json" },
|
|
48
|
-
body: JSON.stringify({ app_id: this.options.appId, thread_id: t, question: e })
|
|
53
|
+
body: JSON.stringify({ app_id: this.options.appId, thread_id: t, question: e }),
|
|
54
|
+
signal: s
|
|
49
55
|
});
|
|
50
56
|
}
|
|
51
57
|
async request(t, e) {
|
|
52
|
-
var o,
|
|
53
|
-
const s = (e == null ? void 0 : e.body) instanceof FormData ? e.headers : { "content-type": "application/json", ...(o = e == null ? void 0 : e.headers) != null ? o : {} },
|
|
54
|
-
if (
|
|
55
|
-
|
|
58
|
+
var o, l;
|
|
59
|
+
const s = (e == null ? void 0 : e.body) instanceof FormData ? e.headers : { "content-type": "application/json", ...(o = e == null ? void 0 : e.headers) != null ? o : {} }, i = await fetch(`${this.base()}${t}`, { ...e, headers: s });
|
|
60
|
+
if (i.status === 204) return;
|
|
61
|
+
const r = await i.json();
|
|
62
|
+
if (!i.ok) throw new Error((l = r.message) != null ? l : "PageOps 请求失败");
|
|
63
|
+
return r;
|
|
56
64
|
}
|
|
57
65
|
base() {
|
|
58
66
|
const t = this.options.apiBase.replace(/\/$/, "");
|
|
59
67
|
return t.endsWith("/api") ? t : `${t}/api`;
|
|
60
68
|
}
|
|
61
69
|
}
|
|
62
|
-
function
|
|
63
|
-
|
|
70
|
+
async function I(n, t) {
|
|
71
|
+
const e = await n.json().catch(() => null);
|
|
72
|
+
return typeof (e == null ? void 0 : e.message) == "string" && e.message.trim() ? e.message : t;
|
|
73
|
+
}
|
|
74
|
+
function T(n) {
|
|
75
|
+
return n.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
64
76
|
}
|
|
65
|
-
function
|
|
66
|
-
return
|
|
77
|
+
function v(n) {
|
|
78
|
+
return T(n).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
|
|
67
79
|
}
|
|
68
|
-
function
|
|
69
|
-
const e =
|
|
80
|
+
function R(n, t) {
|
|
81
|
+
const e = n[t], s = n[t + 1];
|
|
70
82
|
if (!(e != null && e.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
|
|
71
|
-
const
|
|
72
|
-
let
|
|
73
|
-
for (;
|
|
74
|
-
|
|
75
|
-
const o = (
|
|
76
|
-
return { html: `<table><thead><tr>${
|
|
83
|
+
const i = [];
|
|
84
|
+
let r = t;
|
|
85
|
+
for (; r < n.length && n[r].includes("|") && n[r].trim(); )
|
|
86
|
+
i.push(n[r]), r += 1;
|
|
87
|
+
const o = (d) => d.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((f) => v(f.trim())), l = o(i[0]).map((d) => `<th>${d}</th>`).join(""), p = i.slice(2).map((d) => `<tr>${o(d).map((f) => `<td>${f}</td>`).join("")}</tr>`).join("");
|
|
88
|
+
return { html: `<table><thead><tr>${l}</tr></thead><tbody>${p}</tbody></table>`, next: r };
|
|
77
89
|
}
|
|
78
|
-
function
|
|
79
|
-
const t =
|
|
90
|
+
function w(n) {
|
|
91
|
+
const t = n.split(`
|
|
80
92
|
`), e = [];
|
|
81
93
|
for (let s = 0; s < t.length; s += 1) {
|
|
82
|
-
const
|
|
83
|
-
if (
|
|
94
|
+
const i = t[s];
|
|
95
|
+
if (i.trim().startsWith("```")) {
|
|
84
96
|
const o = [];
|
|
85
97
|
for (s += 1; s < t.length && !t[s].trim().startsWith("```"); )
|
|
86
98
|
o.push(t[s]), s += 1;
|
|
87
|
-
e.push(`<pre><code>${
|
|
99
|
+
e.push(`<pre><code>${T(o.join(`
|
|
88
100
|
`))}</code></pre>`);
|
|
89
101
|
continue;
|
|
90
102
|
}
|
|
91
|
-
const
|
|
92
|
-
if (
|
|
93
|
-
e.push(
|
|
103
|
+
const r = R(t, s);
|
|
104
|
+
if (r) {
|
|
105
|
+
e.push(r.html), s = r.next - 1;
|
|
94
106
|
continue;
|
|
95
107
|
}
|
|
96
|
-
|
|
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>");
|
|
97
109
|
}
|
|
98
110
|
return e.join("");
|
|
99
111
|
}
|
|
100
|
-
async function U(
|
|
101
|
-
var
|
|
102
|
-
const e =
|
|
103
|
-
let
|
|
112
|
+
async function U(n, t) {
|
|
113
|
+
var r;
|
|
114
|
+
const e = n.getReader(), s = new TextDecoder();
|
|
115
|
+
let i = "";
|
|
104
116
|
for (; ; ) {
|
|
105
|
-
const { done:
|
|
106
|
-
if (
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
`);
|
|
111
|
-
n = (i = m.pop()) != null ? i : "";
|
|
112
|
-
for (const y of m) {
|
|
113
|
-
const p = (o = y.match(/^event: (.+)$/m)) == null ? void 0 : o[1], l = (a = y.match(/^data: (.+)$/m)) == null ? void 0 : a[1];
|
|
114
|
-
p && l && t(p, JSON.parse(l));
|
|
117
|
+
const { done: o, value: l } = await e.read();
|
|
118
|
+
if (o) {
|
|
119
|
+
i += s.decode();
|
|
120
|
+
break;
|
|
115
121
|
}
|
|
122
|
+
i += s.decode(l, { stream: !0 });
|
|
123
|
+
const p = i.split(/\r?\n\r?\n/);
|
|
124
|
+
i = (r = p.pop()) != null ? r : "";
|
|
125
|
+
for (const d of p) C(d, t);
|
|
126
|
+
}
|
|
127
|
+
i.trim() && C(i, t);
|
|
128
|
+
}
|
|
129
|
+
function C(n, t) {
|
|
130
|
+
var i, r;
|
|
131
|
+
const e = (i = n.match(/^event:\s*(.+)$/m)) == null ? void 0 : i[1], s = (r = n.match(/^data:\s*(.+)$/m)) == null ? void 0 : r[1];
|
|
132
|
+
e && s && t(e, JSON.parse(s));
|
|
133
|
+
}
|
|
134
|
+
class q {
|
|
135
|
+
constructor(t, e = 16) {
|
|
136
|
+
a(this, "queue", []);
|
|
137
|
+
a(this, "timer", null);
|
|
138
|
+
a(this, "drainWaiters", []);
|
|
139
|
+
this.onChunk = t, this.interval = e;
|
|
140
|
+
}
|
|
141
|
+
enqueue(t) {
|
|
142
|
+
this.queue.push(...Array.from(t)), this.timer || this.tick();
|
|
143
|
+
}
|
|
144
|
+
async drain() {
|
|
145
|
+
!this.timer && !this.queue.length || await new Promise((t) => this.drainWaiters.push(t));
|
|
146
|
+
}
|
|
147
|
+
clear() {
|
|
148
|
+
this.timer && clearTimeout(this.timer), this.timer = null, this.queue = [], this.resolveDrainWaiters();
|
|
149
|
+
}
|
|
150
|
+
tick() {
|
|
151
|
+
const t = Math.max(1, Math.ceil(this.queue.length / 90)), e = this.queue.splice(0, t).join("");
|
|
152
|
+
if (e && this.onChunk(e), !this.queue.length) {
|
|
153
|
+
this.timer = null, this.resolveDrainWaiters();
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
this.timer = setTimeout(() => this.tick(), this.interval);
|
|
157
|
+
}
|
|
158
|
+
resolveDrainWaiters() {
|
|
159
|
+
for (const t of this.drainWaiters.splice(0)) t();
|
|
116
160
|
}
|
|
117
161
|
}
|
|
118
|
-
class
|
|
162
|
+
class F {
|
|
119
163
|
constructor() {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
164
|
+
a(this, "client", null);
|
|
165
|
+
a(this, "options", null);
|
|
166
|
+
a(this, "root", null);
|
|
167
|
+
a(this, "panel", null);
|
|
168
|
+
a(this, "context", null);
|
|
169
|
+
a(this, "contextKey", "");
|
|
170
|
+
a(this, "selectedPageKey", "");
|
|
171
|
+
a(this, "currentThread", null);
|
|
172
|
+
a(this, "conversations", []);
|
|
173
|
+
a(this, "messages", []);
|
|
174
|
+
a(this, "steps", []);
|
|
175
|
+
a(this, "sourceSnapshots", []);
|
|
176
|
+
a(this, "sourceUploadStatus", "");
|
|
177
|
+
a(this, "sourceUploadError", "");
|
|
178
|
+
a(this, "sourceUploading", !1);
|
|
179
|
+
a(this, "sourceRefreshTimer", null);
|
|
180
|
+
a(this, "streaming", "");
|
|
181
|
+
a(this, "asking", !1);
|
|
182
|
+
a(this, "waitingForFirstContent", !1);
|
|
183
|
+
a(this, "abortController", null);
|
|
184
|
+
a(this, "activeRunId", 0);
|
|
185
|
+
a(this, "stoppedRunId", -1);
|
|
186
|
+
a(this, "answerStopped", !1);
|
|
187
|
+
a(this, "answerError", "");
|
|
188
|
+
a(this, "conversationError", "");
|
|
189
|
+
a(this, "deletingThreadId", "");
|
|
190
|
+
a(this, "streamFailure", "");
|
|
191
|
+
a(this, "streamDone", null);
|
|
192
|
+
a(this, "typewriter", new q((t) => {
|
|
193
|
+
this.streaming += t, this.updateStreamingMessage();
|
|
194
|
+
}));
|
|
137
195
|
}
|
|
138
196
|
mount(t) {
|
|
139
197
|
var e;
|
|
140
|
-
this.unmount(), this.options = t, this.client = new
|
|
198
|
+
this.unmount(), this.options = t, this.client = new E(t), this.root = document.createElement("div"), this.root.className = "pageops-sdk", ((e = t.container) != null ? e : document.body).appendChild(this.root), this.renderClosed();
|
|
141
199
|
}
|
|
142
200
|
unmount() {
|
|
143
201
|
var t;
|
|
144
|
-
this.stopSourceRefresh(), (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
|
|
202
|
+
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;
|
|
145
203
|
}
|
|
146
204
|
open() {
|
|
147
205
|
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());
|
|
148
206
|
}
|
|
149
207
|
close() {
|
|
150
|
-
this.stopSourceRefresh(), this.renderClosed();
|
|
208
|
+
this.stopSourceRefresh(), this.cancelActiveAnswer(!1), this.renderClosed();
|
|
151
209
|
}
|
|
152
210
|
updateContext(t) {
|
|
153
|
-
this.options && (this.options = { ...this.options, ...t }, this.client = new
|
|
211
|
+
this.options && (this.options = { ...this.options, ...t }, this.client = new E(this.options), this.context = null, this.contextKey = "");
|
|
154
212
|
}
|
|
155
213
|
renderClosed() {
|
|
156
214
|
var t;
|
|
@@ -166,12 +224,12 @@ class C {
|
|
|
166
224
|
return (s = (e = (t = this.options) == null ? void 0 : t.getPageContext) == null ? void 0 : e.call(t)) != null ? s : {};
|
|
167
225
|
}
|
|
168
226
|
getPageContextKey(t) {
|
|
169
|
-
var e, s,
|
|
227
|
+
var e, s, i, r;
|
|
170
228
|
return JSON.stringify([
|
|
171
229
|
(e = t.route) != null ? e : "",
|
|
172
230
|
(s = t.url) != null ? s : location.href,
|
|
173
|
-
(
|
|
174
|
-
(
|
|
231
|
+
(i = t.title) != null ? i : document.title,
|
|
232
|
+
(r = t.menuPath) != null ? r : []
|
|
175
233
|
]);
|
|
176
234
|
}
|
|
177
235
|
async loadSources() {
|
|
@@ -191,10 +249,27 @@ class C {
|
|
|
191
249
|
var s;
|
|
192
250
|
if (!this.client) return;
|
|
193
251
|
const t = await this.ensureContext(), e = (s = t.menu_path) != null && s.length ? t.menu_path.join(" / ") : t.route || document.title || "新的问答";
|
|
194
|
-
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.renderPanel();
|
|
252
|
+
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();
|
|
195
253
|
}
|
|
196
254
|
async selectThread(t) {
|
|
197
|
-
this.client && (this.currentThread = t, this.selectedPageKey = this.getPageContextKey(this.getPageContext()), this.messages = await this.client.listMessages(t.id), this.steps = [], this.streaming = "", this.renderPanel());
|
|
255
|
+
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());
|
|
256
|
+
}
|
|
257
|
+
async deleteConversation(t) {
|
|
258
|
+
var e;
|
|
259
|
+
if (!(!this.client || this.asking || this.deletingThreadId) && window.confirm(`确定删除会话“${t.title}”吗?此操作无法撤销。`)) {
|
|
260
|
+
this.deletingThreadId = t.id, this.conversationError = "", this.renderPanel();
|
|
261
|
+
try {
|
|
262
|
+
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) {
|
|
263
|
+
this.currentThread = null, this.messages = [], this.steps = [], this.streaming = "", this.answerError = "", this.answerStopped = !1;
|
|
264
|
+
const s = this.conversations[0];
|
|
265
|
+
s && await this.selectThread(s);
|
|
266
|
+
}
|
|
267
|
+
} catch (s) {
|
|
268
|
+
this.conversationError = s instanceof Error ? s.message : "删除问答会话失败";
|
|
269
|
+
} finally {
|
|
270
|
+
this.deletingThreadId = "", this.renderPanel();
|
|
271
|
+
}
|
|
272
|
+
}
|
|
198
273
|
}
|
|
199
274
|
async uploadSource(t) {
|
|
200
275
|
if (this.client) {
|
|
@@ -209,26 +284,74 @@ class C {
|
|
|
209
284
|
}
|
|
210
285
|
}
|
|
211
286
|
async ask(t) {
|
|
212
|
-
|
|
213
|
-
if (!this.client) return;
|
|
287
|
+
if (!this.client || this.asking) return;
|
|
214
288
|
const e = this.questionUnavailableReason();
|
|
215
289
|
if (e) {
|
|
216
290
|
this.sourceUploadError = e, this.renderPanel();
|
|
217
291
|
return;
|
|
218
292
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
this.
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
293
|
+
this.resetAnswerState();
|
|
294
|
+
const s = ++this.activeRunId, i = new AbortController();
|
|
295
|
+
this.abortController = i, this.stoppedRunId = -1, this.asking = !0, this.waitingForFirstContent = !0, this.renderPanel();
|
|
296
|
+
try {
|
|
297
|
+
const r = this.getPageContextKey(this.getPageContext());
|
|
298
|
+
if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== r && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) throw new Error("无法创建问答会话,请稍后重试。");
|
|
299
|
+
this.messages.push({ id: `local-${Date.now()}`, role: "user", content: t, metadata_json: {} }), this.steps = [], this.renderPanel();
|
|
300
|
+
const o = await this.client.streamQuestion(this.currentThread.id, t, i.signal);
|
|
301
|
+
if (!o.ok) throw new Error(await I(o, "服务暂时无法回答,请稍后重试。"));
|
|
302
|
+
if (!o.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
|
|
303
|
+
if (await U(o.body, (l, p) => this.handleStreamEvent(l, p)), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
304
|
+
if (this.streamFailure) throw new Error(this.streamFailure);
|
|
305
|
+
if (!this.streamDone) throw new Error("服务响应意外中断,请稍后重试。");
|
|
306
|
+
if (await this.typewriter.drain(), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
|
|
307
|
+
await this.selectThread(this.currentThread);
|
|
308
|
+
} catch (r) {
|
|
309
|
+
if (s !== this.activeRunId) return;
|
|
310
|
+
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 } }));
|
|
311
|
+
} finally {
|
|
312
|
+
if (s !== this.activeRunId) return;
|
|
313
|
+
this.asking = !1, this.waitingForFirstContent = !1, this.abortController === i && (this.abortController = null), this.renderPanel();
|
|
226
314
|
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
315
|
+
}
|
|
316
|
+
cancelActiveAnswer(t) {
|
|
317
|
+
var e;
|
|
318
|
+
if (!(!this.asking && !this.abortController)) {
|
|
319
|
+
if (t) {
|
|
320
|
+
this.stoppedRunId = this.activeRunId, this.answerStopped = !0;
|
|
321
|
+
const s = this.steps.map((i) => i.status === "running" ? { ...i, status: "cancelled" } : i);
|
|
322
|
+
this.steps = s.some((i) => i.status === "cancelled") ? s : [...s, { id: "stopped", title: "已停止", status: "cancelled" }];
|
|
323
|
+
} else
|
|
324
|
+
this.activeRunId += 1, this.asking = !1;
|
|
325
|
+
this.typewriter.clear(), this.waitingForFirstContent = !1, (e = this.abortController) == null || e.abort(), this.abortController = null, t && this.renderPanel();
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
handleStreamEvent(t, e) {
|
|
329
|
+
var s, i;
|
|
330
|
+
if (t === "step") {
|
|
331
|
+
this.upsertStep(e), this.renderPanel();
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
if (t === "delta") {
|
|
335
|
+
const r = String((s = e.content) != null ? s : "");
|
|
336
|
+
if (!r) return;
|
|
337
|
+
this.waitingForFirstContent = !1, this.typewriter.enqueue(r);
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
t === "done" && (this.streamDone = e), t === "error" && (this.streamFailure = String((i = e.message) != null ? i : "服务异常,请稍后重试。"));
|
|
341
|
+
}
|
|
342
|
+
updateStreamingMessage() {
|
|
343
|
+
var s, i;
|
|
344
|
+
const t = (s = this.panel) == null ? void 0 : s.querySelector("[data-streaming-content]");
|
|
345
|
+
if (!t) {
|
|
346
|
+
this.renderPanel();
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
t.innerHTML = w(this.streaming);
|
|
350
|
+
const e = (i = this.panel) == null ? void 0 : i.querySelector(".po-messages");
|
|
351
|
+
e && (e.scrollTop = e.scrollHeight);
|
|
352
|
+
}
|
|
353
|
+
resetAnswerState() {
|
|
354
|
+
this.typewriter.clear(), this.asking = !1, this.waitingForFirstContent = !1, this.answerError = "", this.answerStopped = !1, this.streamFailure = "", this.streamDone = null, this.streaming = "";
|
|
232
355
|
}
|
|
233
356
|
upsertStep(t) {
|
|
234
357
|
const e = this.steps.findIndex((s) => s.id === t.id);
|
|
@@ -252,30 +375,41 @@ class C {
|
|
|
252
375
|
}
|
|
253
376
|
renderPanel() {
|
|
254
377
|
if (!this.panel) return;
|
|
255
|
-
const t = this.questionUnavailableReason(), e = t || "请输入页面分析问题,Enter 发送,Shift + Enter 换行";
|
|
256
|
-
this.panel.innerHTML = `
|
|
378
|
+
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>';
|
|
379
|
+
if (this.panel.innerHTML = `
|
|
257
380
|
<aside class="po-sidebar">
|
|
258
381
|
<div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
|
|
259
|
-
<button class="po-new" data-action="new">+ 新建问答</button>
|
|
382
|
+
<button class="po-new" data-action="new" ${this.asking ? "disabled" : ""}>+ 新建问答</button>
|
|
260
383
|
<input class="po-search" placeholder="搜索问答" />
|
|
261
|
-
|
|
262
|
-
|
|
384
|
+
${this.conversationError ? `<p class="po-conversation-error" role="alert">${h(this.conversationError)}</p>` : ""}
|
|
385
|
+
<div class="po-thread-list">${this.conversations.map((r) => {
|
|
386
|
+
var o;
|
|
263
387
|
return `
|
|
264
|
-
<
|
|
265
|
-
<
|
|
266
|
-
|
|
388
|
+
<div class="po-thread-row ${r.id === ((o = this.currentThread) == null ? void 0 : o.id) ? "active" : ""}">
|
|
389
|
+
<button class="po-thread" data-thread="${h(r.id)}" ${this.asking ? "disabled" : ""}>
|
|
390
|
+
<strong>${h(r.title)}</strong><span>${P(r.created_at)}</span>
|
|
391
|
+
</button>
|
|
392
|
+
<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>
|
|
393
|
+
</div>`;
|
|
267
394
|
}).join("")}</div>
|
|
268
395
|
</aside>
|
|
269
396
|
<main class="po-chat">
|
|
270
|
-
<header><div><p>问数回答</p><h2>${this.currentThread ?
|
|
397
|
+
<header><div><p>问数回答</p><h2>${this.currentThread ? h(this.currentThread.title) : "未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
|
|
271
398
|
<section class="po-messages">
|
|
272
|
-
${this.messages.map((
|
|
273
|
-
${this.
|
|
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
|
+
${this.renderAnswerState()}
|
|
274
401
|
</section>
|
|
275
|
-
<form class="po-composer"><textarea ${
|
|
402
|
+
<form class="po-composer"><textarea ${s ? "disabled" : ""} placeholder="${h(e)}"></textarea>${i}</form>
|
|
276
403
|
</main>
|
|
277
404
|
<aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
|
|
278
|
-
`, this.bindPanelEvents()
|
|
405
|
+
`, this.bindPanelEvents(), this.asking) {
|
|
406
|
+
const r = this.panel.querySelector(".po-messages");
|
|
407
|
+
r && (r.scrollTop = r.scrollHeight);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
renderAnswerState() {
|
|
411
|
+
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>${w(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>' : "";
|
|
412
|
+
return `${t}${e}${i}${s}`;
|
|
279
413
|
}
|
|
280
414
|
renderSourceUploader() {
|
|
281
415
|
return `
|
|
@@ -286,61 +420,70 @@ class C {
|
|
|
286
420
|
<span>${this.sourceUploading ? "上传中..." : "选择代码包"}</span>
|
|
287
421
|
<input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading ? "disabled" : ""} />
|
|
288
422
|
</label>
|
|
289
|
-
${this.sourceUploadStatus ? `<p class="po-upload-status">${
|
|
423
|
+
${this.sourceUploadStatus ? `<p class="po-upload-status">${h(this.sourceUploadStatus)}</p>` : ""}
|
|
290
424
|
${this.sourceSnapshots.length ? `<div class="po-source-list">${this.sourceSnapshots.map((t) => this.renderSourceItem(t)).join("")}</div>` : '<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
|
|
291
|
-
${this.sourceUploadError ? `<p class="po-upload-error">${
|
|
425
|
+
${this.sourceUploadError ? `<p class="po-upload-error">${h(this.sourceUploadError)}</p>` : ""}
|
|
292
426
|
</div>
|
|
293
427
|
`;
|
|
294
428
|
}
|
|
295
429
|
renderSourceItem(t) {
|
|
296
|
-
var
|
|
297
|
-
const e = t.filename || "未命名代码包", s = t.created_at ?
|
|
298
|
-
return `<article class="po-source-item"><strong>${
|
|
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), r = String((p = (l = t.metadata) == null ? void 0 : l.analysis_status) != null ? p : "unknown"), o = (d = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[r]) != null ? d : "项目记忆状态未知";
|
|
432
|
+
return `<article class="po-source-item"><strong>${h(e)}</strong><span>${h(s)} · ${h(i)}</span><span>${h(o)}</span></article>`;
|
|
299
433
|
}
|
|
300
434
|
renderSteps() {
|
|
301
435
|
return (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", details: { message: "发送消息后展示执行过程。" } }]).map((e) => {
|
|
302
436
|
var s;
|
|
303
|
-
return `<details class="po-step ${e.status}" ${e.status === "running" || e.status === "failed" ? "open" : ""}><summary><strong>${
|
|
437
|
+
return `<details class="po-step ${e.status}" ${e.status === "running" || e.status === "failed" ? "open" : ""}><summary><strong>${h(e.title)}</strong><span>${A(e.status)}</span></summary><pre>${h(JSON.stringify((s = e.details) != null ? s : {}, null, 2))}</pre></details>`;
|
|
304
438
|
}).join("");
|
|
305
439
|
}
|
|
306
440
|
bindPanelEvents() {
|
|
307
|
-
var t, e, s,
|
|
308
|
-
(e = (t = this.panel) == null ? void 0 : t.querySelector('[data-action="new"]')) == null || e.addEventListener("click", () => void this.newConversation()), (
|
|
309
|
-
var
|
|
310
|
-
const
|
|
311
|
-
|
|
312
|
-
}), (
|
|
313
|
-
|
|
314
|
-
const
|
|
315
|
-
|
|
441
|
+
var t, e, s, i, r, o, 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()), (o = (r = this.panel) == null ? void 0 : r.querySelector('[data-action="stop-answer"]')) == null || o.addEventListener("click", () => this.cancelActiveAnswer(!0)), (p = (l = this.panel) == null ? void 0 : l.querySelector('[data-action="upload-source"]')) == null || p.addEventListener("change", (g) => {
|
|
443
|
+
var u;
|
|
444
|
+
const c = (u = g.target.files) == null ? void 0 : u[0];
|
|
445
|
+
c && this.uploadSource(c);
|
|
446
|
+
}), (d = this.panel) == null || d.querySelectorAll("[data-thread]").forEach((g) => {
|
|
447
|
+
g.addEventListener("click", () => {
|
|
448
|
+
const c = this.conversations.find((u) => u.id === g.dataset.thread);
|
|
449
|
+
c && this.selectThread(c);
|
|
316
450
|
});
|
|
317
|
-
}), (
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
451
|
+
}), (f = this.panel) == null || f.querySelectorAll("[data-delete-thread]").forEach((g) => {
|
|
452
|
+
g.addEventListener("click", (c) => {
|
|
453
|
+
c.stopPropagation();
|
|
454
|
+
const u = this.conversations.find((m) => m.id === g.dataset.deleteThread);
|
|
455
|
+
u && this.deleteConversation(u);
|
|
456
|
+
});
|
|
457
|
+
}), (S = (y = this.panel) == null ? void 0 : y.querySelector("form")) == null || S.addEventListener("submit", (g) => {
|
|
458
|
+
var m;
|
|
459
|
+
g.preventDefault();
|
|
460
|
+
const c = (m = this.panel) == null ? void 0 : m.querySelector("textarea"), u = c == null ? void 0 : c.value.trim();
|
|
461
|
+
u && (c.value = "", this.ask(u));
|
|
462
|
+
}), ($ = (b = this.panel) == null ? void 0 : b.querySelector("textarea")) == null || $.addEventListener("keydown", (g) => {
|
|
463
|
+
var u, m;
|
|
464
|
+
const c = g;
|
|
465
|
+
c.key === "Enter" && !c.shiftKey && (c.preventDefault(), (m = (u = this.panel) == null ? void 0 : u.querySelector("form")) == null || m.requestSubmit());
|
|
326
466
|
});
|
|
327
467
|
}
|
|
328
468
|
}
|
|
329
|
-
function
|
|
330
|
-
return
|
|
469
|
+
function h(n) {
|
|
470
|
+
return n.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
331
471
|
}
|
|
332
|
-
function
|
|
333
|
-
return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(
|
|
472
|
+
function P(n) {
|
|
473
|
+
return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(n));
|
|
334
474
|
}
|
|
335
|
-
function
|
|
336
|
-
if (!
|
|
475
|
+
function _(n) {
|
|
476
|
+
if (!n) return "0 B";
|
|
337
477
|
const t = ["B", "KB", "MB", "GB"];
|
|
338
|
-
let e =
|
|
478
|
+
let e = n, s = 0;
|
|
339
479
|
for (; e >= 1024 && s < t.length - 1; )
|
|
340
480
|
e /= 1024, s += 1;
|
|
341
481
|
return `${e >= 10 || s === 0 ? e.toFixed(0) : e.toFixed(1)} ${t[s]}`;
|
|
342
482
|
}
|
|
343
|
-
|
|
483
|
+
function A(n) {
|
|
484
|
+
return { pending: "等待中", running: "执行中", completed: "已完成", failed: "失败", cancelled: "已停止" }[n];
|
|
485
|
+
}
|
|
486
|
+
const O = new F();
|
|
344
487
|
export {
|
|
345
|
-
|
|
488
|
+
O as PageOpsSDK
|
|
346
489
|
};
|
package/dist/pageops-sdk.umd.cjs
CHANGED
|
@@ -1,27 +1,29 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
`),
|
|
3
|
-
`))}</code></pre>`);continue}const i=x(e,s);if(i){t.push(i.html),s=i.next-1;continue}n.startsWith("### ")?t.push(`<h4>${v(n.slice(4))}</h4>`):n.startsWith("## ")?t.push(`<h3>${v(n.slice(3))}</h3>`):n.startsWith("# ")?t.push(`<h2>${v(n.slice(2))}</h2>`):n.startsWith("- ")?t.push(`<li>${v(n.slice(2))}</li>`):n.trim()?t.push(`<p>${v(n)}</p>`):t.push("<br>")}return t.join("")}async function T(o,e){var i,r,a;const t=o.getReader(),s=new TextDecoder;let n="";for(;;){const{done:g,value:d}=await t.read();if(g)break;n+=s.decode(d,{stream:!0});const y=n.split(`
|
|
4
|
-
|
|
5
|
-
`);n=(i=y.pop())!=null?i:"";for(const $ of y){const m=(r=$.match(/^event: (.+)$/m))==null?void 0:r[1],l=(a=$.match(/^data: (.+)$/m))==null?void 0:a[1];m&&l&&e(m,JSON.parse(l))}}}class U{constructor(){c(this,"client",null);c(this,"options",null);c(this,"root",null);c(this,"panel",null);c(this,"context",null);c(this,"contextKey","");c(this,"selectedPageKey","");c(this,"currentThread",null);c(this,"conversations",[]);c(this,"messages",[]);c(this,"steps",[]);c(this,"sourceSnapshots",[]);c(this,"sourceUploadStatus","");c(this,"sourceUploadError","");c(this,"sourceUploading",!1);c(this,"sourceRefreshTimer",null);c(this,"streaming","")}mount(e){var t;this.unmount(),this.options=e,this.client=new h(e),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(),(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.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceUploading=!1,this.streaming=""}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.renderClosed()}updateContext(e){this.options&&(this.options={...this.options,...e},this.client=new h(this.options),this.context=null,this.contextKey="")}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:{}}getPageContextKey(e){var t,s,n,i;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(n=e.title)!=null?n:document.title,(i=e.menuPath)!=null?i:[]])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceUploadError=""}catch(e){this.sourceUploadError=e instanceof Error?e.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 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.renderPanel()}async selectThread(e){this.client&&(this.currentThread=e,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(e.id),this.steps=[],this.streaming="",this.renderPanel())}async uploadSource(e){if(this.client){this.sourceUploading=!0,this.sourceUploadStatus="上传中...",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(e),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(e){var i;if(!this.client)return;const t=this.questionUnavailableReason();if(t){this.sourceUploadError=t,this.renderPanel();return}const s=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==s&&(this.currentThread=null),this.currentThread||await this.newConversation(),!this.currentThread)return;this.messages.push({id:`local-${Date.now()}`,role:"user",content:e,metadata_json:{}}),this.steps=[],this.streaming="",this.renderPanel();const n=await this.client.streamQuestion(this.currentThread.id,e);if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(String((i=r.message)!=null?i:"PageOps 流式问答失败"))}if(!n.body)throw new Error("PageOps 流式问答失败");await T(n.body,(r,a)=>{var g;r==="step"&&this.upsertStep(a),r==="delta"&&(this.streaming+=String((g=a.content)!=null?g:"")),r==="done"&&this.selectThread(this.currentThread),r==="error"&&this.upsertStep({id:"error",title:"执行失败",status:"failed",details:a}),this.renderPanel()})}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)}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.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 e=this.questionUnavailableReason(),t=e||"请输入页面分析问题,Enter 发送,Shift + Enter 换行";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 n=(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 r,o,h;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:t.route,url:(r=t.url)!=null?r:location.href,title:(o=t.title)!=null?o:document.title,menu_path:(h=t.menuPath)!=null?h:[],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 o,h;const s=(e==null?void 0:e.body)instanceof FormData?e.headers:{"content-type":"application/json",...(o=e==null?void 0:e.headers)!=null?o:{}},i=await fetch(`${this.base()}${t}`,{...e,headers:s});if(i.status===204)return;const r=await i.json();if(!i.ok)throw new Error((h=r.message)!=null?h:"PageOps 请求失败");return r}base(){const t=this.options.apiBase.replace(/\/$/,"");return t.endsWith("/api")?t:`${t}/api`}}async function w(a,t){const e=await a.json().catch(()=>null);return typeof(e==null?void 0:e.message)=="string"&&e.message.trim()?e.message:t}function $(a){return a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function y(a){return $(a).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function I(a,t){const e=a[t],s=a[t+1];if(!(e!=null&&e.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const i=[];let r=t;for(;r<a.length&&a[r].includes("|")&&a[r].trim();)i.push(a[r]),r+=1;const o=u=>u.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(S=>y(S.trim())),h=o(i[0]).map(u=>`<th>${u}</th>`).join(""),f=i.slice(2).map(u=>`<tr>${o(u).map(S=>`<td>${S}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${h}</tr></thead><tbody>${f}</tbody></table>`,next:r}}function b(a){const t=a.split(`
|
|
2
|
+
`),e=[];for(let s=0;s<t.length;s+=1){const i=t[s];if(i.trim().startsWith("```")){const o=[];for(s+=1;s<t.length&&!t[s].trim().startsWith("```");)o.push(t[s]),s+=1;e.push(`<pre><code>${$(o.join(`
|
|
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=`
|
|
6
4
|
<aside class="po-sidebar">
|
|
7
5
|
<div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
|
|
8
|
-
<button class="po-new" data-action="new">+ 新建问答</button>
|
|
6
|
+
<button class="po-new" data-action="new" ${this.asking?"disabled":""}>+ 新建问答</button>
|
|
9
7
|
<input class="po-search" placeholder="搜索问答" />
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
8
|
+
${this.conversationError?`<p class="po-conversation-error" role="alert">${l(this.conversationError)}</p>`:""}
|
|
9
|
+
<div class="po-thread-list">${this.conversations.map(r=>{var o;return`
|
|
10
|
+
<div class="po-thread-row ${r.id===((o=this.currentThread)==null?void 0:o.id)?"active":""}">
|
|
11
|
+
<button class="po-thread" data-thread="${l(r.id)}" ${this.asking?"disabled":""}>
|
|
12
|
+
<strong>${l(r.title)}</strong><span>${P(r.created_at)}</span>
|
|
13
|
+
</button>
|
|
14
|
+
<button class="po-thread-delete" type="button" data-delete-thread="${l(r.id)}" aria-label="删除会话:${l(r.title)}" title="删除会话" ${this.asking||this.deletingThreadId===r.id?"disabled":""}><span class="po-trash-icon" aria-hidden="true"></span></button>
|
|
15
|
+
</div>`}).join("")}</div>
|
|
14
16
|
</aside>
|
|
15
17
|
<main class="po-chat">
|
|
16
|
-
<header><div><p>问数回答</p><h2>${this.currentThread?
|
|
18
|
+
<header><div><p>问数回答</p><h2>${this.currentThread?l(this.currentThread.title):"未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
|
|
17
19
|
<section class="po-messages">
|
|
18
|
-
${this.messages.map(
|
|
19
|
-
${this.
|
|
20
|
+
${this.messages.map(r=>`<article class="po-message ${r.role}"><b>${r.role==="user"?"你":"PageOps 分析"}</b><div>${r.role==="assistant"?b(r.content):l(r.content)}</div></article>`).join("")}
|
|
21
|
+
${this.renderAnswerState()}
|
|
20
22
|
</section>
|
|
21
|
-
<form class="po-composer"><textarea ${
|
|
23
|
+
<form class="po-composer"><textarea ${s?"disabled":""} placeholder="${l(e)}"></textarea>${i}</form>
|
|
22
24
|
</main>
|
|
23
25
|
<aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
|
|
24
|
-
`,this.bindPanelEvents()}renderSourceUploader(){return`
|
|
26
|
+
`,this.bindPanelEvents(),this.asking){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>${l(this.answerError)}</div></article>`:"",i=this.answerStopped?'<div class="po-stream-stopped" role="status">已停止输出</div>':"";return`${t}${e}${i}${s}`}renderSourceUploader(){return`
|
|
25
27
|
<div class="po-source-uploader">
|
|
26
28
|
<strong>源码包</strong>
|
|
27
29
|
<p>上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
|
|
@@ -29,8 +31,8 @@
|
|
|
29
31
|
<span>${this.sourceUploading?"上传中...":"选择代码包"}</span>
|
|
30
32
|
<input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
|
|
31
33
|
</label>
|
|
32
|
-
${this.sourceUploadStatus?`<p class="po-upload-status">${
|
|
33
|
-
${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(
|
|
34
|
-
${this.sourceUploadError?`<p class="po-upload-error">${
|
|
34
|
+
${this.sourceUploadStatus?`<p class="po-upload-status">${l(this.sourceUploadStatus)}</p>`:""}
|
|
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">${l(this.sourceUploadError)}</p>`:""}
|
|
35
37
|
</div>
|
|
36
|
-
`}renderSourceItem(
|
|
38
|
+
`}renderSourceItem(t){var h,f,u;const e=t.filename||"未命名代码包",s=t.created_at?P(t.created_at):"刚刚上传",i=F(t.archive_bytes||t.total_bytes||0),r=String((f=(h=t.metadata)==null?void 0:h.analysis_status)!=null?f:"unknown"),o=(u={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[r])!=null?u:"项目记忆状态未知";return`<article class="po-source-item"><strong>${l(e)}</strong><span>${l(s)} · ${l(i)}</span><span>${l(o)}</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>${l(e.title)}</strong><span>${O(e.status)}</span></summary><pre>${l(JSON.stringify((s=e.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var t,e,s,i,r,o,h,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()),(o=(r=this.panel)==null?void 0:r.querySelector('[data-action="stop-answer"]'))==null||o.addEventListener("click",()=>this.cancelActiveAnswer(!0)),(f=(h=this.panel)==null?void 0:h.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 l(a){return a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function P(a){return new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(a))}function F(a){if(!a)return"0 B";const t=["B","KB","MB","GB"];let e=a,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(a){return{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",cancelled:"已停止"}[a]}const K=new q;g.PageOpsSDK=K,Object.defineProperty(g,Symbol.toStringTag,{value:"Module"})}));
|
package/dist/types.d.ts
CHANGED
|
@@ -42,7 +42,7 @@ export interface ConversationMessage {
|
|
|
42
42
|
export interface ExecutionStep {
|
|
43
43
|
id: string;
|
|
44
44
|
title: string;
|
|
45
|
-
status: 'pending' | 'running' | 'completed' | 'failed';
|
|
45
|
+
status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
|
|
46
46
|
details?: Record<string, unknown>;
|
|
47
47
|
}
|
|
48
48
|
export interface SourceSnapshot {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export declare class TypewriterQueue {
|
|
2
|
+
private readonly onChunk;
|
|
3
|
+
private readonly interval;
|
|
4
|
+
private queue;
|
|
5
|
+
private timer;
|
|
6
|
+
private drainWaiters;
|
|
7
|
+
constructor(onChunk: (chunk: string) => void, interval?: number);
|
|
8
|
+
enqueue(content: string): void;
|
|
9
|
+
drain(): Promise<void>;
|
|
10
|
+
clear(): void;
|
|
11
|
+
private tick;
|
|
12
|
+
private resolveDrainWaiters;
|
|
13
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pageops/sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.9",
|
|
4
4
|
"description": "PageOps embeddable frontend SDK",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/pageops-sdk.umd.cjs",
|
|
@@ -20,13 +20,16 @@
|
|
|
20
20
|
],
|
|
21
21
|
"scripts": {
|
|
22
22
|
"build": "vite build && tsc --emitDeclarationOnly",
|
|
23
|
-
"pack:check": "npm pack --dry-run"
|
|
23
|
+
"pack:check": "npm pack --dry-run",
|
|
24
|
+
"test": "vitest run"
|
|
24
25
|
},
|
|
25
26
|
"dependencies": {},
|
|
26
27
|
"devDependencies": {
|
|
27
28
|
"@types/node": "22.10.2",
|
|
29
|
+
"jsdom": "25.0.1",
|
|
28
30
|
"typescript": "5.8.3",
|
|
29
|
-
"vite": "6.3.5"
|
|
31
|
+
"vite": "6.3.5",
|
|
32
|
+
"vitest": "3.2.4"
|
|
30
33
|
},
|
|
31
34
|
"engines": {
|
|
32
35
|
"node": ">=20"
|