@pageops/sdk 0.1.1 → 0.1.3

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 CHANGED
@@ -1,4 +1,4 @@
1
- import type { ContextSession, ConversationMessage, ConversationThread, PageOpsMountOptions } from './types';
1
+ import type { ContextSession, ConversationMessage, ConversationThread, PageOpsMountOptions, SourceSnapshot } from './types';
2
2
  export declare class PageOpsClient {
3
3
  private options;
4
4
  constructor(options: PageOpsMountOptions);
@@ -6,6 +6,8 @@ export declare class PageOpsClient {
6
6
  listConversations(): Promise<ConversationThread[]>;
7
7
  createConversation(contextSessionId: string, title?: string): Promise<ConversationThread>;
8
8
  listMessages(threadId: string): Promise<ConversationMessage[]>;
9
+ listSources(): Promise<SourceSnapshot[]>;
10
+ uploadSource(file: File): Promise<SourceSnapshot>;
9
11
  streamQuestion(threadId: string, question: string): Promise<Response>;
10
12
  private request;
11
13
  private base;
package/dist/index.d.ts CHANGED
@@ -10,6 +10,10 @@ declare class PageOpsSDKController {
10
10
  private conversations;
11
11
  private messages;
12
12
  private steps;
13
+ private sourceSnapshots;
14
+ private sourceUploadStatus;
15
+ private sourceUploadError;
16
+ private sourceUploading;
13
17
  private streaming;
14
18
  mount(options: PageOpsMountOptions): void;
15
19
  unmount(): void;
@@ -18,12 +22,16 @@ declare class PageOpsSDKController {
18
22
  updateContext(options: Partial<PageOpsMountOptions>): void;
19
23
  private renderClosed;
20
24
  private ensureContext;
25
+ private loadSources;
21
26
  private loadConversations;
22
27
  private newConversation;
23
28
  private selectThread;
29
+ private uploadSource;
24
30
  private ask;
25
31
  private upsertStep;
26
32
  private renderPanel;
33
+ private renderSourceUploader;
34
+ private renderSourceItem;
27
35
  private renderSteps;
28
36
  private bindPanelEvents;
29
37
  }
@@ -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;gap:4px;width:100%;border:1px solid transparent;border-radius:10px;background:transparent;color:#334155;padding:9px 10px;text-align:left}.po-thread.active{border-color:#bfdbfe;background:#fff;color:var(--po-text)}.po-thread span{color:#94a3b8;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 code{border-radius:5px;background:#eaf0ff;color:var(--po-primary-dark);padding:1px 5px}.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-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-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 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%}}
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;gap:4px;width:100%;border:1px solid transparent;border-radius:10px;background:transparent;color:#334155;padding:9px 10px;text-align:left}.po-thread.active{border-color:#bfdbfe;background:#fff;color:var(--po-text)}.po-thread span{color:#94a3b8;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 code{border-radius:5px;background:#eaf0ff;color:var(--po-primary-dark);padding:1px 5px}.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-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 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%}}
@@ -1,13 +1,13 @@
1
- var y = Object.defineProperty;
2
- var $ = (i, t, e) => t in i ? y(i, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : i[t] = e;
3
- var l = (i, t, e) => $(i, typeof t != "symbol" ? t + "" : t, e);
4
- class v {
1
+ var w = Object.defineProperty;
2
+ var x = (r, t, e) => t in r ? w(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
3
+ var a = (r, t, e) => x(r, typeof t != "symbol" ? t + "" : t, e);
4
+ class S {
5
5
  constructor(t) {
6
6
  this.options = t;
7
7
  }
8
8
  async createContext() {
9
- var e, s, r, n, a;
10
- const t = (r = (s = (e = this.options).getPageContext) == null ? void 0 : s.call(e)) != null ? r : {};
9
+ var e, s, o, n, c;
10
+ const t = (o = (s = (e = this.options).getPageContext) == null ? void 0 : s.call(e)) != null ? o : {};
11
11
  return this.request("/context/session", {
12
12
  method: "POST",
13
13
  body: JSON.stringify({
@@ -15,7 +15,7 @@ class v {
15
15
  env: this.options.env,
16
16
  route: t.route,
17
17
  url: (n = t.url) != null ? n : location.href,
18
- title: (a = t.title) != null ? a : document.title,
18
+ title: (c = t.title) != null ? c : document.title,
19
19
  tenant_id: t.tenantId,
20
20
  user_role: t.userRole,
21
21
  build_version: t.buildVersion
@@ -34,6 +34,13 @@ class v {
34
34
  async listMessages(t) {
35
35
  return (await this.request(`/conversations/${encodeURIComponent(t)}/messages`)).messages;
36
36
  }
37
+ async listSources() {
38
+ return (await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources;
39
+ }
40
+ uploadSource(t) {
41
+ const e = new FormData();
42
+ return e.append("file", t), this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`, { method: "POST", body: e, headers: {} });
43
+ }
37
44
  streamQuestion(t, e) {
38
45
  return fetch(`${this.base()}/question/stream`, {
39
46
  method: "POST",
@@ -42,95 +49,97 @@ class v {
42
49
  });
43
50
  }
44
51
  async request(t, e) {
45
- var n, a;
46
- const s = await fetch(`${this.base()}${t}`, {
47
- ...e,
48
- headers: { "content-type": "application/json", ...(n = e == null ? void 0 : e.headers) != null ? n : {} }
49
- }), r = await s.json();
50
- if (!s.ok) throw new Error((a = r.message) != null ? a : "PageOps 请求失败");
51
- return r;
52
+ var c, h;
53
+ const s = (e == null ? void 0 : e.body) instanceof FormData ? e.headers : { "content-type": "application/json", ...(c = e == null ? void 0 : e.headers) != null ? c : {} }, o = await fetch(`${this.base()}${t}`, { ...e, headers: s }), n = await o.json();
54
+ if (!o.ok) throw new Error((h = n.message) != null ? h : "PageOps 请求失败");
55
+ return n;
52
56
  }
53
57
  base() {
54
- return this.options.apiBase.replace(/\/$/, "");
58
+ const t = this.options.apiBase.replace(/\/$/, "");
59
+ return t.endsWith("/api") ? t : `${t}/api`;
55
60
  }
56
61
  }
57
- function w(i) {
58
- return i.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
62
+ function E(r) {
63
+ return r.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
59
64
  }
60
- function g(i) {
61
- return w(i).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
65
+ function f(r) {
66
+ return E(r).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
62
67
  }
63
- function x(i, t) {
64
- const e = i[t], s = i[t + 1];
68
+ function P(r, t) {
69
+ const e = r[t], s = r[t + 1];
65
70
  if (!(e != null && e.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
66
- const r = [];
71
+ const o = [];
67
72
  let n = t;
68
- for (; n < i.length && i[n].includes("|") && i[n].trim(); )
69
- r.push(i[n]), n += 1;
70
- const a = (h) => h.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => g(c.trim())), u = a(r[0]).map((h) => `<th>${h}</th>`).join(""), m = r.slice(2).map((h) => `<tr>${a(h).map((c) => `<td>${c}</td>`).join("")}</tr>`).join("");
71
- return { html: `<table><thead><tr>${u}</tr></thead><tbody>${m}</tbody></table>`, next: n };
73
+ for (; n < r.length && r[n].includes("|") && r[n].trim(); )
74
+ o.push(r[n]), n += 1;
75
+ const c = (d) => d.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((m) => f(m.trim())), h = c(o[0]).map((d) => `<th>${d}</th>`).join(""), g = o.slice(2).map((d) => `<tr>${c(d).map((m) => `<td>${m}</td>`).join("")}</tr>`).join("");
76
+ return { html: `<table><thead><tr>${h}</tr></thead><tbody>${g}</tbody></table>`, next: n };
72
77
  }
73
- function b(i) {
74
- const t = i.split(`
78
+ function b(r) {
79
+ const t = r.split(`
75
80
  `), e = [];
76
81
  for (let s = 0; s < t.length; s += 1) {
77
- const r = x(t, s);
78
- if (r) {
79
- e.push(r.html), s = r.next - 1;
82
+ const o = P(t, s);
83
+ if (o) {
84
+ e.push(o.html), s = o.next - 1;
80
85
  continue;
81
86
  }
82
87
  const n = t[s];
83
- n.startsWith("### ") ? e.push(`<h4>${g(n.slice(4))}</h4>`) : n.startsWith("## ") ? e.push(`<h3>${g(n.slice(3))}</h3>`) : n.startsWith("# ") ? e.push(`<h2>${g(n.slice(2))}</h2>`) : n.startsWith("- ") ? e.push(`<li>${g(n.slice(2))}</li>`) : n.trim() ? e.push(`<p>${g(n)}</p>`) : e.push("<br>");
88
+ n.startsWith("### ") ? e.push(`<h4>${f(n.slice(4))}</h4>`) : n.startsWith("## ") ? e.push(`<h3>${f(n.slice(3))}</h3>`) : n.startsWith("# ") ? e.push(`<h2>${f(n.slice(2))}</h2>`) : n.startsWith("- ") ? e.push(`<li>${f(n.slice(2))}</li>`) : n.trim() ? e.push(`<p>${f(n)}</p>`) : e.push("<br>");
84
89
  }
85
90
  return e.join("");
86
91
  }
87
- async function S(i, t) {
88
- var n, a, u;
89
- const e = i.getReader(), s = new TextDecoder();
90
- let r = "";
92
+ async function T(r, t) {
93
+ var n, c, h;
94
+ const e = r.getReader(), s = new TextDecoder();
95
+ let o = "";
91
96
  for (; ; ) {
92
- const { done: m, value: h } = await e.read();
93
- if (m) break;
94
- r += s.decode(h, { stream: !0 });
95
- const c = r.split(`
97
+ const { done: g, value: d } = await e.read();
98
+ if (g) break;
99
+ o += s.decode(d, { stream: !0 });
100
+ const m = o.split(`
96
101
 
97
102
  `);
98
- r = (n = c.pop()) != null ? n : "";
99
- for (const o of c) {
100
- const d = (a = o.match(/^event: (.+)$/m)) == null ? void 0 : a[1], p = (u = o.match(/^data: (.+)$/m)) == null ? void 0 : u[1];
101
- d && p && t(d, JSON.parse(p));
103
+ o = (n = m.pop()) != null ? n : "";
104
+ for (const v of m) {
105
+ const l = (c = v.match(/^event: (.+)$/m)) == null ? void 0 : c[1], i = (h = v.match(/^data: (.+)$/m)) == null ? void 0 : h[1];
106
+ l && i && t(l, JSON.parse(i));
102
107
  }
103
108
  }
104
109
  }
105
- class T {
110
+ class U {
106
111
  constructor() {
107
- l(this, "client", null);
108
- l(this, "options", null);
109
- l(this, "root", null);
110
- l(this, "panel", null);
111
- l(this, "context", null);
112
- l(this, "currentThread", null);
113
- l(this, "conversations", []);
114
- l(this, "messages", []);
115
- l(this, "steps", []);
116
- l(this, "streaming", "");
112
+ a(this, "client", null);
113
+ a(this, "options", null);
114
+ a(this, "root", null);
115
+ a(this, "panel", null);
116
+ a(this, "context", null);
117
+ a(this, "currentThread", null);
118
+ a(this, "conversations", []);
119
+ a(this, "messages", []);
120
+ a(this, "steps", []);
121
+ a(this, "sourceSnapshots", []);
122
+ a(this, "sourceUploadStatus", "");
123
+ a(this, "sourceUploadError", "");
124
+ a(this, "sourceUploading", !1);
125
+ a(this, "streaming", "");
117
126
  }
118
127
  mount(t) {
119
128
  var e;
120
- this.unmount(), this.options = t, this.client = new v(t), this.root = document.createElement("div"), this.root.className = "pageops-sdk", ((e = t.container) != null ? e : document.body).appendChild(this.root), this.renderClosed();
129
+ this.unmount(), this.options = t, this.client = new S(t), this.root = document.createElement("div"), this.root.className = "pageops-sdk", ((e = t.container) != null ? e : document.body).appendChild(this.root), this.renderClosed();
121
130
  }
122
131
  unmount() {
123
132
  var t;
124
- (t = this.root) == null || t.remove(), this.root = null, this.panel = null, this.context = null, this.currentThread = null, this.conversations = [], this.messages = [], this.steps = [], this.streaming = "";
133
+ (t = this.root) == null || t.remove(), this.root = null, this.panel = null, this.context = null, this.currentThread = null, this.conversations = [], this.messages = [], this.steps = [], this.sourceSnapshots = [], this.sourceUploadStatus = "", this.sourceUploadError = "", this.sourceUploading = !1, this.streaming = "";
125
134
  }
126
135
  open() {
127
- this.root && (this.root.innerHTML = "", this.panel = document.createElement("div"), this.panel.className = "po-panel", this.root.appendChild(this.panel), this.loadConversations(), this.renderPanel());
136
+ 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());
128
137
  }
129
138
  close() {
130
139
  this.renderClosed();
131
140
  }
132
141
  updateContext(t) {
133
- this.options && (this.options = { ...this.options, ...t }, this.client = new v(this.options));
142
+ this.options && (this.options = { ...this.options, ...t }, this.client = new S(this.options));
134
143
  }
135
144
  renderClosed() {
136
145
  var t;
@@ -141,6 +150,16 @@ class T {
141
150
  if (!this.client) throw new Error("PageOps SDK 未初始化");
142
151
  return this.context = await this.client.createContext(), this.context;
143
152
  }
153
+ async loadSources() {
154
+ if (this.client) {
155
+ try {
156
+ this.sourceSnapshots = await this.client.listSources(), this.sourceUploadError = "";
157
+ } catch (t) {
158
+ this.sourceUploadError = t instanceof Error ? t.message : "源码包状态加载失败";
159
+ }
160
+ this.renderPanel();
161
+ }
162
+ }
144
163
  async loadConversations() {
145
164
  this.client && (this.conversations = await this.client.listConversations(), this.renderPanel());
146
165
  }
@@ -152,14 +171,31 @@ class T {
152
171
  async selectThread(t) {
153
172
  this.client && (this.currentThread = t, this.messages = await this.client.listMessages(t.id), this.steps = [], this.streaming = "", this.renderPanel());
154
173
  }
174
+ async uploadSource(t) {
175
+ if (this.client) {
176
+ this.sourceUploading = !0, this.sourceUploadStatus = "上传中...", this.sourceUploadError = "", this.renderPanel();
177
+ try {
178
+ await this.client.uploadSource(t), this.sourceSnapshots = await this.client.listSources(), this.sourceUploadStatus = "上传完成";
179
+ } catch (e) {
180
+ this.sourceUploadError = e instanceof Error ? e.message : "源码包上传失败", this.sourceUploadStatus = "";
181
+ } finally {
182
+ this.sourceUploading = !1, this.renderPanel();
183
+ }
184
+ }
185
+ }
155
186
  async ask(t) {
156
- if (!this.client || (this.currentThread || await this.newConversation(), !this.currentThread)) return;
187
+ if (!this.client) return;
188
+ if (!this.sourceSnapshots.length) {
189
+ this.sourceUploadError = "请先上传代码包后再提问。", this.renderPanel();
190
+ return;
191
+ }
192
+ if (this.currentThread || await this.newConversation(), !this.currentThread) return;
157
193
  this.messages.push({ id: `local-${Date.now()}`, role: "user", content: t, metadata_json: {} }), this.steps = [], this.streaming = "", this.renderPanel();
158
194
  const e = await this.client.streamQuestion(this.currentThread.id, t);
159
195
  if (!e.ok || !e.body) throw new Error("PageOps 流式问答失败");
160
- await S(e.body, (s, r) => {
196
+ await T(e.body, (s, o) => {
161
197
  var n;
162
- s === "step" && this.upsertStep(r), s === "delta" && (this.streaming += String((n = r.content) != null ? n : "")), s === "done" && this.selectThread(this.currentThread), s === "error" && this.upsertStep({ id: "error", title: "执行失败", status: "failed", details: r }), this.renderPanel();
198
+ s === "step" && this.upsertStep(o), s === "delta" && (this.streaming += String((n = o.content) != null ? n : "")), s === "done" && this.selectThread(this.currentThread), s === "error" && this.upsertStep({ id: "error", title: "执行失败", status: "failed", details: o }), this.renderPanel();
163
199
  });
164
200
  }
165
201
  upsertStep(t) {
@@ -176,53 +212,84 @@ class T {
176
212
  var e;
177
213
  return `
178
214
  <button class="po-thread ${t.id === ((e = this.currentThread) == null ? void 0 : e.id) ? "active" : ""}" data-thread="${t.id}">
179
- <strong>${f(t.title)}</strong><span>${C(t.created_at)}</span>
215
+ <strong>${u(t.title)}</strong><span>${y(t.created_at)}</span>
180
216
  </button>`;
181
217
  }).join("")}</div>
182
218
  </aside>
183
219
  <main class="po-chat">
184
- <header><div><p>问数回答</p><h2>${this.currentThread ? f(this.currentThread.title) : "未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
220
+ <header><div><p>问数回答</p><h2>${this.currentThread ? u(this.currentThread.title) : "未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
185
221
  <section class="po-messages">
186
- ${this.messages.map((t) => `<article class="po-message ${t.role}"><b>${t.role === "user" ? "你" : "PageOps 分析"}</b><div>${t.role === "assistant" ? b(t.content) : f(t.content)}</div></article>`).join("")}
222
+ ${this.messages.map((t) => `<article class="po-message ${t.role}"><b>${t.role === "user" ? "你" : "PageOps 分析"}</b><div>${t.role === "assistant" ? b(t.content) : u(t.content)}</div></article>`).join("")}
187
223
  ${this.streaming ? `<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${b(this.streaming)}</div></article>` : ""}
188
224
  </section>
189
- <form class="po-composer"><textarea placeholder="请输入页面分析问题,Enter 发送,Shift + Enter 换行"></textarea><button type="submit">发送</button></form>
225
+ <form class="po-composer"><textarea ${this.sourceSnapshots.length ? "" : "disabled"} placeholder="${this.sourceSnapshots.length ? "请输入页面分析问题,Enter 发送,Shift + Enter 换行" : "请先上传代码包后再提问"}"></textarea><button type="submit" ${this.sourceSnapshots.length ? "" : "disabled"}>${this.sourceSnapshots.length ? "发送" : "请先上传代码包"}</button></form>
190
226
  </main>
191
- <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSteps()}</section></aside>
227
+ <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
192
228
  `, this.bindPanelEvents());
193
229
  }
230
+ renderSourceUploader() {
231
+ return `
232
+ <div class="po-source-uploader">
233
+ <strong>源码包</strong>
234
+ <p>上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
235
+ <label class="po-upload-button">
236
+ <span>${this.sourceUploading ? "上传中..." : "选择代码包"}</span>
237
+ <input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading ? "disabled" : ""} />
238
+ </label>
239
+ ${this.sourceUploadStatus ? `<p class="po-upload-status">${u(this.sourceUploadStatus)}</p>` : ""}
240
+ ${this.sourceSnapshots.length ? `<div class="po-source-list">${this.sourceSnapshots.map((t) => this.renderSourceItem(t)).join("")}</div>` : '<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
241
+ ${this.sourceUploadError ? `<p class="po-upload-error">${u(this.sourceUploadError)}</p>` : ""}
242
+ </div>
243
+ `;
244
+ }
245
+ renderSourceItem(t) {
246
+ const e = t.filename || "未命名代码包", s = t.created_at ? y(t.created_at) : "刚刚上传", o = C(t.archive_bytes || t.total_bytes || 0);
247
+ return `<article class="po-source-item"><strong>${u(e)}</strong><span>${u(s)} · ${u(o)}</span></article>`;
248
+ }
194
249
  renderSteps() {
195
250
  return (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", details: { message: "发送消息后展示执行过程。" } }]).map((e) => {
196
251
  var s;
197
- return `<details class="po-step ${e.status}" ${e.status === "running" || e.status === "failed" ? "open" : ""}><summary><strong>${f(e.title)}</strong><span>${e.status}</span></summary><pre>${f(JSON.stringify((s = e.details) != null ? s : {}, null, 2))}</pre></details>`;
252
+ return `<details class="po-step ${e.status}" ${e.status === "running" || e.status === "failed" ? "open" : ""}><summary><strong>${u(e.title)}</strong><span>${e.status}</span></summary><pre>${u(JSON.stringify((s = e.details) != null ? s : {}, null, 2))}</pre></details>`;
198
253
  }).join("");
199
254
  }
200
255
  bindPanelEvents() {
201
- var t, e, s, r, n, a, u, m, h;
202
- (e = (t = this.panel) == null ? void 0 : t.querySelector('[data-action="new"]')) == null || e.addEventListener("click", () => void this.newConversation()), (r = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || r.addEventListener("click", () => this.close()), (n = this.panel) == null || n.querySelectorAll("[data-thread]").forEach((c) => {
203
- c.addEventListener("click", () => {
204
- const o = this.conversations.find((d) => d.id === c.dataset.thread);
205
- o && this.selectThread(o);
206
- });
207
- }), (u = (a = this.panel) == null ? void 0 : a.querySelector("form")) == null || u.addEventListener("submit", (c) => {
256
+ var t, e, s, o, n, c, h, g, d, m, v;
257
+ (e = (t = this.panel) == null ? void 0 : t.querySelector('[data-action="new"]')) == null || e.addEventListener("click", () => void this.newConversation()), (o = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || o.addEventListener("click", () => this.close()), (c = (n = this.panel) == null ? void 0 : n.querySelector('[data-action="upload-source"]')) == null || c.addEventListener("change", (l) => {
208
258
  var p;
209
- c.preventDefault();
210
- const o = (p = this.panel) == null ? void 0 : p.querySelector("textarea"), d = o == null ? void 0 : o.value.trim();
211
- d && (o.value = "", this.ask(d));
212
- }), (h = (m = this.panel) == null ? void 0 : m.querySelector("textarea")) == null || h.addEventListener("keydown", (c) => {
213
- var d, p;
214
- const o = c;
215
- o.key === "Enter" && !o.shiftKey && (o.preventDefault(), (p = (d = this.panel) == null ? void 0 : d.querySelector("form")) == null || p.requestSubmit());
259
+ const i = (p = l.target.files) == null ? void 0 : p[0];
260
+ i && this.uploadSource(i);
261
+ }), (h = this.panel) == null || h.querySelectorAll("[data-thread]").forEach((l) => {
262
+ l.addEventListener("click", () => {
263
+ const i = this.conversations.find((p) => p.id === l.dataset.thread);
264
+ i && this.selectThread(i);
265
+ });
266
+ }), (d = (g = this.panel) == null ? void 0 : g.querySelector("form")) == null || d.addEventListener("submit", (l) => {
267
+ var $;
268
+ l.preventDefault();
269
+ const i = ($ = this.panel) == null ? void 0 : $.querySelector("textarea"), p = i == null ? void 0 : i.value.trim();
270
+ p && (i.value = "", this.ask(p));
271
+ }), (v = (m = this.panel) == null ? void 0 : m.querySelector("textarea")) == null || v.addEventListener("keydown", (l) => {
272
+ var p, $;
273
+ const i = l;
274
+ i.key === "Enter" && !i.shiftKey && (i.preventDefault(), ($ = (p = this.panel) == null ? void 0 : p.querySelector("form")) == null || $.requestSubmit());
216
275
  });
217
276
  }
218
277
  }
219
- function f(i) {
220
- return i.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
278
+ function u(r) {
279
+ return r.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
280
+ }
281
+ function y(r) {
282
+ return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(r));
221
283
  }
222
- function C(i) {
223
- return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(i));
284
+ function C(r) {
285
+ if (!r) return "0 B";
286
+ const t = ["B", "KB", "MB", "GB"];
287
+ let e = r, s = 0;
288
+ for (; e >= 1024 && s < t.length - 1; )
289
+ e /= 1024, s += 1;
290
+ return `${e >= 10 || s === 0 ? e.toFixed(0) : e.toFixed(1)} ${t[s]}`;
224
291
  }
225
- const E = new T();
292
+ const q = new U();
226
293
  export {
227
- E as PageOpsSDK
294
+ q as PageOpsSDK
228
295
  };
@@ -1,23 +1,35 @@
1
- (function(h,o){typeof exports=="object"&&typeof module!="undefined"?o(exports):typeof define=="function"&&define.amd?define(["exports"],o):(h=typeof globalThis!="undefined"?globalThis:h||self,o(h.PageOpsSDK={}))})(this,(function(h){"use strict";var C=Object.defineProperty;var O=(h,o,g)=>o in h?C(h,o,{enumerable:!0,configurable:!0,writable:!0,value:g}):h[o]=g;var d=(h,o,g)=>O(h,typeof o!="symbol"?o+"":o,g);class o{constructor(t){this.options=t}async createContext(){var e,s,i,n,a;const t=(i=(s=(e=this.options).getPageContext)==null?void 0:s.call(e))!=null?i:{};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:(a=t.title)!=null?a:document.title,tenant_id:t.tenantId,user_role:t.userRole,build_version:t.buildVersion})})}async listConversations(){return(await this.request("/conversations")).conversations}async createConversation(t,e){return this.request("/conversations",{method:"POST",body:JSON.stringify({context_session_id:t,title:e})})}async listMessages(t){return(await this.request(`/conversations/${encodeURIComponent(t)}/messages`)).messages}streamQuestion(t,e){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({thread_id:t,question:e})})}async request(t,e){var n,a;const s=await fetch(`${this.base()}${t}`,{...e,headers:{"content-type":"application/json",...(n=e==null?void 0:e.headers)!=null?n:{}}}),i=await s.json();if(!s.ok)throw new Error((a=i.message)!=null?a:"PageOps 请求失败");return i}base(){return this.options.apiBase.replace(/\/$/,"")}}function g(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function v(r){return g(r).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function w(r,t){const e=r[t],s=r[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<r.length&&r[n].includes("|")&&r[n].trim();)i.push(r[n]),n+=1;const a=p=>p.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(l=>v(l.trim())),f=a(i[0]).map(p=>`<th>${p}</th>`).join(""),b=i.slice(2).map(p=>`<tr>${a(p).map(l=>`<td>${l}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${f}</tr></thead><tbody>${b}</tbody></table>`,next:n}}function $(r){const t=r.split(`
2
- `),e=[];for(let s=0;s<t.length;s+=1){const i=w(t,s);if(i){e.push(i.html),s=i.next-1;continue}const n=t[s];n.startsWith("### ")?e.push(`<h4>${v(n.slice(4))}</h4>`):n.startsWith("## ")?e.push(`<h3>${v(n.slice(3))}</h3>`):n.startsWith("# ")?e.push(`<h2>${v(n.slice(2))}</h2>`):n.startsWith("- ")?e.push(`<li>${v(n.slice(2))}</li>`):n.trim()?e.push(`<p>${v(n)}</p>`):e.push("<br>")}return e.join("")}async function S(r,t){var n,a,f;const e=r.getReader(),s=new TextDecoder;let i="";for(;;){const{done:b,value:p}=await e.read();if(b)break;i+=s.decode(p,{stream:!0});const l=i.split(`
1
+ (function(h,c){typeof exports=="object"&&typeof module!="undefined"?c(exports):typeof define=="function"&&define.amd?define(["exports"],c):(h=typeof globalThis!="undefined"?globalThis:h||self,c(h.PageOpsSDK={}))})(this,(function(h){"use strict";var O=Object.defineProperty;var q=(h,c,v)=>c in h?O(h,c,{enumerable:!0,configurable:!0,writable:!0,value:v}):h[c]=v;var a=(h,c,v)=>q(h,typeof c!="symbol"?c+"":c,v);class c{constructor(t){this.options=t}async createContext(){var e,s,r,n,l;const t=(r=(s=(e=this.options).getPageContext)==null?void 0:s.call(e))!=null?r:{};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:(l=t.title)!=null?l:document.title,tenant_id:t.tenantId,user_role:t.userRole,build_version:t.buildVersion})})}async listConversations(){return(await this.request("/conversations")).conversations}async createConversation(t,e){return this.request("/conversations",{method:"POST",body:JSON.stringify({context_session_id:t,title:e})})}async listMessages(t){return(await this.request(`/conversations/${encodeURIComponent(t)}/messages`)).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){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({thread_id:t,question:e})})}async request(t,e){var l,u;const s=(e==null?void 0:e.body)instanceof FormData?e.headers:{"content-type":"application/json",...(l=e==null?void 0:e.headers)!=null?l:{}},r=await fetch(`${this.base()}${t}`,{...e,headers:s}),n=await r.json();if(!r.ok)throw new Error((u=n.message)!=null?u:"PageOps 请求失败");return n}base(){const t=this.options.apiBase.replace(/\/$/,"");return t.endsWith("/api")?t:`${t}/api`}}function v(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function S(o){return v(o).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function E(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 r=[];let n=t;for(;n<o.length&&o[n].includes("|")&&o[n].trim();)r.push(o[n]),n+=1;const l=m=>m.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(g=>S(g.trim())),u=l(r[0]).map(m=>`<th>${m}</th>`).join(""),$=r.slice(2).map(m=>`<tr>${l(m).map(g=>`<td>${g}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${u}</tr></thead><tbody>${$}</tbody></table>`,next:n}}function w(o){const t=o.split(`
2
+ `),e=[];for(let s=0;s<t.length;s+=1){const r=E(t,s);if(r){e.push(r.html),s=r.next-1;continue}const n=t[s];n.startsWith("### ")?e.push(`<h4>${S(n.slice(4))}</h4>`):n.startsWith("## ")?e.push(`<h3>${S(n.slice(3))}</h3>`):n.startsWith("# ")?e.push(`<h2>${S(n.slice(2))}</h2>`):n.startsWith("- ")?e.push(`<li>${S(n.slice(2))}</li>`):n.trim()?e.push(`<p>${S(n)}</p>`):e.push("<br>")}return e.join("")}async function P(o,t){var n,l,u;const e=o.getReader(),s=new TextDecoder;let r="";for(;;){const{done:$,value:m}=await e.read();if($)break;r+=s.decode(m,{stream:!0});const g=r.split(`
3
3
 
4
- `);i=(n=l.pop())!=null?n:"";for(const c of l){const u=(a=c.match(/^event: (.+)$/m))==null?void 0:a[1],m=(f=c.match(/^data: (.+)$/m))==null?void 0:f[1];u&&m&&t(u,JSON.parse(m))}}}class x{constructor(){d(this,"client",null);d(this,"options",null);d(this,"root",null);d(this,"panel",null);d(this,"context",null);d(this,"currentThread",null);d(this,"conversations",[]);d(this,"messages",[]);d(this,"steps",[]);d(this,"streaming","")}mount(t){var e;this.unmount(),this.options=t,this.client=new o(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;(t=this.root)==null||t.remove(),this.root=null,this.panel=null,this.context=null,this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.streaming=""}open(){this.root&&(this.root.innerHTML="",this.panel=document.createElement("div"),this.panel.className="po-panel",this.root.appendChild(this.panel),this.loadConversations(),this.renderPanel())}close(){this.renderClosed()}updateContext(t){this.options&&(this.options={...this.options,...t},this.client=new o(this.options))}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.context)return this.context;if(!this.client)throw new Error("PageOps SDK 未初始化");return this.context=await this.client.createContext(),this.context}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){if(!this.client)return;const t=await this.ensureContext();this.currentThread=await this.client.createConversation(t.id,t.route||document.title||"新的问答"),this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.renderPanel()}async selectThread(t){this.client&&(this.currentThread=t,this.messages=await this.client.listMessages(t.id),this.steps=[],this.streaming="",this.renderPanel())}async ask(t){if(!this.client||(this.currentThread||await this.newConversation(),!this.currentThread))return;this.messages.push({id:`local-${Date.now()}`,role:"user",content:t,metadata_json:{}}),this.steps=[],this.streaming="",this.renderPanel();const e=await this.client.streamQuestion(this.currentThread.id,t);if(!e.ok||!e.body)throw new Error("PageOps 流式问答失败");await S(e.body,(s,i)=>{var n;s==="step"&&this.upsertStep(i),s==="delta"&&(this.streaming+=String((n=i.content)!=null?n:"")),s==="done"&&this.selectThread(this.currentThread),s==="error"&&this.upsertStep({id:"error",title:"执行失败",status:"failed",details:i}),this.renderPanel()})}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)}renderPanel(){this.panel&&(this.panel.innerHTML=`
4
+ `);r=(n=g.pop())!=null?n:"";for(const y of g){const d=(l=y.match(/^event: (.+)$/m))==null?void 0:l[1],i=(u=y.match(/^data: (.+)$/m))==null?void 0:u[1];d&&i&&t(d,JSON.parse(i))}}}class T{constructor(){a(this,"client",null);a(this,"options",null);a(this,"root",null);a(this,"panel",null);a(this,"context",null);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,"streaming","")}mount(t){var e;this.unmount(),this.options=t,this.client=new c(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;(t=this.root)==null||t.remove(),this.root=null,this.panel=null,this.context=null,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.renderClosed()}updateContext(t){this.options&&(this.options={...this.options,...t},this.client=new c(this.options))}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.context)return this.context;if(!this.client)throw new Error("PageOps SDK 未初始化");return this.context=await this.client.createContext(),this.context}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceUploadError=""}catch(t){this.sourceUploadError=t instanceof Error?t.message:"源码包状态加载失败"}this.renderPanel()}}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){if(!this.client)return;const t=await this.ensureContext();this.currentThread=await this.client.createConversation(t.id,t.route||document.title||"新的问答"),this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.renderPanel()}async selectThread(t){this.client&&(this.currentThread=t,this.messages=await this.client.listMessages(t.id),this.steps=[],this.streaming="",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="上传完成"}catch(e){this.sourceUploadError=e instanceof Error?e.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.renderPanel()}}}async ask(t){if(!this.client)return;if(!this.sourceSnapshots.length){this.sourceUploadError="请先上传代码包后再提问。",this.renderPanel();return}if(this.currentThread||await this.newConversation(),!this.currentThread)return;this.messages.push({id:`local-${Date.now()}`,role:"user",content:t,metadata_json:{}}),this.steps=[],this.streaming="",this.renderPanel();const e=await this.client.streamQuestion(this.currentThread.id,t);if(!e.ok||!e.body)throw new Error("PageOps 流式问答失败");await P(e.body,(s,r)=>{var n;s==="step"&&this.upsertStep(r),s==="delta"&&(this.streaming+=String((n=r.content)!=null?n:"")),s==="done"&&this.selectThread(this.currentThread),s==="error"&&this.upsertStep({id:"error",title:"执行失败",status:"failed",details:r}),this.renderPanel()})}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)}renderPanel(){this.panel&&(this.panel.innerHTML=`
5
5
  <aside class="po-sidebar">
6
6
  <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
7
7
  <button class="po-new" data-action="new">+ 新建问答</button>
8
8
  <input class="po-search" placeholder="搜索问答" />
9
9
  <div class="po-thread-list">${this.conversations.map(t=>{var e;return`
10
10
  <button class="po-thread ${t.id===((e=this.currentThread)==null?void 0:e.id)?"active":""}" data-thread="${t.id}">
11
- <strong>${y(t.title)}</strong><span>${T(t.created_at)}</span>
11
+ <strong>${p(t.title)}</strong><span>${x(t.created_at)}</span>
12
12
  </button>`}).join("")}</div>
13
13
  </aside>
14
14
  <main class="po-chat">
15
- <header><div><p>问数回答</p><h2>${this.currentThread?y(this.currentThread.title):"未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
15
+ <header><div><p>问数回答</p><h2>${this.currentThread?p(this.currentThread.title):"未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
16
16
  <section class="po-messages">
17
- ${this.messages.map(t=>`<article class="po-message ${t.role}"><b>${t.role==="user"?"你":"PageOps 分析"}</b><div>${t.role==="assistant"?$(t.content):y(t.content)}</div></article>`).join("")}
18
- ${this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${$(this.streaming)}</div></article>`:""}
17
+ ${this.messages.map(t=>`<article class="po-message ${t.role}"><b>${t.role==="user"?"你":"PageOps 分析"}</b><div>${t.role==="assistant"?w(t.content):p(t.content)}</div></article>`).join("")}
18
+ ${this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${w(this.streaming)}</div></article>`:""}
19
19
  </section>
20
- <form class="po-composer"><textarea placeholder="请输入页面分析问题,Enter 发送,Shift + Enter 换行"></textarea><button type="submit">发送</button></form>
20
+ <form class="po-composer"><textarea ${this.sourceSnapshots.length?"":"disabled"} placeholder="${this.sourceSnapshots.length?"请输入页面分析问题,Enter 发送,Shift + Enter 换行":"请先上传代码包后再提问"}"></textarea><button type="submit" ${this.sourceSnapshots.length?"":"disabled"}>${this.sourceSnapshots.length?"发送":"请先上传代码包"}</button></form>
21
21
  </main>
22
- <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSteps()}</section></aside>
23
- `,this.bindPanelEvents())}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>${y(e.title)}</strong><span>${e.status}</span></summary><pre>${y(JSON.stringify((s=e.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var t,e,s,i,n,a,f,b,p;(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()),(n=this.panel)==null||n.querySelectorAll("[data-thread]").forEach(l=>{l.addEventListener("click",()=>{const c=this.conversations.find(u=>u.id===l.dataset.thread);c&&this.selectThread(c)})}),(f=(a=this.panel)==null?void 0:a.querySelector("form"))==null||f.addEventListener("submit",l=>{var m;l.preventDefault();const c=(m=this.panel)==null?void 0:m.querySelector("textarea"),u=c==null?void 0:c.value.trim();u&&(c.value="",this.ask(u))}),(p=(b=this.panel)==null?void 0:b.querySelector("textarea"))==null||p.addEventListener("keydown",l=>{var u,m;const c=l;c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),(m=(u=this.panel)==null?void 0:u.querySelector("form"))==null||m.requestSubmit())})}}function y(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function T(r){return new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(r))}const P=new x;h.PageOpsSDK=P,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
22
+ <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
23
+ `,this.bindPanelEvents())}renderSourceUploader(){return`
24
+ <div class="po-source-uploader">
25
+ <strong>源码包</strong>
26
+ <p>上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
27
+ <label class="po-upload-button">
28
+ <span>${this.sourceUploading?"上传中...":"选择代码包"}</span>
29
+ <input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
30
+ </label>
31
+ ${this.sourceUploadStatus?`<p class="po-upload-status">${p(this.sourceUploadStatus)}</p>`:""}
32
+ ${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(t=>this.renderSourceItem(t)).join("")}</div>`:'<p class="po-upload-empty">当前系统暂无代码包,请先上传后再提问。</p>'}
33
+ ${this.sourceUploadError?`<p class="po-upload-error">${p(this.sourceUploadError)}</p>`:""}
34
+ </div>
35
+ `}renderSourceItem(t){const e=t.filename||"未命名代码包",s=t.created_at?x(t.created_at):"刚刚上传",r=U(t.archive_bytes||t.total_bytes||0);return`<article class="po-source-item"><strong>${p(e)}</strong><span>${p(s)} · ${p(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>${p(e.title)}</strong><span>${e.status}</span></summary><pre>${p(JSON.stringify((s=e.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var t,e,s,r,n,l,u,$,m,g,y;(e=(t=this.panel)==null?void 0:t.querySelector('[data-action="new"]'))==null||e.addEventListener("click",()=>void this.newConversation()),(r=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||r.addEventListener("click",()=>this.close()),(l=(n=this.panel)==null?void 0:n.querySelector('[data-action="upload-source"]'))==null||l.addEventListener("change",d=>{var f;const i=(f=d.target.files)==null?void 0:f[0];i&&this.uploadSource(i)}),(u=this.panel)==null||u.querySelectorAll("[data-thread]").forEach(d=>{d.addEventListener("click",()=>{const i=this.conversations.find(f=>f.id===d.dataset.thread);i&&this.selectThread(i)})}),(m=($=this.panel)==null?void 0:$.querySelector("form"))==null||m.addEventListener("submit",d=>{var b;d.preventDefault();const i=(b=this.panel)==null?void 0:b.querySelector("textarea"),f=i==null?void 0:i.value.trim();f&&(i.value="",this.ask(f))}),(y=(g=this.panel)==null?void 0:g.querySelector("textarea"))==null||y.addEventListener("keydown",d=>{var f,b;const i=d;i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),(b=(f=this.panel)==null?void 0:f.querySelector("form"))==null||b.requestSubmit())})}}function p(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function x(o){return new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(o))}function U(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]}`}const C=new T;h.PageOpsSDK=C,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
package/dist/types.d.ts CHANGED
@@ -43,6 +43,21 @@ export interface ExecutionStep {
43
43
  status: 'pending' | 'running' | 'completed' | 'failed';
44
44
  details?: Record<string, unknown>;
45
45
  }
46
+ export interface SourceSnapshot {
47
+ id?: string;
48
+ source_snapshot_id?: string | null;
49
+ project_id?: string;
50
+ filename?: string | null;
51
+ archive_bytes?: number;
52
+ status: string;
53
+ message?: string | null;
54
+ file_count: number;
55
+ total_bytes?: number;
56
+ created_at?: string | null;
57
+ }
58
+ export interface SourceSnapshotListResponse {
59
+ sources: SourceSnapshot[];
60
+ }
46
61
  export interface StreamDonePayload {
47
62
  message_id: string;
48
63
  answer: Record<string, unknown>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pageops/sdk",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "PageOps embeddable frontend SDK",
5
5
  "type": "module",
6
6
  "main": "dist/pageops-sdk.umd.cjs",