@pageops/sdk 0.1.0

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.
@@ -0,0 +1,12 @@
1
+ import type { ContextSession, ConversationMessage, ConversationThread, PageOpsMountOptions } from './types';
2
+ export declare class PageOpsClient {
3
+ private options;
4
+ constructor(options: PageOpsMountOptions);
5
+ createContext(): Promise<ContextSession>;
6
+ listConversations(): Promise<ConversationThread[]>;
7
+ createConversation(contextSessionId: string, title?: string): Promise<ConversationThread>;
8
+ listMessages(threadId: string): Promise<ConversationMessage[]>;
9
+ streamQuestion(threadId: string, question: string): Promise<Response>;
10
+ private request;
11
+ private base;
12
+ }
@@ -0,0 +1,31 @@
1
+ import './styles.css';
2
+ import type { PageOpsContext, PageOpsMountOptions } from './types';
3
+ declare class PageOpsSDKController {
4
+ private client;
5
+ private options;
6
+ private root;
7
+ private panel;
8
+ private context;
9
+ private currentThread;
10
+ private conversations;
11
+ private messages;
12
+ private steps;
13
+ private streaming;
14
+ mount(options: PageOpsMountOptions): void;
15
+ unmount(): void;
16
+ open(): void;
17
+ close(): void;
18
+ updateContext(options: Partial<PageOpsMountOptions>): void;
19
+ private renderClosed;
20
+ private ensureContext;
21
+ private loadConversations;
22
+ private newConversation;
23
+ private selectThread;
24
+ private ask;
25
+ private upsertStep;
26
+ private renderPanel;
27
+ private renderSteps;
28
+ private bindPanelEvents;
29
+ }
30
+ export declare const PageOpsSDK: PageOpsSDKController;
31
+ export type { PageOpsMountOptions, PageOpsContext };
@@ -0,0 +1 @@
1
+ export declare function renderMarkdown(text: string): string;
@@ -0,0 +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;top:40px;right:40px;bottom:40px;left: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{top:12px;right:12px;bottom:12px;left: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%}}
@@ -0,0 +1,222 @@
1
+ var y = Object.defineProperty;
2
+ var $ = (n, t, e) => t in n ? y(n, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : n[t] = e;
3
+ var l = (n, t, e) => $(n, typeof t != "symbol" ? t + "" : t, e);
4
+ class v {
5
+ constructor(t) {
6
+ this.options = t;
7
+ }
8
+ async createContext() {
9
+ var e, s;
10
+ const t = ((s = (e = this.options).getPageContext) == null ? void 0 : s.call(e)) ?? {};
11
+ return this.request("/context/session", {
12
+ method: "POST",
13
+ body: JSON.stringify({
14
+ app_id: this.options.appId,
15
+ env: this.options.env,
16
+ route: t.route,
17
+ url: t.url ?? location.href,
18
+ title: t.title ?? document.title,
19
+ tenant_id: t.tenantId,
20
+ user_role: t.userRole,
21
+ build_version: t.buildVersion
22
+ })
23
+ });
24
+ }
25
+ async listConversations() {
26
+ return (await this.request("/conversations")).conversations;
27
+ }
28
+ async createConversation(t, e) {
29
+ return this.request("/conversations", {
30
+ method: "POST",
31
+ body: JSON.stringify({ context_session_id: t, title: e })
32
+ });
33
+ }
34
+ async listMessages(t) {
35
+ return (await this.request(`/conversations/${encodeURIComponent(t)}/messages`)).messages;
36
+ }
37
+ streamQuestion(t, e) {
38
+ return fetch(`${this.base()}/question/stream`, {
39
+ method: "POST",
40
+ headers: { "content-type": "application/json" },
41
+ body: JSON.stringify({ thread_id: t, question: e })
42
+ });
43
+ }
44
+ async request(t, e) {
45
+ const s = await fetch(`${this.base()}${t}`, {
46
+ ...e,
47
+ headers: { "content-type": "application/json", ...(e == null ? void 0 : e.headers) ?? {} }
48
+ }), r = await s.json();
49
+ if (!s.ok) throw new Error(r.message ?? "PageOps 请求失败");
50
+ return r;
51
+ }
52
+ base() {
53
+ return this.options.apiBase.replace(/\/$/, "");
54
+ }
55
+ }
56
+ function w(n) {
57
+ return n.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
58
+ }
59
+ function m(n) {
60
+ return w(n).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
61
+ }
62
+ function x(n, t) {
63
+ const e = n[t], s = n[t + 1];
64
+ if (!(e != null && e.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s ?? "")) return null;
65
+ const r = [];
66
+ let i = t;
67
+ for (; i < n.length && n[i].includes("|") && n[i].trim(); )
68
+ r.push(n[i]), i += 1;
69
+ const d = (c) => c.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((o) => m(o.trim())), p = d(r[0]).map((c) => `<th>${c}</th>`).join(""), u = r.slice(2).map((c) => `<tr>${d(c).map((o) => `<td>${o}</td>`).join("")}</tr>`).join("");
70
+ return { html: `<table><thead><tr>${p}</tr></thead><tbody>${u}</tbody></table>`, next: i };
71
+ }
72
+ function b(n) {
73
+ const t = n.split(`
74
+ `), e = [];
75
+ for (let s = 0; s < t.length; s += 1) {
76
+ const r = x(t, s);
77
+ if (r) {
78
+ e.push(r.html), s = r.next - 1;
79
+ continue;
80
+ }
81
+ const i = t[s];
82
+ i.startsWith("### ") ? e.push(`<h4>${m(i.slice(4))}</h4>`) : i.startsWith("## ") ? e.push(`<h3>${m(i.slice(3))}</h3>`) : i.startsWith("# ") ? e.push(`<h2>${m(i.slice(2))}</h2>`) : i.startsWith("- ") ? e.push(`<li>${m(i.slice(2))}</li>`) : i.trim() ? e.push(`<p>${m(i)}</p>`) : e.push("<br>");
83
+ }
84
+ return e.join("");
85
+ }
86
+ async function S(n, t) {
87
+ var i, d;
88
+ const e = n.getReader(), s = new TextDecoder();
89
+ let r = "";
90
+ for (; ; ) {
91
+ const { done: p, value: u } = await e.read();
92
+ if (p) break;
93
+ r += s.decode(u, { stream: !0 });
94
+ const c = r.split(`
95
+
96
+ `);
97
+ r = c.pop() ?? "";
98
+ for (const o of c) {
99
+ const a = (i = o.match(/^event: (.+)$/m)) == null ? void 0 : i[1], h = (d = o.match(/^data: (.+)$/m)) == null ? void 0 : d[1];
100
+ a && h && t(a, JSON.parse(h));
101
+ }
102
+ }
103
+ }
104
+ class T {
105
+ constructor() {
106
+ l(this, "client", null);
107
+ l(this, "options", null);
108
+ l(this, "root", null);
109
+ l(this, "panel", null);
110
+ l(this, "context", null);
111
+ l(this, "currentThread", null);
112
+ l(this, "conversations", []);
113
+ l(this, "messages", []);
114
+ l(this, "steps", []);
115
+ l(this, "streaming", "");
116
+ }
117
+ mount(t) {
118
+ this.unmount(), this.options = t, this.client = new v(t), this.root = document.createElement("div"), this.root.className = "pageops-sdk", (t.container ?? document.body).appendChild(this.root), this.renderClosed();
119
+ }
120
+ unmount() {
121
+ var t;
122
+ (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 = "";
123
+ }
124
+ open() {
125
+ this.root && (this.root.innerHTML = "", this.panel = document.createElement("div"), this.panel.className = "po-panel", this.root.appendChild(this.panel), this.loadConversations(), this.renderPanel());
126
+ }
127
+ close() {
128
+ this.renderClosed();
129
+ }
130
+ updateContext(t) {
131
+ this.options && (this.options = { ...this.options, ...t }, this.client = new v(this.options));
132
+ }
133
+ renderClosed() {
134
+ var t;
135
+ this.root && (this.root.innerHTML = '<button class="po-fab" type="button">多轮问答</button>', (t = this.root.querySelector("button")) == null || t.addEventListener("click", () => this.open()));
136
+ }
137
+ async ensureContext() {
138
+ if (this.context) return this.context;
139
+ if (!this.client) throw new Error("PageOps SDK 未初始化");
140
+ return this.context = await this.client.createContext(), this.context;
141
+ }
142
+ async loadConversations() {
143
+ this.client && (this.conversations = await this.client.listConversations(), this.renderPanel());
144
+ }
145
+ async newConversation() {
146
+ if (!this.client) return;
147
+ const t = await this.ensureContext();
148
+ 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();
149
+ }
150
+ async selectThread(t) {
151
+ this.client && (this.currentThread = t, this.messages = await this.client.listMessages(t.id), this.steps = [], this.streaming = "", this.renderPanel());
152
+ }
153
+ async ask(t) {
154
+ if (!this.client || (this.currentThread || await this.newConversation(), !this.currentThread)) return;
155
+ this.messages.push({ id: `local-${Date.now()}`, role: "user", content: t, metadata_json: {} }), this.steps = [], this.streaming = "", this.renderPanel();
156
+ const e = await this.client.streamQuestion(this.currentThread.id, t);
157
+ if (!e.ok || !e.body) throw new Error("PageOps 流式问答失败");
158
+ await S(e.body, (s, r) => {
159
+ s === "step" && this.upsertStep(r), s === "delta" && (this.streaming += String(r.content ?? "")), s === "done" && this.selectThread(this.currentThread), s === "error" && this.upsertStep({ id: "error", title: "执行失败", status: "failed", details: r }), this.renderPanel();
160
+ });
161
+ }
162
+ upsertStep(t) {
163
+ const e = this.steps.findIndex((s) => s.id === t.id);
164
+ this.steps = e === -1 ? [...this.steps, t] : this.steps.map((s) => s.id === t.id ? { ...s, ...t } : s);
165
+ }
166
+ renderPanel() {
167
+ this.panel && (this.panel.innerHTML = `
168
+ <aside class="po-sidebar">
169
+ <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
170
+ <button class="po-new" data-action="new">+ 新建问答</button>
171
+ <input class="po-search" placeholder="搜索问答" />
172
+ <div class="po-thread-list">${this.conversations.map((t) => {
173
+ var e;
174
+ return `
175
+ <button class="po-thread ${t.id === ((e = this.currentThread) == null ? void 0 : e.id) ? "active" : ""}" data-thread="${t.id}">
176
+ <strong>${f(t.title)}</strong><span>${C(t.created_at)}</span>
177
+ </button>`;
178
+ }).join("")}</div>
179
+ </aside>
180
+ <main class="po-chat">
181
+ <header><div><p>问数回答</p><h2>${this.currentThread ? f(this.currentThread.title) : "未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
182
+ <section class="po-messages">
183
+ ${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("")}
184
+ ${this.streaming ? `<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${b(this.streaming)}</div></article>` : ""}
185
+ </section>
186
+ <form class="po-composer"><textarea placeholder="请输入页面分析问题,Enter 发送,Shift + Enter 换行"></textarea><button type="submit">发送</button></form>
187
+ </main>
188
+ <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSteps()}</section></aside>
189
+ `, this.bindPanelEvents());
190
+ }
191
+ renderSteps() {
192
+ return (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", details: { message: "发送消息后展示执行过程。" } }]).map((e) => `<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(e.details ?? {}, null, 2))}</pre></details>`).join("");
193
+ }
194
+ bindPanelEvents() {
195
+ var t, e, s, r, i, d, p, u, c;
196
+ (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()), (i = this.panel) == null || i.querySelectorAll("[data-thread]").forEach((o) => {
197
+ o.addEventListener("click", () => {
198
+ const a = this.conversations.find((h) => h.id === o.dataset.thread);
199
+ a && this.selectThread(a);
200
+ });
201
+ }), (p = (d = this.panel) == null ? void 0 : d.querySelector("form")) == null || p.addEventListener("submit", (o) => {
202
+ var g;
203
+ o.preventDefault();
204
+ const a = (g = this.panel) == null ? void 0 : g.querySelector("textarea"), h = a == null ? void 0 : a.value.trim();
205
+ h && (a.value = "", this.ask(h));
206
+ }), (c = (u = this.panel) == null ? void 0 : u.querySelector("textarea")) == null || c.addEventListener("keydown", (o) => {
207
+ var h, g;
208
+ const a = o;
209
+ a.key === "Enter" && !a.shiftKey && (a.preventDefault(), (g = (h = this.panel) == null ? void 0 : h.querySelector("form")) == null || g.requestSubmit());
210
+ });
211
+ }
212
+ }
213
+ function f(n) {
214
+ return n.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
215
+ }
216
+ function C(n) {
217
+ return new Intl.DateTimeFormat("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(new Date(n));
218
+ }
219
+ const E = new T();
220
+ export {
221
+ E as PageOpsSDK
222
+ };
@@ -0,0 +1,23 @@
1
+ (function(l,o){typeof exports=="object"&&typeof module<"u"?o(exports):typeof define=="function"&&define.amd?define(["exports"],o):(l=typeof globalThis<"u"?globalThis:l||self,o(l.PageOpsSDK={}))})(this,(function(l){"use strict";var C=Object.defineProperty;var O=(l,o,m)=>o in l?C(l,o,{enumerable:!0,configurable:!0,writable:!0,value:m}):l[o]=m;var d=(l,o,m)=>O(l,typeof o!="symbol"?o+"":o,m);class o{constructor(t){this.options=t}async createContext(){var e,s;const t=((s=(e=this.options).getPageContext)==null?void 0:s.call(e))??{};return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:t.route,url:t.url??location.href,title:t.title??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){const s=await fetch(`${this.base()}${t}`,{...e,headers:{"content-type":"application/json",...(e==null?void 0:e.headers)??{}}}),i=await s.json();if(!s.ok)throw new Error(i.message??"PageOps 请求失败");return i}base(){return this.options.apiBase.replace(/\/$/,"")}}function m(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function f(r){return m(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??""))return null;const i=[];let n=t;for(;n<r.length&&r[n].includes("|")&&r[n].trim();)i.push(r[n]),n+=1;const u=h=>h.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(c=>f(c.trim())),g=u(i[0]).map(h=>`<th>${h}</th>`).join(""),v=i.slice(2).map(h=>`<tr>${u(h).map(c=>`<td>${c}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${g}</tr></thead><tbody>${v}</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>${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>")}return e.join("")}async function S(r,t){var n,u;const e=r.getReader(),s=new TextDecoder;let i="";for(;;){const{done:g,value:v}=await e.read();if(g)break;i+=s.decode(v,{stream:!0});const h=i.split(`
3
+
4
+ `);i=h.pop()??"";for(const c of h){const a=(n=c.match(/^event: (.+)$/m))==null?void 0:n[1],p=(u=c.match(/^data: (.+)$/m))==null?void 0:u[1];a&&p&&t(a,JSON.parse(p))}}}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){this.unmount(),this.options=t,this.client=new o(t),this.root=document.createElement("div"),this.root.className="pageops-sdk",(t.container??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)=>{s==="step"&&this.upsertStep(i),s==="delta"&&(this.streaming+=String(i.content??"")),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=`
5
+ <aside class="po-sidebar">
6
+ <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
7
+ <button class="po-new" data-action="new">+ 新建问答</button>
8
+ <input class="po-search" placeholder="搜索问答" />
9
+ <div class="po-thread-list">${this.conversations.map(t=>{var e;return`
10
+ <button class="po-thread ${t.id===((e=this.currentThread)==null?void 0:e.id)?"active":""}" data-thread="${t.id}">
11
+ <strong>${b(t.title)}</strong><span>${T(t.created_at)}</span>
12
+ </button>`}).join("")}</div>
13
+ </aside>
14
+ <main class="po-chat">
15
+ <header><div><p>问数回答</p><h2>${this.currentThread?b(this.currentThread.title):"未选择问答"}</h2></div><span>Markdown · 流式输出</span></header>
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):b(t.content)}</div></article>`).join("")}
18
+ ${this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div>${$(this.streaming)}</div></article>`:""}
19
+ </section>
20
+ <form class="po-composer"><textarea placeholder="请输入页面分析问题,Enter 发送,Shift + Enter 换行"></textarea><button type="submit">发送</button></form>
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=>`<details class="po-step ${e.status}" ${e.status==="running"||e.status==="failed"?"open":""}><summary><strong>${b(e.title)}</strong><span>${e.status}</span></summary><pre>${b(JSON.stringify(e.details??{},null,2))}</pre></details>`).join("")}bindPanelEvents(){var t,e,s,i,n,u,g,v,h;(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(c=>{c.addEventListener("click",()=>{const a=this.conversations.find(p=>p.id===c.dataset.thread);a&&this.selectThread(a)})}),(g=(u=this.panel)==null?void 0:u.querySelector("form"))==null||g.addEventListener("submit",c=>{var y;c.preventDefault();const a=(y=this.panel)==null?void 0:y.querySelector("textarea"),p=a==null?void 0:a.value.trim();p&&(a.value="",this.ask(p))}),(h=(v=this.panel)==null?void 0:v.querySelector("textarea"))==null||h.addEventListener("keydown",c=>{var p,y;const a=c;a.key==="Enter"&&!a.shiftKey&&(a.preventDefault(),(y=(p=this.panel)==null?void 0:p.querySelector("form"))==null||y.requestSubmit())})}}function b(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;l.PageOpsSDK=P,Object.defineProperty(l,Symbol.toStringTag,{value:"Module"})}));
@@ -0,0 +1,2 @@
1
+ export type StreamHandler = (event: string, data: any) => void;
2
+ export declare function readEventStream(body: ReadableStream<Uint8Array>, handler: StreamHandler): Promise<void>;
@@ -0,0 +1,51 @@
1
+ export interface PageOpsContext {
2
+ route?: string;
3
+ url?: string;
4
+ title?: string;
5
+ tenantId?: string;
6
+ userRole?: string;
7
+ buildVersion?: string;
8
+ }
9
+ export interface PageOpsMountOptions {
10
+ apiBase: string;
11
+ appId: string;
12
+ env: string;
13
+ getPageContext?: () => PageOpsContext;
14
+ container?: HTMLElement;
15
+ }
16
+ export interface ContextSession {
17
+ id: string;
18
+ app_id: string;
19
+ env: string;
20
+ route?: string;
21
+ url?: string;
22
+ title?: string;
23
+ tenant_id?: string;
24
+ user_role?: string;
25
+ build_version?: string;
26
+ }
27
+ export interface ConversationThread {
28
+ id: string;
29
+ context_session_id: string;
30
+ title: string;
31
+ created_at: string;
32
+ }
33
+ export interface ConversationMessage {
34
+ id: string;
35
+ role: string;
36
+ content: string;
37
+ evidence_bundle_id?: string | null;
38
+ metadata_json: Record<string, unknown>;
39
+ }
40
+ export interface ExecutionStep {
41
+ id: string;
42
+ title: string;
43
+ status: 'pending' | 'running' | 'completed' | 'failed';
44
+ details?: Record<string, unknown>;
45
+ }
46
+ export interface StreamDonePayload {
47
+ message_id: string;
48
+ answer: Record<string, unknown>;
49
+ bundle_id: string;
50
+ llm: Record<string, unknown>;
51
+ }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@pageops/sdk",
3
+ "version": "0.1.0",
4
+ "description": "PageOps embeddable frontend SDK",
5
+ "type": "module",
6
+ "main": "dist/pageops-sdk.umd.cjs",
7
+ "module": "dist/pageops-sdk.es.js",
8
+ "types": "dist/index.d.ts",
9
+ "style": "dist/pageops-sdk.css",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "import": "./dist/pageops-sdk.es.js",
14
+ "require": "./dist/pageops-sdk.umd.cjs"
15
+ },
16
+ "./dist/pageops-sdk.css": "./dist/pageops-sdk.css"
17
+ },
18
+ "files": ["dist"],
19
+ "scripts": {
20
+ "build": "vite build && tsc --emitDeclarationOnly",
21
+ "pack:check": "npm pack --dry-run"
22
+ },
23
+ "dependencies": {},
24
+ "devDependencies": {
25
+ "@types/node": "22.10.2",
26
+ "typescript": "5.8.3",
27
+ "vite": "6.3.5"
28
+ },
29
+ "engines": {
30
+ "node": ">=20"
31
+ }
32
+ }