@pageops/sdk 0.1.12 → 0.1.13

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, PageOpsContext, PageOpsMountOptions, SourceSnapshot } from './types';
1
+ import type { AgentRunHistory, ContextSession, ConversationMessage, ConversationThread, PageOpsContext, PageOpsMountOptions, SourceSnapshot } from './types';
2
2
  export declare class PageOpsClient {
3
3
  private options;
4
4
  constructor(options: PageOpsMountOptions);
@@ -7,6 +7,7 @@ export declare class PageOpsClient {
7
7
  createConversation(contextSessionId: string, title?: string): Promise<ConversationThread>;
8
8
  deleteConversation(threadId: string): Promise<void>;
9
9
  listMessages(threadId: string): Promise<ConversationMessage[]>;
10
+ getAgentRun(runId: string): Promise<AgentRunHistory>;
10
11
  listSources(): Promise<SourceSnapshot[]>;
11
12
  uploadSource(file: File): Promise<SourceSnapshot>;
12
13
  streamQuestion(threadId: string, question: string, signal?: AbortSignal): Promise<Response>;
package/dist/index.d.ts CHANGED
@@ -12,6 +12,11 @@ declare class PageOpsSDKController {
12
12
  private conversations;
13
13
  private messages;
14
14
  private steps;
15
+ private selectedAgentRunId;
16
+ private runLoading;
17
+ private runLoadError;
18
+ private copiedAgentRunId;
19
+ private copyFeedbackTimer;
15
20
  private sourceSnapshots;
16
21
  private sourceUploadStatus;
17
22
  private sourceUploadError;
@@ -58,6 +63,9 @@ declare class PageOpsSDKController {
58
63
  private updateStreamingMessage;
59
64
  private resetAnswerState;
60
65
  private upsertStep;
66
+ private loadAgentRun;
67
+ private copyAgentRunId;
68
+ private clearCopyFeedback;
61
69
  private latestAnalysisStatus;
62
70
  private isProjectMemoryUpdating;
63
71
  private questionUnavailableReason;
@@ -65,6 +73,7 @@ declare class PageOpsSDKController {
65
73
  private stopSourceRefresh;
66
74
  private renderPanel;
67
75
  private renderAnswerState;
76
+ private renderMessage;
68
77
  private renderSourceUploader;
69
78
  private renderSourceItem;
70
79
  private renderSteps;
@@ -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-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:0}.po-chat-title{min-width:0}.po-chat-title h2{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.po-audience{display:flex;flex:0 0 auto;align-items:center;gap:8px}.po-audience>span{white-space:nowrap}.po-audience-options{display:grid;grid-template-columns:repeat(4,44px);height:32px;overflow:hidden;border:1px solid #cbd5e1;border-radius:6px;background:#f8fafc}.po-audience-options button{min-width:0;border:0;border-right:1px solid #e2e8f0;background:transparent;color:#475569;padding:0 8px;font-size:12px;font-weight:650}.po-audience-options button:last-child{border-right:0}.po-audience-options button[aria-pressed=true]{background:var(--po-primary);color:#fff}.po-audience-options button:disabled{cursor:not-allowed;opacity:.55}.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-chat header{align-items:flex-start;flex-wrap:wrap}.po-audience{width:100%;justify-content:space-between}.po-message{max-width:94%}}@media(prefers-reduced-motion:reduce){.po-ai-spinner,.po-typing-cursor{animation:none}}
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:0}.po-chat-title{min-width:0}.po-chat-title h2{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.po-audience{display:flex;flex:0 0 auto;align-items:center;gap:8px}.po-audience>span{white-space:nowrap}.po-audience-options{display:grid;grid-template-columns:repeat(4,44px);height:32px;overflow:hidden;border:1px solid #cbd5e1;border-radius:6px;background:#f8fafc}.po-audience-options button{min-width:0;border:0;border-right:1px solid #e2e8f0;background:transparent;color:#475569;padding:0 8px;font-size:12px;font-weight:650}.po-audience-options button:last-child{border-right:0}.po-audience-options button[aria-pressed=true]{background:var(--po-primary);color:#fff}.po-audience-options button:disabled{cursor:not-allowed;opacity:.55}.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.run-selected{border-color:#93c5fd;box-shadow:0 0 0 2px #3b82f614}.po-answer-meta{display:flex;min-width:0;align-items:center;flex-wrap:wrap;gap:6px 10px;border-top:1px solid var(--po-soft-border);margin-top:5px;padding-top:8px;color:var(--po-muted);font-size:11px}.po-answer-meta.selected{color:#1d4ed8}.po-run-id{display:flex;min-width:0;max-width:100%;align-items:center;gap:5px}.po-run-id code{display:block;max-width:148px;overflow:hidden;background:transparent;color:inherit;padding:0;text-overflow:ellipsis;white-space:nowrap}.po-answer-meta button{border:0;background:transparent;color:var(--po-primary-dark);padding:2px 0;font-size:11px;font-weight:700}.po-answer-meta button:hover{text-decoration:underline}.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:8px;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:grid;grid-template-columns:9px minmax(0,1fr) auto;align-items:start;gap:9px;cursor:pointer}.po-step summary::marker{display:none;content:""}.po-step[data-static] summary{cursor:default}.po-step-dot{width:8px;height:8px;margin-top:5px;border:2px solid #94a3b8;border-radius:50%;background:#fff}.po-step.running .po-step-dot{border-color:#2563eb;animation:po-step-pulse 1.2s ease-in-out infinite}.po-step.completed .po-step-dot{border-color:#16a34a;background:#16a34a}.po-step.failed .po-step-dot{border-color:#dc2626;background:#dc2626}.po-step-copy{display:grid;min-width:0;gap:4px}.po-step-copy strong{font-size:13px}.po-step-copy small{color:var(--po-muted);font-size:12px;font-weight:500;line-height:1.45}.po-step-status{color:var(--po-muted);font-size:11px;white-space:nowrap}.po-step-metrics{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0 0 18px}.po-step-metrics span{border:1px solid #dbeafe;border-radius:4px;background:#f8fbff;color:#475569;padding:2px 6px;font-size:11px}.po-step-details{display:grid;gap:8px;margin:10px 0 0 18px;border-top:1px solid var(--po-soft-border);padding-top:9px}.po-step-details div{display:grid;gap:3px}.po-step-details span{color:var(--po-muted);font-size:11px}.po-step-details p{overflow-wrap:anywhere;margin:0;color:#334155;font-size:12px;line-height:1.5;white-space:pre-wrap}.po-trace-state{display:flex;align-items:center;gap:8px;border:1px solid var(--po-soft-border);border-radius:8px;background:#fff;color:var(--po-muted);padding:12px;font-size:12px}.po-trace-state.failed{border-color:#fecaca;color:#b91c1c}@keyframes po-step-pulse{50%{opacity:.35}}@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-chat header{align-items:flex-start;flex-wrap:wrap}.po-audience{width:100%;justify-content:space-between}.po-message{max-width:94%}}@media(prefers-reduced-motion:reduce){.po-ai-spinner,.po-step-dot,.po-typing-cursor{animation:none}}
@@ -1,21 +1,21 @@
1
- var x = Object.defineProperty;
2
- var k = (a, e, t) => e in a ? x(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
3
- var o = (a, e, t) => k(a, typeof e != "symbol" ? e + "" : e, t);
4
- class P {
1
+ var L = Object.defineProperty;
2
+ var q = (a, e, t) => e in a ? L(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
3
+ var r = (a, e, t) => q(a, typeof e != "symbol" ? e + "" : e, t);
4
+ class R {
5
5
  constructor(e) {
6
6
  this.options = e;
7
7
  }
8
8
  async createContext(e = ((i) => (i = ((t) => ((s) => (s = (t = this.options).getPageContext) == null ? void 0 : s.call(t))())()) != null ? i : {})()) {
9
- var r, l, n;
9
+ var n, c, o;
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: e.route,
16
- url: (r = e.url) != null ? r : location.href,
17
- title: (l = e.title) != null ? l : document.title,
18
- menu_path: (n = e.menuPath) != null ? n : [],
16
+ url: (n = e.url) != null ? n : location.href,
17
+ title: (c = e.title) != null ? c : document.title,
18
+ menu_path: (o = e.menuPath) != null ? o : [],
19
19
  tenant_id: e.tenantId,
20
20
  user_role: e.userRole,
21
21
  build_version: e.buildVersion
@@ -39,6 +39,9 @@ class P {
39
39
  async listMessages(e) {
40
40
  return (await this.request(`/conversations/${encodeURIComponent(e)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages;
41
41
  }
42
+ async getAgentRun(e) {
43
+ return this.request(`/question/runs/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`);
44
+ }
42
45
  async listSources() {
43
46
  return (await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources;
44
47
  }
@@ -55,87 +58,87 @@ class P {
55
58
  });
56
59
  }
57
60
  async request(e, t) {
58
- var l, n;
59
- const s = (t == null ? void 0 : t.body) instanceof FormData ? t.headers : { "content-type": "application/json", ...(l = t == null ? void 0 : t.headers) != null ? l : {} }, i = await fetch(`${this.base()}${e}`, { ...t, headers: s });
61
+ var c, o;
62
+ const s = (t == null ? void 0 : t.body) instanceof FormData ? t.headers : { "content-type": "application/json", ...(c = t == null ? void 0 : t.headers) != null ? c : {} }, i = await fetch(`${this.base()}${e}`, { ...t, headers: s });
60
63
  if (i.status === 204) return;
61
- const r = await i.json();
62
- if (!i.ok) throw new Error((n = r.message) != null ? n : "PageOps 请求失败");
63
- return r;
64
+ const n = await i.json();
65
+ if (!i.ok) throw new Error((o = n.message) != null ? o : "PageOps 请求失败");
66
+ return n;
64
67
  }
65
68
  base() {
66
69
  const e = this.options.apiBase.replace(/\/$/, "");
67
70
  return e.endsWith("/api") ? e : `${e}/api`;
68
71
  }
69
72
  }
70
- async function R(a, e) {
73
+ async function U(a, e) {
71
74
  const t = await a.json().catch(() => null);
72
75
  return typeof (t == null ? void 0 : t.message) == "string" && t.message.trim() ? t.message : e;
73
76
  }
74
- function I(a) {
77
+ function x(a) {
75
78
  return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
76
79
  }
77
80
  function v(a) {
78
- return I(a).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
81
+ return x(a).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
79
82
  }
80
- function q(a, e) {
83
+ function F(a, e) {
81
84
  const t = a[e], s = a[e + 1];
82
85
  if (!(t != null && t.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
83
86
  const i = [];
84
- let r = e;
85
- for (; r < a.length && a[r].includes("|") && a[r].trim(); )
86
- i.push(a[r]), r += 1;
87
- const l = (p) => p.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((f) => v(f.trim())), n = l(i[0]).map((p) => `<th>${p}</th>`).join(""), d = i.slice(2).map((p) => `<tr>${l(p).map((f) => `<td>${f}</td>`).join("")}</tr>`).join("");
88
- return { html: `<table><thead><tr>${n}</tr></thead><tbody>${d}</tbody></table>`, next: r };
87
+ let n = e;
88
+ for (; n < a.length && a[n].includes("|") && a[n].trim(); )
89
+ i.push(a[n]), n += 1;
90
+ const c = (g) => g.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((f) => v(f.trim())), o = c(i[0]).map((g) => `<th>${g}</th>`).join(""), p = i.slice(2).map((g) => `<tr>${c(g).map((f) => `<td>${f}</td>`).join("")}</tr>`).join("");
91
+ return { html: `<table><thead><tr>${o}</tr></thead><tbody>${p}</tbody></table>`, next: n };
89
92
  }
90
- function w(a) {
93
+ function y(a) {
91
94
  const e = a.split(`
92
95
  `), t = [];
93
96
  for (let s = 0; s < e.length; s += 1) {
94
97
  const i = e[s];
95
98
  if (i.trim().startsWith("```")) {
96
- const l = [];
99
+ const c = [];
97
100
  for (s += 1; s < e.length && !e[s].trim().startsWith("```"); )
98
- l.push(e[s]), s += 1;
99
- t.push(`<pre><code>${I(l.join(`
101
+ c.push(e[s]), s += 1;
102
+ t.push(`<pre><code>${x(c.join(`
100
103
  `))}</code></pre>`);
101
104
  continue;
102
105
  }
103
- const r = q(e, s);
104
- if (r) {
105
- t.push(r.html), s = r.next - 1;
106
+ const n = F(e, s);
107
+ if (n) {
108
+ t.push(n.html), s = n.next - 1;
106
109
  continue;
107
110
  }
108
111
  i.startsWith("### ") ? t.push(`<h4>${v(i.slice(4))}</h4>`) : i.startsWith("## ") ? t.push(`<h3>${v(i.slice(3))}</h3>`) : i.startsWith("# ") ? t.push(`<h2>${v(i.slice(2))}</h2>`) : i.startsWith("- ") ? t.push(`<li>${v(i.slice(2))}</li>`) : i.trim() ? t.push(`<p>${v(i)}</p>`) : t.push("<br>");
109
112
  }
110
113
  return t.join("");
111
114
  }
112
- async function U(a, e) {
113
- var r;
115
+ async function K(a, e) {
116
+ var n;
114
117
  const t = a.getReader(), s = new TextDecoder();
115
118
  let i = "";
116
119
  for (; ; ) {
117
- const { done: l, value: n } = await t.read();
118
- if (l) {
120
+ const { done: c, value: o } = await t.read();
121
+ if (c) {
119
122
  i += s.decode();
120
123
  break;
121
124
  }
122
- i += s.decode(n, { stream: !0 });
123
- const d = i.split(/\r?\n\r?\n/);
124
- i = (r = d.pop()) != null ? r : "";
125
- for (const p of d) T(p, e);
125
+ i += s.decode(o, { stream: !0 });
126
+ const p = i.split(/\r?\n\r?\n/);
127
+ i = (n = p.pop()) != null ? n : "";
128
+ for (const g of p) I(g, e);
126
129
  }
127
- i.trim() && T(i, e);
130
+ i.trim() && I(i, e);
128
131
  }
129
- function T(a, e) {
130
- var i, r;
131
- const t = (i = a.match(/^event:\s*(.+)$/m)) == null ? void 0 : i[1], s = (r = a.match(/^data:\s*(.+)$/m)) == null ? void 0 : r[1];
132
+ function I(a, e) {
133
+ var i, n;
134
+ const t = (i = a.match(/^event:\s*(.+)$/m)) == null ? void 0 : i[1], s = (n = a.match(/^data:\s*(.+)$/m)) == null ? void 0 : n[1];
132
135
  t && s && e(t, JSON.parse(s));
133
136
  }
134
- class K {
137
+ class _ {
135
138
  constructor(e, t = 16) {
136
- o(this, "queue", []);
137
- o(this, "timer", null);
138
- o(this, "drainWaiters", []);
139
+ r(this, "queue", []);
140
+ r(this, "timer", null);
141
+ r(this, "drainWaiters", []);
139
142
  this.onChunk = e, this.interval = t;
140
143
  }
141
144
  enqueue(e) {
@@ -159,56 +162,61 @@ class K {
159
162
  for (const e of this.drainWaiters.splice(0)) e();
160
163
  }
161
164
  }
162
- const y = [
165
+ const w = [
163
166
  { value: "product", label: "产品" },
164
167
  { value: "business", label: "业务" },
165
168
  { value: "developer", label: "研发" },
166
169
  { value: "tester", label: "测试" }
167
170
  ];
168
- class F {
171
+ class j {
169
172
  constructor() {
170
- o(this, "client", null);
171
- o(this, "options", null);
172
- o(this, "root", null);
173
- o(this, "panel", null);
174
- o(this, "context", null);
175
- o(this, "contextKey", "");
176
- o(this, "selectedPageKey", "");
177
- o(this, "currentThread", null);
178
- o(this, "conversations", []);
179
- o(this, "messages", []);
180
- o(this, "steps", []);
181
- o(this, "sourceSnapshots", []);
182
- o(this, "sourceUploadStatus", "");
183
- o(this, "sourceUploadError", "");
184
- o(this, "sourceLoadError", "");
185
- o(this, "sourceUploading", !1);
186
- o(this, "sourceRefreshTimer", null);
187
- o(this, "streaming", "");
188
- o(this, "asking", !1);
189
- o(this, "waitingForFirstContent", !1);
190
- o(this, "abortController", null);
191
- o(this, "activeRunId", 0);
192
- o(this, "stoppedRunId", -1);
193
- o(this, "answerStopped", !1);
194
- o(this, "answerError", "");
195
- o(this, "conversationError", "");
196
- o(this, "deletingThreadId", "");
197
- o(this, "streamFailure", "");
198
- o(this, "streamDone", null);
199
- o(this, "answerAudience", "business");
200
- o(this, "audienceChanging", !1);
201
- o(this, "typewriter", new K((e) => {
173
+ r(this, "client", null);
174
+ r(this, "options", null);
175
+ r(this, "root", null);
176
+ r(this, "panel", null);
177
+ r(this, "context", null);
178
+ r(this, "contextKey", "");
179
+ r(this, "selectedPageKey", "");
180
+ r(this, "currentThread", null);
181
+ r(this, "conversations", []);
182
+ r(this, "messages", []);
183
+ r(this, "steps", []);
184
+ r(this, "selectedAgentRunId", "");
185
+ r(this, "runLoading", !1);
186
+ r(this, "runLoadError", "");
187
+ r(this, "copiedAgentRunId", "");
188
+ r(this, "copyFeedbackTimer", null);
189
+ r(this, "sourceSnapshots", []);
190
+ r(this, "sourceUploadStatus", "");
191
+ r(this, "sourceUploadError", "");
192
+ r(this, "sourceLoadError", "");
193
+ r(this, "sourceUploading", !1);
194
+ r(this, "sourceRefreshTimer", null);
195
+ r(this, "streaming", "");
196
+ r(this, "asking", !1);
197
+ r(this, "waitingForFirstContent", !1);
198
+ r(this, "abortController", null);
199
+ r(this, "activeRunId", 0);
200
+ r(this, "stoppedRunId", -1);
201
+ r(this, "answerStopped", !1);
202
+ r(this, "answerError", "");
203
+ r(this, "conversationError", "");
204
+ r(this, "deletingThreadId", "");
205
+ r(this, "streamFailure", "");
206
+ r(this, "streamDone", null);
207
+ r(this, "answerAudience", "business");
208
+ r(this, "audienceChanging", !1);
209
+ r(this, "typewriter", new _((e) => {
202
210
  this.streaming += e, this.updateStreamingMessage();
203
211
  }));
204
212
  }
205
213
  mount(e) {
206
214
  var t;
207
- this.unmount(), this.options = e, this.client = new P(e), this.answerAudience = this.loadAnswerAudience(e.appId), this.root = document.createElement("div"), this.root.className = "pageops-sdk", ((t = e.container) != null ? t : document.body).appendChild(this.root), this.renderClosed();
215
+ this.unmount(), this.options = e, this.client = new R(e), this.answerAudience = this.loadAnswerAudience(e.appId), this.root = document.createElement("div"), this.root.className = "pageops-sdk", ((t = e.container) != null ? t : document.body).appendChild(this.root), this.renderClosed();
208
216
  }
209
217
  unmount() {
210
218
  var e;
211
- this.stopSourceRefresh(), this.cancelActiveAnswer(!1), this.resetAnswerState(), (e = this.root) == null || e.remove(), this.root = null, this.panel = null, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.conversations = [], this.messages = [], this.steps = [], this.sourceSnapshots = [], this.sourceUploadStatus = "", this.sourceUploadError = "", this.sourceLoadError = "", this.sourceUploading = !1, this.answerAudience = "business", this.audienceChanging = !1;
219
+ this.stopSourceRefresh(), this.cancelActiveAnswer(!1), this.resetAnswerState(), (e = this.root) == null || e.remove(), this.root = null, this.panel = null, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.conversations = [], this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoading = !1, this.runLoadError = "", this.clearCopyFeedback(), this.sourceSnapshots = [], this.sourceUploadStatus = "", this.sourceUploadError = "", this.sourceLoadError = "", this.sourceUploading = !1, this.answerAudience = "business", this.audienceChanging = !1;
212
220
  }
213
221
  open() {
214
222
  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());
@@ -219,7 +227,7 @@ class F {
219
227
  updateContext(e) {
220
228
  if (!this.options) return;
221
229
  const t = this.options.appId;
222
- this.options = { ...this.options, ...e }, this.client = new P(this.options), this.options.appId !== t && (this.answerAudience = this.loadAnswerAudience(this.options.appId), this.currentThread = null, this.selectedPageKey = "", this.messages = [], this.steps = []), this.context = null, this.contextKey = "", this.renderPanel();
230
+ this.options = { ...this.options, ...e }, this.client = new R(this.options), this.options.appId !== t && (this.answerAudience = this.loadAnswerAudience(this.options.appId), this.currentThread = null, this.selectedPageKey = "", this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = ""), this.context = null, this.contextKey = "", this.renderPanel();
223
231
  }
224
232
  renderClosed() {
225
233
  var e;
@@ -243,7 +251,7 @@ class F {
243
251
  loadAnswerAudience(e) {
244
252
  try {
245
253
  const t = localStorage.getItem(this.answerAudienceStorageKey(e));
246
- return y.some((s) => s.value === t) ? t : "business";
254
+ return w.some((s) => s.value === t) ? t : "business";
247
255
  } catch (t) {
248
256
  return "business";
249
257
  }
@@ -258,9 +266,9 @@ class F {
258
266
  async changeAnswerAudience(e) {
259
267
  var s;
260
268
  if (this.asking || this.audienceChanging) return;
261
- const t = (s = y.find((i) => i.value === e)) == null ? void 0 : s.value;
269
+ const t = (s = w.find((i) => i.value === e)) == null ? void 0 : s.value;
262
270
  if (!(!t || t === this.answerAudience)) {
263
- this.answerAudience = t, this.saveAnswerAudience(), this.audienceChanging = !0, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.messages = [], this.steps = [], this.streaming = "", this.answerError = "", this.answerStopped = !1, this.conversationError = "", this.renderPanel();
271
+ this.answerAudience = t, this.saveAnswerAudience(), this.audienceChanging = !0, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.streaming = "", this.answerError = "", this.answerStopped = !1, this.conversationError = "", this.renderPanel();
264
272
  try {
265
273
  await this.newConversation();
266
274
  } catch (i) {
@@ -271,13 +279,13 @@ class F {
271
279
  }
272
280
  }
273
281
  getPageContextKey(e) {
274
- var t, s, i, r, l;
282
+ var t, s, i, n, c;
275
283
  return JSON.stringify([
276
284
  (t = e.route) != null ? t : "",
277
285
  (s = e.url) != null ? s : location.href,
278
286
  (i = e.title) != null ? i : document.title,
279
- (r = e.menuPath) != null ? r : [],
280
- (l = e.userRole) != null ? l : ""
287
+ (n = e.menuPath) != null ? n : [],
288
+ (c = e.userRole) != null ? c : ""
281
289
  ]);
282
290
  }
283
291
  async loadSources() {
@@ -300,7 +308,10 @@ class F {
300
308
  this.currentThread = await this.client.createConversation(e.id, t), this.selectedPageKey = this.contextKey, this.conversations = [this.currentThread, ...this.conversations], this.messages = [], this.steps = [], this.streaming = "", this.answerError = "", this.answerStopped = !1, this.renderPanel();
301
309
  }
302
310
  async selectThread(e) {
303
- this.client && (this.currentThread = e, this.selectedPageKey = this.getPageContextKey(this.getPageContext()), this.messages = await this.client.listMessages(e.id), this.steps = [], this.streaming = "", this.answerError = "", this.answerStopped = !1, this.renderPanel());
311
+ if (!this.client) return;
312
+ this.currentThread = e, this.selectedPageKey = this.getPageContextKey(this.getPageContext()), this.messages = await this.client.listMessages(e.id), this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.streaming = "", this.answerError = "", this.answerStopped = !1, this.renderPanel();
313
+ const t = [...this.messages].reverse().map(T).find(Boolean);
314
+ t && await this.loadAgentRun(t);
304
315
  }
305
316
  async deleteConversation(e) {
306
317
  var t;
@@ -308,7 +319,7 @@ class F {
308
319
  this.deletingThreadId = e.id, this.conversationError = "", this.renderPanel();
309
320
  try {
310
321
  if (await this.client.deleteConversation(e.id), this.conversations = this.conversations.filter((s) => s.id !== e.id), ((t = this.currentThread) == null ? void 0 : t.id) === e.id) {
311
- this.currentThread = null, this.messages = [], this.steps = [], this.streaming = "", this.answerError = "", this.answerStopped = !1;
322
+ this.currentThread = null, this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.streaming = "", this.answerError = "", this.answerStopped = !1;
312
323
  const s = this.conversations[0];
313
324
  s && await this.selectThread(s);
314
325
  }
@@ -342,20 +353,20 @@ class F {
342
353
  const s = ++this.activeRunId, i = new AbortController();
343
354
  this.abortController = i, this.stoppedRunId = -1, this.asking = !0, this.waitingForFirstContent = !0, this.renderPanel();
344
355
  try {
345
- const r = this.getPageContextKey(this.getPageContext());
346
- if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== r && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) throw new Error("无法创建问答会话,请稍后重试。");
347
- this.messages.push({ id: `local-${Date.now()}`, role: "user", content: e, metadata_json: {} }), this.steps = [], this.renderPanel();
348
- const l = await this.client.streamQuestion(this.currentThread.id, e, i.signal);
349
- if (!l.ok) throw new Error(await R(l, "服务暂时无法回答,请稍后重试。"));
350
- if (!l.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
351
- if (await U(l.body, (n, d) => this.handleStreamEvent(n, d)), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
356
+ const n = this.getPageContextKey(this.getPageContext());
357
+ if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== n && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) throw new Error("无法创建问答会话,请稍后重试。");
358
+ this.messages.push({ id: `local-${Date.now()}`, role: "user", content: e, metadata_json: {} }), this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.renderPanel();
359
+ const c = await this.client.streamQuestion(this.currentThread.id, e, i.signal);
360
+ if (!c.ok) throw new Error(await U(c, "服务暂时无法回答,请稍后重试。"));
361
+ if (!c.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
362
+ if (await K(c.body, (o, p) => this.handleStreamEvent(o, p)), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
352
363
  if (this.streamFailure) throw new Error(this.streamFailure);
353
364
  if (!this.streamDone) throw new Error("服务响应意外中断,请稍后重试。");
354
365
  if (await this.typewriter.drain(), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
355
366
  await this.selectThread(this.currentThread);
356
- } catch (r) {
367
+ } catch (n) {
357
368
  if (s !== this.activeRunId) return;
358
- 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 } }));
369
+ this.typewriter.clear(), this.waitingForFirstContent = !1, s === this.stoppedRunId ? this.answerStopped = !0 : (this.answerError = n instanceof Error ? n.message : "服务异常,请稍后重试。", this.upsertStep({ id: "error", title: "执行失败", status: "failed", summary: this.answerError }));
359
370
  } finally {
360
371
  if (s !== this.activeRunId) return;
361
372
  this.asking = !1, this.waitingForFirstContent = !1, this.abortController === i && (this.abortController = null), this.renderPanel(!0);
@@ -380,9 +391,9 @@ class F {
380
391
  return;
381
392
  }
382
393
  if (e === "delta") {
383
- const r = String((s = t.content) != null ? s : "");
384
- if (!r) return;
385
- this.waitingForFirstContent = !1, this.typewriter.enqueue(r);
394
+ const n = String((s = t.content) != null ? s : "");
395
+ if (!n) return;
396
+ this.waitingForFirstContent = !1, this.typewriter.enqueue(n);
386
397
  return;
387
398
  }
388
399
  e === "done" && (this.streamDone = t), e === "error" && (this.streamFailure = String((i = t.message) != null ? i : "服务异常,请稍后重试。"));
@@ -394,7 +405,7 @@ class F {
394
405
  this.renderPanel();
395
406
  return;
396
407
  }
397
- e.innerHTML = w(this.streaming);
408
+ e.innerHTML = y(this.streaming);
398
409
  const t = (i = this.panel) == null ? void 0 : i.querySelector(".po-messages");
399
410
  t && (t.scrollTop = t.scrollHeight);
400
411
  }
@@ -405,6 +416,43 @@ class F {
405
416
  const t = this.steps.findIndex((s) => s.id === e.id);
406
417
  this.steps = t === -1 ? [...this.steps, e] : this.steps.map((s) => s.id === e.id ? { ...s, ...e } : s);
407
418
  }
419
+ async loadAgentRun(e) {
420
+ if (!(!this.client || !e)) {
421
+ this.selectedAgentRunId = e, this.runLoading = !0, this.runLoadError = "", this.renderPanel();
422
+ try {
423
+ const t = await this.client.getAgentRun(e);
424
+ if (this.selectedAgentRunId !== e) return;
425
+ this.steps = t.steps;
426
+ } catch (t) {
427
+ if (this.selectedAgentRunId !== e) return;
428
+ this.steps = [], this.runLoadError = t instanceof Error ? t.message : "执行过程加载失败";
429
+ } finally {
430
+ this.selectedAgentRunId === e && (this.runLoading = !1, this.renderPanel());
431
+ }
432
+ }
433
+ }
434
+ async copyAgentRunId(e) {
435
+ var t;
436
+ if (e) {
437
+ try {
438
+ if ((t = navigator.clipboard) != null && t.writeText)
439
+ await navigator.clipboard.writeText(e);
440
+ else {
441
+ const s = document.createElement("textarea");
442
+ s.value = e, s.style.position = "fixed", s.style.opacity = "0", document.body.appendChild(s), s.select(), document.execCommand("copy"), s.remove();
443
+ }
444
+ this.copiedAgentRunId = e;
445
+ } catch (s) {
446
+ this.copiedAgentRunId = `error:${e}`;
447
+ }
448
+ this.clearCopyFeedback(!1), this.copyFeedbackTimer = setTimeout(() => {
449
+ this.copiedAgentRunId = "", this.copyFeedbackTimer = null, this.renderPanel();
450
+ }, 1800), this.renderPanel();
451
+ }
452
+ }
453
+ clearCopyFeedback(e = !0) {
454
+ this.copyFeedbackTimer && clearTimeout(this.copyFeedbackTimer), this.copyFeedbackTimer = null, e && (this.copiedAgentRunId = "");
455
+ }
408
456
  latestAnalysisStatus() {
409
457
  var e, t, s;
410
458
  return String((s = (t = (e = this.sourceSnapshots[0]) == null ? void 0 : e.metadata) == null ? void 0 : t.analysis_status) != null ? s : "");
@@ -423,44 +471,56 @@ class F {
423
471
  }
424
472
  renderPanel(e = this.asking) {
425
473
  if (!this.panel) return;
426
- const t = this.questionUnavailableReason(), s = t || (this.asking ? "回答生成中,请稍候" : "请输入页面分析问题,Enter 发送,Shift + Enter 换行"), i = !!(t || this.asking), r = 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>', l = y.map((n) => `
427
- <button type="button" data-audience="${n.value}" aria-pressed="${n.value === this.answerAudience}" ${this.asking || this.audienceChanging ? "disabled" : ""}>${n.label}</button>
474
+ const t = this.questionUnavailableReason(), s = t || (this.asking ? "回答生成中,请稍候" : "请输入页面分析问题,Enter 发送,Shift + Enter 换行"), i = !!(t || this.asking), n = 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>', c = w.map((o) => `
475
+ <button type="button" data-audience="${o.value}" aria-pressed="${o.value === this.answerAudience}" ${this.asking || this.audienceChanging ? "disabled" : ""}>${o.label}</button>
428
476
  `).join("");
429
477
  if (this.panel.innerHTML = `
430
478
  <aside class="po-sidebar">
431
479
  <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
432
480
  <button class="po-new" data-action="new" ${this.asking ? "disabled" : ""}>+ 新建问答</button>
433
481
  <input class="po-search" placeholder="搜索问答" />
434
- ${this.conversationError ? `<p class="po-conversation-error" role="alert">${c(this.conversationError)}</p>` : ""}
435
- <div class="po-thread-list">${this.conversations.map((n) => {
436
- var d;
482
+ ${this.conversationError ? `<p class="po-conversation-error" role="alert">${l(this.conversationError)}</p>` : ""}
483
+ <div class="po-thread-list">${this.conversations.map((o) => {
484
+ var p;
437
485
  return `
438
- <div class="po-thread-row ${n.id === ((d = this.currentThread) == null ? void 0 : d.id) ? "active" : ""}">
439
- <button class="po-thread" data-thread="${c(n.id)}" ${this.asking ? "disabled" : ""}>
440
- <strong>${c(n.title)}</strong><span>${A(n.created_at)}</span>
486
+ <div class="po-thread-row ${o.id === ((p = this.currentThread) == null ? void 0 : p.id) ? "active" : ""}">
487
+ <button class="po-thread" data-thread="${l(o.id)}" ${this.asking ? "disabled" : ""}>
488
+ <strong>${l(o.title)}</strong><span>${k(o.created_at)}</span>
441
489
  </button>
442
- <button class="po-thread-delete" type="button" data-delete-thread="${c(n.id)}" aria-label="删除会话:${c(n.title)}" title="删除会话" ${this.asking || this.deletingThreadId === n.id ? "disabled" : ""}><span class="po-trash-icon" aria-hidden="true"></span></button>
490
+ <button class="po-thread-delete" type="button" data-delete-thread="${l(o.id)}" aria-label="删除会话:${l(o.title)}" title="删除会话" ${this.asking || this.deletingThreadId === o.id ? "disabled" : ""}><span class="po-trash-icon" aria-hidden="true"></span></button>
443
491
  </div>`;
444
492
  }).join("")}</div>
445
493
  </aside>
446
494
  <main class="po-chat">
447
- <header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread ? c(this.currentThread.title) : "未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${l}</div></div></header>
495
+ <header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread ? l(this.currentThread.title) : "未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${c}</div></div></header>
448
496
  <section class="po-messages">
449
- ${this.messages.map((n) => `<article class="po-message ${n.role}"><b>${n.role === "user" ? "你" : "PageOps 分析"}</b><div>${n.role === "assistant" ? w(n.content) : c(n.content)}</div></article>`).join("")}
497
+ ${this.messages.map((o) => this.renderMessage(o)).join("")}
450
498
  ${this.renderAnswerState()}
451
499
  </section>
452
- <form class="po-composer"><textarea ${i ? "disabled" : ""} placeholder="${c(s)}"></textarea>${r}</form>
500
+ <form class="po-composer"><textarea ${i ? "disabled" : ""} placeholder="${l(s)}"></textarea>${n}</form>
453
501
  </main>
454
502
  <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
455
503
  `, this.bindPanelEvents(), e) {
456
- const n = this.panel.querySelector(".po-messages");
457
- n && (n.scrollTop = n.scrollHeight);
504
+ const o = this.panel.querySelector(".po-messages");
505
+ o && (o.scrollTop = o.scrollHeight);
458
506
  }
459
507
  }
460
508
  renderAnswerState() {
461
- const e = this.asking && this.waitingForFirstContent ? '<article class="po-message assistant waiting" role="status" aria-live="polite"><b>PageOps 分析</b><div class="po-ai-waiting"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在理解问题并检索证据</span></div></article>' : "", t = this.streaming ? `<article class="po-message assistant streaming"><b>PageOps 分析</b><div><span data-streaming-content>${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>${c(this.answerError)}</div></article>` : "", i = this.answerStopped ? '<div class="po-stream-stopped" role="status">已停止输出</div>' : "";
509
+ const e = this.asking && this.waitingForFirstContent ? '<article class="po-message assistant waiting" role="status" aria-live="polite"><b>PageOps 分析</b><div class="po-ai-waiting"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在理解问题并检索证据</span></div></article>' : "", t = this.streaming ? `<article class="po-message assistant streaming"><b>PageOps 分析</b><div><span data-streaming-content>${y(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>' : "";
462
510
  return `${e}${t}${i}${s}`;
463
511
  }
512
+ renderMessage(e) {
513
+ const t = T(e), s = t && t === this.selectedAgentRunId, i = this.copiedAgentRunId === t, n = this.copiedAgentRunId === `error:${t}`, c = e.role === "assistant" && t ? `<footer class="po-answer-meta ${s ? "selected" : ""}">
514
+ <span class="po-run-id" title="${l(t)}">问答流水号 <code>${l(t)}</code></span>
515
+ <button type="button" data-copy-run="${l(t)}">${i ? "已复制" : n ? "复制失败" : "复制流水号"}</button>
516
+ <button type="button" data-view-run="${l(t)}" aria-pressed="${s}">${s ? "正在查看" : "查看执行过程"}</button>
517
+ </footer>` : "";
518
+ return `<article class="po-message ${e.role} ${s ? "run-selected" : ""}" data-message="${l(e.id)}">
519
+ <b>${e.role === "user" ? "你" : "PageOps 分析"}</b>
520
+ <div>${e.role === "assistant" ? y(e.content) : l(e.content)}</div>
521
+ ${c}
522
+ </article>`;
523
+ }
464
524
  renderSourceUploader() {
465
525
  const e = this.sourceLoadError ? "暂时无法读取项目共享代码包,连接恢复后将自动重试。" : "当前项目暂无代码包,请先上传后再提问。";
466
526
  return `
@@ -471,62 +531,85 @@ class F {
471
531
  <span>${this.sourceUploading ? "上传中..." : "选择代码包"}</span>
472
532
  <input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading ? "disabled" : ""} />
473
533
  </label>
474
- ${this.sourceUploadStatus ? `<p class="po-upload-status">${c(this.sourceUploadStatus)}</p>` : ""}
534
+ ${this.sourceUploadStatus ? `<p class="po-upload-status">${l(this.sourceUploadStatus)}</p>` : ""}
475
535
  ${this.sourceSnapshots.length ? `<div class="po-source-list">${this.sourceSnapshots.map((t) => this.renderSourceItem(t)).join("")}</div>` : `<p class="po-upload-empty">${e}</p>`}
476
- ${this.sourceLoadError ? `<p class="po-upload-error">${c(this.sourceLoadError)}</p>` : ""}
477
- ${this.sourceUploadError ? `<p class="po-upload-error">${c(this.sourceUploadError)}</p>` : ""}
536
+ ${this.sourceLoadError ? `<p class="po-upload-error">${l(this.sourceLoadError)}</p>` : ""}
537
+ ${this.sourceUploadError ? `<p class="po-upload-error">${l(this.sourceUploadError)}</p>` : ""}
478
538
  </div>
479
539
  `;
480
540
  }
481
541
  renderSourceItem(e) {
482
- var n, d, p;
483
- const t = e.filename || "未命名代码包", s = e.created_at ? A(e.created_at) : "刚刚上传", i = O(e.archive_bytes || e.total_bytes || 0), r = String((d = (n = e.metadata) == null ? void 0 : n.analysis_status) != null ? d : "unknown"), l = (p = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[r]) != null ? p : "项目记忆状态未知";
484
- return `<article class="po-source-item"><strong>${c(t)}</strong><span>${c(s)} · ${c(i)}</span><span>${c(l)}</span></article>`;
542
+ var o, p, g;
543
+ const t = e.filename || "未命名代码包", s = e.created_at ? k(e.created_at) : "刚刚上传", i = O(e.archive_bytes || e.total_bytes || 0), n = String((p = (o = e.metadata) == null ? void 0 : o.analysis_status) != null ? p : "unknown"), c = (g = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[n]) != null ? g : "项目记忆状态未知";
544
+ return `<article class="po-source-item"><strong>${l(t)}</strong><span>${l(s)} · ${l(i)}</span><span>${l(c)}</span></article>`;
485
545
  }
486
546
  renderSteps() {
487
- return (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", details: { message: "发送消息后展示执行过程。" } }]).map((t) => {
488
- var s;
489
- return `<details class="po-step ${t.status}" ${t.status === "running" || t.status === "failed" ? "open" : ""}><summary><strong>${c(t.title)}</strong><span>${_(t.status)}</span></summary><pre>${c(JSON.stringify((s = t.details) != null ? s : {}, null, 2))}</pre></details>`;
547
+ return this.runLoading ? '<div class="po-trace-state"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在恢复本次执行过程</span></div>' : this.runLoadError ? `<div class="po-trace-state failed" role="alert">${l(this.runLoadError)}</div>` : (this.steps.length ? this.steps : [{ id: "idle", title: "等待任务", status: "pending", summary: "发送问题后,这里会展示完整分析过程。" }]).map((t) => {
548
+ var c, o, p;
549
+ const s = (c = t.metrics) != null && c.length ? `<div class="po-step-metrics">${t.metrics.map((g) => `<span>${l(g)}</span>`).join("")}</div>` : "", i = (o = t.details) != null && o.length ? `<div class="po-step-details">${t.details.map((g) => `<div><span>${l(g.label)}</span><p>${l(g.value)}</p></div>`).join("")}</div>` : "", n = !!(s || i);
550
+ return `<details class="po-step ${t.status}" ${t.status === "running" || t.status === "failed" ? "open" : ""} ${n ? "" : "data-static"}>
551
+ <summary>
552
+ <span class="po-step-dot" aria-hidden="true"></span>
553
+ <span class="po-step-copy"><strong>${l(t.title)}</strong><small>${l((p = t.summary) != null ? p : "")}</small></span>
554
+ <span class="po-step-status">${D(t.status)}</span>
555
+ </summary>
556
+ ${s}${i}
557
+ </details>`;
490
558
  }).join("");
491
559
  }
492
560
  bindPanelEvents() {
493
- var e, t, s, i, r, l, n, d, p, f, b, S, $, E, C;
494
- (t = (e = this.panel) == null ? void 0 : e.querySelector('[data-action="new"]')) == null || t.addEventListener("click", () => void this.newConversation()), (i = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || i.addEventListener("click", () => this.close()), (l = (r = this.panel) == null ? void 0 : r.querySelector('[data-action="stop-answer"]')) == null || l.addEventListener("click", () => this.cancelActiveAnswer(!0)), (n = this.panel) == null || n.querySelectorAll("[data-audience]").forEach((u) => {
495
- u.addEventListener("click", () => {
561
+ var e, t, s, i, n, c, o, p, g, f, b, $, S, E, A, C, P;
562
+ (t = (e = this.panel) == null ? void 0 : e.querySelector('[data-action="new"]')) == null || t.addEventListener("click", () => void this.newConversation()), (i = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || i.addEventListener("click", () => this.close()), (c = (n = this.panel) == null ? void 0 : n.querySelector('[data-action="stop-answer"]')) == null || c.addEventListener("click", () => this.cancelActiveAnswer(!0)), (o = this.panel) == null || o.querySelectorAll("[data-audience]").forEach((d) => {
563
+ d.addEventListener("click", () => {
496
564
  var h;
497
- return void this.changeAnswerAudience((h = u.dataset.audience) != null ? h : "");
565
+ return void this.changeAnswerAudience((h = d.dataset.audience) != null ? h : "");
498
566
  });
499
- }), (p = (d = this.panel) == null ? void 0 : d.querySelector('[data-action="upload-source"]')) == null || p.addEventListener("change", (u) => {
500
- var g;
501
- const h = (g = u.target.files) == null ? void 0 : g[0];
567
+ }), (g = (p = this.panel) == null ? void 0 : p.querySelector('[data-action="upload-source"]')) == null || g.addEventListener("change", (d) => {
568
+ var u;
569
+ const h = (u = d.target.files) == null ? void 0 : u[0];
502
570
  h && this.uploadSource(h);
503
- }), (f = this.panel) == null || f.querySelectorAll("[data-thread]").forEach((u) => {
504
- u.addEventListener("click", () => {
505
- const h = this.conversations.find((g) => g.id === u.dataset.thread);
571
+ }), (f = this.panel) == null || f.querySelectorAll("[data-thread]").forEach((d) => {
572
+ d.addEventListener("click", () => {
573
+ const h = this.conversations.find((u) => u.id === d.dataset.thread);
506
574
  h && this.selectThread(h);
507
575
  });
508
- }), (b = this.panel) == null || b.querySelectorAll("[data-delete-thread]").forEach((u) => {
509
- u.addEventListener("click", (h) => {
576
+ }), (b = this.panel) == null || b.querySelectorAll("[data-delete-thread]").forEach((d) => {
577
+ d.addEventListener("click", (h) => {
510
578
  h.stopPropagation();
511
- const g = this.conversations.find((m) => m.id === u.dataset.deleteThread);
512
- g && this.deleteConversation(g);
579
+ const u = this.conversations.find((m) => m.id === d.dataset.deleteThread);
580
+ u && this.deleteConversation(u);
581
+ });
582
+ }), ($ = this.panel) == null || $.querySelectorAll("[data-view-run]").forEach((d) => {
583
+ d.addEventListener("click", (h) => {
584
+ var u;
585
+ h.stopPropagation(), this.loadAgentRun((u = d.dataset.viewRun) != null ? u : "");
513
586
  });
514
- }), ($ = (S = this.panel) == null ? void 0 : S.querySelector("form")) == null || $.addEventListener("submit", (u) => {
587
+ }), (S = this.panel) == null || S.querySelectorAll("[data-copy-run]").forEach((d) => {
588
+ d.addEventListener("click", (h) => {
589
+ var u;
590
+ h.stopPropagation(), this.copyAgentRunId((u = d.dataset.copyRun) != null ? u : "");
591
+ });
592
+ }), (A = (E = this.panel) == null ? void 0 : E.querySelector("form")) == null || A.addEventListener("submit", (d) => {
515
593
  var m;
516
- u.preventDefault();
517
- const h = (m = this.panel) == null ? void 0 : m.querySelector("textarea"), g = h == null ? void 0 : h.value.trim();
518
- g && (h.value = "", this.ask(g));
519
- }), (C = (E = this.panel) == null ? void 0 : E.querySelector("textarea")) == null || C.addEventListener("keydown", (u) => {
520
- var g, m;
521
- const h = u;
522
- h.key === "Enter" && !h.shiftKey && (h.preventDefault(), (m = (g = this.panel) == null ? void 0 : g.querySelector("form")) == null || m.requestSubmit());
594
+ d.preventDefault();
595
+ const h = (m = this.panel) == null ? void 0 : m.querySelector("textarea"), u = h == null ? void 0 : h.value.trim();
596
+ u && (h.value = "", this.ask(u));
597
+ }), (P = (C = this.panel) == null ? void 0 : C.querySelector("textarea")) == null || P.addEventListener("keydown", (d) => {
598
+ var u, m;
599
+ const h = d;
600
+ h.key === "Enter" && !h.shiftKey && (h.preventDefault(), (m = (u = this.panel) == null ? void 0 : u.querySelector("form")) == null || m.requestSubmit());
523
601
  });
524
602
  }
525
603
  }
526
- function c(a) {
604
+ function l(a) {
527
605
  return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
528
606
  }
529
- function A(a) {
607
+ function T(a) {
608
+ var t;
609
+ const e = (t = a.metadata_json) == null ? void 0 : t.agent_run_id;
610
+ return typeof e == "string" ? e : "";
611
+ }
612
+ function k(a) {
530
613
  return new Intl.DateTimeFormat("zh-CN", {
531
614
  timeZone: "Asia/Shanghai",
532
615
  month: "2-digit",
@@ -544,10 +627,10 @@ function O(a) {
544
627
  t /= 1024, s += 1;
545
628
  return `${t >= 10 || s === 0 ? t.toFixed(0) : t.toFixed(1)} ${e[s]}`;
546
629
  }
547
- function _(a) {
630
+ function D(a) {
548
631
  return { pending: "等待中", running: "执行中", completed: "已完成", failed: "失败", cancelled: "已停止" }[a];
549
632
  }
550
- const j = new F();
633
+ const W = new j();
551
634
  export {
552
- j as PageOpsSDK
635
+ W as PageOpsSDK
553
636
  };
@@ -1,31 +1,39 @@
1
- (function(m,u){typeof exports=="object"&&typeof module!="undefined"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(m=typeof globalThis!="undefined"?globalThis:m||self,u(m.PageOpsSDK={}))})(this,(function(m){"use strict";var _=Object.defineProperty;var D=(m,u,w)=>u in m?_(m,u,{enumerable:!0,configurable:!0,writable:!0,value:w}):m[u]=w;var a=(m,u,w)=>D(m,typeof u!="symbol"?u+"":u,w);class u{constructor(e){this.options=e}async createContext(e=(i=>(i=(t=>(s=>(s=(t=this.options).getPageContext)==null?void 0:s.call(t))())())!=null?i:{})()){var n,l,r;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:e.route,url:(n=e.url)!=null?n:location.href,title:(l=e.title)!=null?l:document.title,menu_path:(r=e.menuPath)!=null?r:[],tenant_id:e.tenantId,user_role:e.userRole,build_version:e.buildVersion})})}async listConversations(){return(await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations}async createConversation(e,t){return this.request("/conversations",{method:"POST",body:JSON.stringify({app_id:this.options.appId,context_session_id:e,title:t})})}async deleteConversation(e){return this.request(`/conversations/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`,{method:"DELETE"})}async listMessages(e){return(await this.request(`/conversations/${encodeURIComponent(e)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages}async listSources(){return(await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources}uploadSource(e){const t=new FormData;return t.append("file",e),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:t,headers:{}})}streamQuestion(e,t,s){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:this.options.appId,thread_id:e,question:t}),signal:s})}async request(e,t){var l,r;const s=(t==null?void 0:t.body)instanceof FormData?t.headers:{"content-type":"application/json",...(l=t==null?void 0:t.headers)!=null?l:{}},i=await fetch(`${this.base()}${e}`,{...t,headers:s});if(i.status===204)return;const n=await i.json();if(!i.ok)throw new Error((r=n.message)!=null?r:"PageOps 请求失败");return n}base(){const e=this.options.apiBase.replace(/\/$/,"");return e.endsWith("/api")?e:`${e}/api`}}async function w(o,e){const t=await o.json().catch(()=>null);return typeof(t==null?void 0:t.message)=="string"&&t.message.trim()?t.message:e}function E(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function y(o){return E(o).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function R(o,e){const t=o[e],s=o[e+1];if(!(t!=null&&t.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const i=[];let n=e;for(;n<o.length&&o[n].includes("|")&&o[n].trim();)i.push(o[n]),n+=1;const l=g=>g.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(S=>y(S.trim())),r=l(i[0]).map(g=>`<th>${g}</th>`).join(""),d=i.slice(2).map(g=>`<tr>${l(g).map(S=>`<td>${S}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${r}</tr></thead><tbody>${d}</tbody></table>`,next:n}}function b(o){const e=o.split(`
2
- `),t=[];for(let s=0;s<e.length;s+=1){const i=e[s];if(i.trim().startsWith("```")){const l=[];for(s+=1;s<e.length&&!e[s].trim().startsWith("```");)l.push(e[s]),s+=1;t.push(`<pre><code>${E(l.join(`
3
- `))}</code></pre>`);continue}const n=R(e,s);if(n){t.push(n.html),s=n.next-1;continue}i.startsWith("### ")?t.push(`<h4>${y(i.slice(4))}</h4>`):i.startsWith("## ")?t.push(`<h3>${y(i.slice(3))}</h3>`):i.startsWith("# ")?t.push(`<h2>${y(i.slice(2))}</h2>`):i.startsWith("- ")?t.push(`<li>${y(i.slice(2))}</li>`):i.trim()?t.push(`<p>${y(i)}</p>`):t.push("<br>")}return t.join("")}async function q(o,e){var n;const t=o.getReader(),s=new TextDecoder;let i="";for(;;){const{done:l,value:r}=await t.read();if(l){i+=s.decode();break}i+=s.decode(r,{stream:!0});const d=i.split(/\r?\n\r?\n/);i=(n=d.pop())!=null?n:"";for(const g of d)P(g,e)}i.trim()&&P(i,e)}function P(o,e){var i,n;const t=(i=o.match(/^event:\s*(.+)$/m))==null?void 0:i[1],s=(n=o.match(/^data:\s*(.+)$/m))==null?void 0:n[1];t&&s&&e(t,JSON.parse(s))}class U{constructor(e,t=16){a(this,"queue",[]);a(this,"timer",null);a(this,"drainWaiters",[]);this.onChunk=e,this.interval=t}enqueue(e){this.queue.push(...Array.from(e)),this.timer||this.tick()}async drain(){!this.timer&&!this.queue.length||await new Promise(e=>this.drainWaiters.push(e))}clear(){this.timer&&clearTimeout(this.timer),this.timer=null,this.queue=[],this.resolveDrainWaiters()}tick(){const e=Math.max(1,Math.ceil(this.queue.length/90)),t=this.queue.splice(0,e).join("");if(t&&this.onChunk(t),!this.queue.length){this.timer=null,this.resolveDrainWaiters();return}this.timer=setTimeout(()=>this.tick(),this.interval)}resolveDrainWaiters(){for(const e of this.drainWaiters.splice(0))e()}}const $=[{value:"product",label:"产品"},{value:"business",label:"业务"},{value:"developer",label:"研发"},{value:"tester",label:"测试"}];class K{constructor(){a(this,"client",null);a(this,"options",null);a(this,"root",null);a(this,"panel",null);a(this,"context",null);a(this,"contextKey","");a(this,"selectedPageKey","");a(this,"currentThread",null);a(this,"conversations",[]);a(this,"messages",[]);a(this,"steps",[]);a(this,"sourceSnapshots",[]);a(this,"sourceUploadStatus","");a(this,"sourceUploadError","");a(this,"sourceLoadError","");a(this,"sourceUploading",!1);a(this,"sourceRefreshTimer",null);a(this,"streaming","");a(this,"asking",!1);a(this,"waitingForFirstContent",!1);a(this,"abortController",null);a(this,"activeRunId",0);a(this,"stoppedRunId",-1);a(this,"answerStopped",!1);a(this,"answerError","");a(this,"conversationError","");a(this,"deletingThreadId","");a(this,"streamFailure","");a(this,"streamDone",null);a(this,"answerAudience","business");a(this,"audienceChanging",!1);a(this,"typewriter",new U(e=>{this.streaming+=e,this.updateStreamingMessage()}))}mount(e){var t;this.unmount(),this.options=e,this.client=new u(e),this.answerAudience=this.loadAnswerAudience(e.appId),this.root=document.createElement("div"),this.root.className="pageops-sdk",((t=e.container)!=null?t:document.body).appendChild(this.root),this.renderClosed()}unmount(){var e;this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.resetAnswerState(),(e=this.root)==null||e.remove(),this.root=null,this.panel=null,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceLoadError="",this.sourceUploading=!1,this.answerAudience="business",this.audienceChanging=!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(e){if(!this.options)return;const t=this.options.appId;this.options={...this.options,...e},this.client=new u(this.options),this.options.appId!==t&&(this.answerAudience=this.loadAnswerAudience(this.options.appId),this.currentThread=null,this.selectedPageKey="",this.messages=[],this.steps=[]),this.context=null,this.contextKey="",this.renderPanel()}renderClosed(){var e;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(e=this.root.querySelector("button"))==null||e.addEventListener("click",()=>this.open()))}async ensureContext(){if(!this.client||!this.options)throw new Error("PageOps SDK 未初始化");const e=this.getPageContext(),t=this.getPageContextKey(e);return this.context&&this.contextKey===t?this.context:(this.context=await this.client.createContext(e),this.contextKey=t,this.context)}getPageContext(){var e,t,s;return{...(s=(t=(e=this.options)==null?void 0:e.getPageContext)==null?void 0:t.call(e))!=null?s:{},userRole:this.answerAudience}}answerAudienceStorageKey(e){return`pageops:answer-audience:${e}`}loadAnswerAudience(e){try{const t=localStorage.getItem(this.answerAudienceStorageKey(e));return $.some(s=>s.value===t)?t:"business"}catch(t){return"business"}}saveAnswerAudience(){if(this.options)try{localStorage.setItem(this.answerAudienceStorageKey(this.options.appId),this.answerAudience)}catch(e){}}async changeAnswerAudience(e){var s;if(this.asking||this.audienceChanging)return;const t=(s=$.find(i=>i.value===e))==null?void 0:s.value;if(!(!t||t===this.answerAudience)){this.answerAudience=t,this.saveAnswerAudience(),this.audienceChanging=!0,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.messages=[],this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.conversationError="",this.renderPanel();try{await this.newConversation()}catch(i){this.conversationError=i instanceof Error?i.message:"切换回答角色失败,请稍后重试。"}finally{this.audienceChanging=!1,this.renderPanel()}}}getPageContextKey(e){var t,s,i,n,l;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(i=e.title)!=null?i:document.title,(n=e.menuPath)!=null?n:[],(l=e.userRole)!=null?l:""])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceLoadError=""}catch(e){this.sourceLoadError="源码包状态加载失败,连接恢复后将自动重试。"}this.scheduleSourceRefresh(),this.renderPanel()}}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){var s;if(!this.client)return;const e=await this.ensureContext(),t=(s=e.menu_path)!=null&&s.length?e.menu_path.join(" / "):e.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(e.id,t),this.selectedPageKey=this.contextKey,this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel()}async selectThread(e){this.client&&(this.currentThread=e,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(e.id),this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel())}async deleteConversation(e){var t;if(!(!this.client||this.asking||this.deletingThreadId)&&window.confirm(`确定删除会话“${e.title}”吗?此操作无法撤销。`)){this.deletingThreadId=e.id,this.conversationError="",this.renderPanel();try{if(await this.client.deleteConversation(e.id),this.conversations=this.conversations.filter(s=>s.id!==e.id),((t=this.currentThread)==null?void 0:t.id)===e.id){this.currentThread=null,this.messages=[],this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1;const s=this.conversations[0];s&&await this.selectThread(s)}}catch(s){this.conversationError=s instanceof Error?s.message:"删除问答会话失败"}finally{this.deletingThreadId="",this.renderPanel()}}}async uploadSource(e){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){if(!this.client||this.asking)return;const t=this.questionUnavailableReason();if(t){this.sourceUploadError=t,this.renderPanel();return}this.resetAnswerState();const s=++this.activeRunId,i=new AbortController;this.abortController=i,this.stoppedRunId=-1,this.asking=!0,this.waitingForFirstContent=!0,this.renderPanel();try{const n=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==n&&(this.currentThread=null),this.currentThread||await this.newConversation(),!this.currentThread)throw new Error("无法创建问答会话,请稍后重试。");this.messages.push({id:`local-${Date.now()}`,role:"user",content:e,metadata_json:{}}),this.steps=[],this.renderPanel();const l=await this.client.streamQuestion(this.currentThread.id,e,i.signal);if(!l.ok)throw new Error(await w(l,"服务暂时无法回答,请稍后重试。"));if(!l.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await q(l.body,(r,d)=>this.handleStreamEvent(r,d)),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");if(this.streamFailure)throw new Error(this.streamFailure);if(!this.streamDone)throw new Error("服务响应意外中断,请稍后重试。");if(await this.typewriter.drain(),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");await this.selectThread(this.currentThread)}catch(n){if(s!==this.activeRunId)return;this.typewriter.clear(),this.waitingForFirstContent=!1,s===this.stoppedRunId?this.answerStopped=!0:(this.answerError=n instanceof Error?n.message:"服务异常,请稍后重试。",this.upsertStep({id:"error",title:"执行失败",status:"failed",details:{message:this.answerError}}))}finally{if(s!==this.activeRunId)return;this.asking=!1,this.waitingForFirstContent=!1,this.abortController===i&&(this.abortController=null),this.renderPanel(!0)}}cancelActiveAnswer(e){var t;if(!(!this.asking&&!this.abortController)){if(e){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,(t=this.abortController)==null||t.abort(),this.abortController=null,e&&this.renderPanel()}}handleStreamEvent(e,t){var s,i;if(e==="step"){this.upsertStep(t),this.renderPanel();return}if(e==="delta"){const n=String((s=t.content)!=null?s:"");if(!n)return;this.waitingForFirstContent=!1,this.typewriter.enqueue(n);return}e==="done"&&(this.streamDone=t),e==="error"&&(this.streamFailure=String((i=t.message)!=null?i:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,i;const e=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!e){this.renderPanel();return}e.innerHTML=b(this.streaming);const t=(i=this.panel)==null?void 0:i.querySelector(".po-messages");t&&(t.scrollTop=t.scrollHeight)}resetAnswerState(){this.typewriter.clear(),this.asking=!1,this.waitingForFirstContent=!1,this.answerError="",this.answerStopped=!1,this.streamFailure="",this.streamDone=null,this.streaming=""}upsertStep(e){const t=this.steps.findIndex(s=>s.id===e.id);this.steps=t===-1?[...this.steps,e]:this.steps.map(s=>s.id===e.id?{...s,...e}:s)}latestAnalysisStatus(){var e,t,s;return String((s=(t=(e=this.sourceSnapshots[0])==null?void 0:e.metadata)==null?void 0:t.analysis_status)!=null?s:"")}isProjectMemoryUpdating(){return["pending","running"].includes(this.latestAnalysisStatus())}questionUnavailableReason(){return this.sourceLoadError&&!this.sourceSnapshots.length?"暂时无法读取项目共享代码包,请检查 PageOps 服务连接。":this.sourceSnapshots.length?this.isProjectMemoryUpdating()?"项目记忆正在更新,完成前暂不能问答。":this.latestAnalysisStatus()==="failed"?"项目记忆更新失败,请重新上传或重新索引。":"":"请先上传代码包后再提问。"}scheduleSourceRefresh(){this.stopSourceRefresh(),!(!this.sourceLoadError&&!this.isProjectMemoryUpdating())&&(this.sourceRefreshTimer=setTimeout(()=>void this.loadSources(),1500))}stopSourceRefresh(){this.sourceRefreshTimer&&clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null}renderPanel(e=this.asking){if(!this.panel)return;const t=this.questionUnavailableReason(),s=t||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),i=!!(t||this.asking),n=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>',l=$.map(r=>`
4
- <button type="button" data-audience="${r.value}" aria-pressed="${r.value===this.answerAudience}" ${this.asking||this.audienceChanging?"disabled":""}>${r.label}</button>
1
+ (function(f,m){typeof exports=="object"&&typeof module!="undefined"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(f=typeof globalThis!="undefined"?globalThis:f||self,m(f.PageOpsSDK={}))})(this,(function(f){"use strict";var M=Object.defineProperty;var W=(f,m,y)=>m in f?M(f,m,{enumerable:!0,configurable:!0,writable:!0,value:y}):f[m]=y;var r=(f,m,y)=>W(f,typeof m!="symbol"?m+"":m,y);class m{constructor(e){this.options=e}async createContext(e=(i=>(i=(t=>(s=>(s=(t=this.options).getPageContext)==null?void 0:s.call(t))())())!=null?i:{})()){var n,c,a;return this.request("/context/session",{method:"POST",body:JSON.stringify({app_id:this.options.appId,env:this.options.env,route:e.route,url:(n=e.url)!=null?n:location.href,title:(c=e.title)!=null?c:document.title,menu_path:(a=e.menuPath)!=null?a:[],tenant_id:e.tenantId,user_role:e.userRole,build_version:e.buildVersion})})}async listConversations(){return(await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations}async createConversation(e,t){return this.request("/conversations",{method:"POST",body:JSON.stringify({app_id:this.options.appId,context_session_id:e,title:t})})}async deleteConversation(e){return this.request(`/conversations/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`,{method:"DELETE"})}async listMessages(e){return(await this.request(`/conversations/${encodeURIComponent(e)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages}async getAgentRun(e){return this.request(`/question/runs/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`)}async listSources(){return(await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources}uploadSource(e){const t=new FormData;return t.append("file",e),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:t,headers:{}})}streamQuestion(e,t,s){return fetch(`${this.base()}/question/stream`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:this.options.appId,thread_id:e,question:t}),signal:s})}async request(e,t){var c,a;const s=(t==null?void 0:t.body)instanceof FormData?t.headers:{"content-type":"application/json",...(c=t==null?void 0:t.headers)!=null?c:{}},i=await fetch(`${this.base()}${e}`,{...t,headers:s});if(i.status===204)return;const n=await i.json();if(!i.ok)throw new Error((a=n.message)!=null?a:"PageOps 请求失败");return n}base(){const e=this.options.apiBase.replace(/\/$/,"");return e.endsWith("/api")?e:`${e}/api`}}async function y(o,e){const t=await o.json().catch(()=>null);return typeof(t==null?void 0:t.message)=="string"&&t.message.trim()?t.message:e}function E(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function w(o){return E(o).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function U(o,e){const t=o[e],s=o[e+1];if(!(t!=null&&t.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const i=[];let n=e;for(;n<o.length&&o[n].includes("|")&&o[n].trim();)i.push(o[n]),n+=1;const c=g=>g.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(b=>w(b.trim())),a=c(i[0]).map(g=>`<th>${g}</th>`).join(""),p=i.slice(2).map(g=>`<tr>${c(g).map(b=>`<td>${b}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${a}</tr></thead><tbody>${p}</tbody></table>`,next:n}}function $(o){const e=o.split(`
2
+ `),t=[];for(let s=0;s<e.length;s+=1){const i=e[s];if(i.trim().startsWith("```")){const c=[];for(s+=1;s<e.length&&!e[s].trim().startsWith("```");)c.push(e[s]),s+=1;t.push(`<pre><code>${E(c.join(`
3
+ `))}</code></pre>`);continue}const n=U(e,s);if(n){t.push(n.html),s=n.next-1;continue}i.startsWith("### ")?t.push(`<h4>${w(i.slice(4))}</h4>`):i.startsWith("## ")?t.push(`<h3>${w(i.slice(3))}</h3>`):i.startsWith("# ")?t.push(`<h2>${w(i.slice(2))}</h2>`):i.startsWith("- ")?t.push(`<li>${w(i.slice(2))}</li>`):i.trim()?t.push(`<p>${w(i)}</p>`):t.push("<br>")}return t.join("")}async function F(o,e){var n;const t=o.getReader(),s=new TextDecoder;let i="";for(;;){const{done:c,value:a}=await t.read();if(c){i+=s.decode();break}i+=s.decode(a,{stream:!0});const p=i.split(/\r?\n\r?\n/);i=(n=p.pop())!=null?n:"";for(const g of p)A(g,e)}i.trim()&&A(i,e)}function A(o,e){var i,n;const t=(i=o.match(/^event:\s*(.+)$/m))==null?void 0:i[1],s=(n=o.match(/^data:\s*(.+)$/m))==null?void 0:n[1];t&&s&&e(t,JSON.parse(s))}class K{constructor(e,t=16){r(this,"queue",[]);r(this,"timer",null);r(this,"drainWaiters",[]);this.onChunk=e,this.interval=t}enqueue(e){this.queue.push(...Array.from(e)),this.timer||this.tick()}async drain(){!this.timer&&!this.queue.length||await new Promise(e=>this.drainWaiters.push(e))}clear(){this.timer&&clearTimeout(this.timer),this.timer=null,this.queue=[],this.resolveDrainWaiters()}tick(){const e=Math.max(1,Math.ceil(this.queue.length/90)),t=this.queue.splice(0,e).join("");if(t&&this.onChunk(t),!this.queue.length){this.timer=null,this.resolveDrainWaiters();return}this.timer=setTimeout(()=>this.tick(),this.interval)}resolveDrainWaiters(){for(const e of this.drainWaiters.splice(0))e()}}const S=[{value:"product",label:"产品"},{value:"business",label:"业务"},{value:"developer",label:"研发"},{value:"tester",label:"测试"}];class _{constructor(){r(this,"client",null);r(this,"options",null);r(this,"root",null);r(this,"panel",null);r(this,"context",null);r(this,"contextKey","");r(this,"selectedPageKey","");r(this,"currentThread",null);r(this,"conversations",[]);r(this,"messages",[]);r(this,"steps",[]);r(this,"selectedAgentRunId","");r(this,"runLoading",!1);r(this,"runLoadError","");r(this,"copiedAgentRunId","");r(this,"copyFeedbackTimer",null);r(this,"sourceSnapshots",[]);r(this,"sourceUploadStatus","");r(this,"sourceUploadError","");r(this,"sourceLoadError","");r(this,"sourceUploading",!1);r(this,"sourceRefreshTimer",null);r(this,"streaming","");r(this,"asking",!1);r(this,"waitingForFirstContent",!1);r(this,"abortController",null);r(this,"activeRunId",0);r(this,"stoppedRunId",-1);r(this,"answerStopped",!1);r(this,"answerError","");r(this,"conversationError","");r(this,"deletingThreadId","");r(this,"streamFailure","");r(this,"streamDone",null);r(this,"answerAudience","business");r(this,"audienceChanging",!1);r(this,"typewriter",new K(e=>{this.streaming+=e,this.updateStreamingMessage()}))}mount(e){var t;this.unmount(),this.options=e,this.client=new m(e),this.answerAudience=this.loadAnswerAudience(e.appId),this.root=document.createElement("div"),this.root.className="pageops-sdk",((t=e.container)!=null?t:document.body).appendChild(this.root),this.renderClosed()}unmount(){var e;this.stopSourceRefresh(),this.cancelActiveAnswer(!1),this.resetAnswerState(),(e=this.root)==null||e.remove(),this.root=null,this.panel=null,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.conversations=[],this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoading=!1,this.runLoadError="",this.clearCopyFeedback(),this.sourceSnapshots=[],this.sourceUploadStatus="",this.sourceUploadError="",this.sourceLoadError="",this.sourceUploading=!1,this.answerAudience="business",this.audienceChanging=!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(e){if(!this.options)return;const t=this.options.appId;this.options={...this.options,...e},this.client=new m(this.options),this.options.appId!==t&&(this.answerAudience=this.loadAnswerAudience(this.options.appId),this.currentThread=null,this.selectedPageKey="",this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError=""),this.context=null,this.contextKey="",this.renderPanel()}renderClosed(){var e;this.root&&(this.root.innerHTML='<button class="po-fab" type="button">多轮问答</button>',(e=this.root.querySelector("button"))==null||e.addEventListener("click",()=>this.open()))}async ensureContext(){if(!this.client||!this.options)throw new Error("PageOps SDK 未初始化");const e=this.getPageContext(),t=this.getPageContextKey(e);return this.context&&this.contextKey===t?this.context:(this.context=await this.client.createContext(e),this.contextKey=t,this.context)}getPageContext(){var e,t,s;return{...(s=(t=(e=this.options)==null?void 0:e.getPageContext)==null?void 0:t.call(e))!=null?s:{},userRole:this.answerAudience}}answerAudienceStorageKey(e){return`pageops:answer-audience:${e}`}loadAnswerAudience(e){try{const t=localStorage.getItem(this.answerAudienceStorageKey(e));return S.some(s=>s.value===t)?t:"business"}catch(t){return"business"}}saveAnswerAudience(){if(this.options)try{localStorage.setItem(this.answerAudienceStorageKey(this.options.appId),this.answerAudience)}catch(e){}}async changeAnswerAudience(e){var s;if(this.asking||this.audienceChanging)return;const t=(s=S.find(i=>i.value===e))==null?void 0:s.value;if(!(!t||t===this.answerAudience)){this.answerAudience=t,this.saveAnswerAudience(),this.audienceChanging=!0,this.context=null,this.contextKey="",this.selectedPageKey="",this.currentThread=null,this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1,this.conversationError="",this.renderPanel();try{await this.newConversation()}catch(i){this.conversationError=i instanceof Error?i.message:"切换回答角色失败,请稍后重试。"}finally{this.audienceChanging=!1,this.renderPanel()}}}getPageContextKey(e){var t,s,i,n,c;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(i=e.title)!=null?i:document.title,(n=e.menuPath)!=null?n:[],(c=e.userRole)!=null?c:""])}async loadSources(){if(this.client){try{this.sourceSnapshots=await this.client.listSources(),this.sourceLoadError=""}catch(e){this.sourceLoadError="源码包状态加载失败,连接恢复后将自动重试。"}this.scheduleSourceRefresh(),this.renderPanel()}}async loadConversations(){this.client&&(this.conversations=await this.client.listConversations(),this.renderPanel())}async newConversation(){var s;if(!this.client)return;const e=await this.ensureContext(),t=(s=e.menu_path)!=null&&s.length?e.menu_path.join(" / "):e.route||document.title||"新的问答";this.currentThread=await this.client.createConversation(e.id,t),this.selectedPageKey=this.contextKey,this.conversations=[this.currentThread,...this.conversations],this.messages=[],this.steps=[],this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel()}async selectThread(e){if(!this.client)return;this.currentThread=e,this.selectedPageKey=this.getPageContextKey(this.getPageContext()),this.messages=await this.client.listMessages(e.id),this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1,this.renderPanel();const t=[...this.messages].reverse().map(P).find(Boolean);t&&await this.loadAgentRun(t)}async deleteConversation(e){var t;if(!(!this.client||this.asking||this.deletingThreadId)&&window.confirm(`确定删除会话“${e.title}”吗?此操作无法撤销。`)){this.deletingThreadId=e.id,this.conversationError="",this.renderPanel();try{if(await this.client.deleteConversation(e.id),this.conversations=this.conversations.filter(s=>s.id!==e.id),((t=this.currentThread)==null?void 0:t.id)===e.id){this.currentThread=null,this.messages=[],this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.streaming="",this.answerError="",this.answerStopped=!1;const s=this.conversations[0];s&&await this.selectThread(s)}}catch(s){this.conversationError=s instanceof Error?s.message:"删除问答会话失败"}finally{this.deletingThreadId="",this.renderPanel()}}}async uploadSource(e){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){if(!this.client||this.asking)return;const t=this.questionUnavailableReason();if(t){this.sourceUploadError=t,this.renderPanel();return}this.resetAnswerState();const s=++this.activeRunId,i=new AbortController;this.abortController=i,this.stoppedRunId=-1,this.asking=!0,this.waitingForFirstContent=!0,this.renderPanel();try{const n=this.getPageContextKey(this.getPageContext());if(this.currentThread&&this.selectedPageKey&&this.selectedPageKey!==n&&(this.currentThread=null),this.currentThread||await this.newConversation(),!this.currentThread)throw new Error("无法创建问答会话,请稍后重试。");this.messages.push({id:`local-${Date.now()}`,role:"user",content:e,metadata_json:{}}),this.steps=[],this.selectedAgentRunId="",this.runLoadError="",this.renderPanel();const c=await this.client.streamQuestion(this.currentThread.id,e,i.signal);if(!c.ok)throw new Error(await y(c,"服务暂时无法回答,请稍后重试。"));if(!c.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await F(c.body,(a,p)=>this.handleStreamEvent(a,p)),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");if(this.streamFailure)throw new Error(this.streamFailure);if(!this.streamDone)throw new Error("服务响应意外中断,请稍后重试。");if(await this.typewriter.drain(),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");await this.selectThread(this.currentThread)}catch(n){if(s!==this.activeRunId)return;this.typewriter.clear(),this.waitingForFirstContent=!1,s===this.stoppedRunId?this.answerStopped=!0:(this.answerError=n instanceof Error?n.message:"服务异常,请稍后重试。",this.upsertStep({id:"error",title:"执行失败",status:"failed",summary:this.answerError}))}finally{if(s!==this.activeRunId)return;this.asking=!1,this.waitingForFirstContent=!1,this.abortController===i&&(this.abortController=null),this.renderPanel(!0)}}cancelActiveAnswer(e){var t;if(!(!this.asking&&!this.abortController)){if(e){this.stoppedRunId=this.activeRunId,this.answerStopped=!0;const s=this.steps.map(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,(t=this.abortController)==null||t.abort(),this.abortController=null,e&&this.renderPanel()}}handleStreamEvent(e,t){var s,i;if(e==="step"){this.upsertStep(t),this.renderPanel();return}if(e==="delta"){const n=String((s=t.content)!=null?s:"");if(!n)return;this.waitingForFirstContent=!1,this.typewriter.enqueue(n);return}e==="done"&&(this.streamDone=t),e==="error"&&(this.streamFailure=String((i=t.message)!=null?i:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,i;const e=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!e){this.renderPanel();return}e.innerHTML=$(this.streaming);const t=(i=this.panel)==null?void 0:i.querySelector(".po-messages");t&&(t.scrollTop=t.scrollHeight)}resetAnswerState(){this.typewriter.clear(),this.asking=!1,this.waitingForFirstContent=!1,this.answerError="",this.answerStopped=!1,this.streamFailure="",this.streamDone=null,this.streaming=""}upsertStep(e){const t=this.steps.findIndex(s=>s.id===e.id);this.steps=t===-1?[...this.steps,e]:this.steps.map(s=>s.id===e.id?{...s,...e}:s)}async loadAgentRun(e){if(!(!this.client||!e)){this.selectedAgentRunId=e,this.runLoading=!0,this.runLoadError="",this.renderPanel();try{const t=await this.client.getAgentRun(e);if(this.selectedAgentRunId!==e)return;this.steps=t.steps}catch(t){if(this.selectedAgentRunId!==e)return;this.steps=[],this.runLoadError=t instanceof Error?t.message:"执行过程加载失败"}finally{this.selectedAgentRunId===e&&(this.runLoading=!1,this.renderPanel())}}}async copyAgentRunId(e){var t;if(e){try{if((t=navigator.clipboard)!=null&&t.writeText)await navigator.clipboard.writeText(e);else{const s=document.createElement("textarea");s.value=e,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.select(),document.execCommand("copy"),s.remove()}this.copiedAgentRunId=e}catch(s){this.copiedAgentRunId=`error:${e}`}this.clearCopyFeedback(!1),this.copyFeedbackTimer=setTimeout(()=>{this.copiedAgentRunId="",this.copyFeedbackTimer=null,this.renderPanel()},1800),this.renderPanel()}}clearCopyFeedback(e=!0){this.copyFeedbackTimer&&clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=null,e&&(this.copiedAgentRunId="")}latestAnalysisStatus(){var e,t,s;return String((s=(t=(e=this.sourceSnapshots[0])==null?void 0:e.metadata)==null?void 0:t.analysis_status)!=null?s:"")}isProjectMemoryUpdating(){return["pending","running"].includes(this.latestAnalysisStatus())}questionUnavailableReason(){return this.sourceLoadError&&!this.sourceSnapshots.length?"暂时无法读取项目共享代码包,请检查 PageOps 服务连接。":this.sourceSnapshots.length?this.isProjectMemoryUpdating()?"项目记忆正在更新,完成前暂不能问答。":this.latestAnalysisStatus()==="failed"?"项目记忆更新失败,请重新上传或重新索引。":"":"请先上传代码包后再提问。"}scheduleSourceRefresh(){this.stopSourceRefresh(),!(!this.sourceLoadError&&!this.isProjectMemoryUpdating())&&(this.sourceRefreshTimer=setTimeout(()=>void this.loadSources(),1500))}stopSourceRefresh(){this.sourceRefreshTimer&&clearTimeout(this.sourceRefreshTimer),this.sourceRefreshTimer=null}renderPanel(e=this.asking){if(!this.panel)return;const t=this.questionUnavailableReason(),s=t||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),i=!!(t||this.asking),n=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>',c=S.map(a=>`
4
+ <button type="button" data-audience="${a.value}" aria-pressed="${a.value===this.answerAudience}" ${this.asking||this.audienceChanging?"disabled":""}>${a.label}</button>
5
5
  `).join("");if(this.panel.innerHTML=`
6
6
  <aside class="po-sidebar">
7
7
  <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
8
8
  <button class="po-new" data-action="new" ${this.asking?"disabled":""}>+ 新建问答</button>
9
9
  <input class="po-search" placeholder="搜索问答" />
10
- ${this.conversationError?`<p class="po-conversation-error" role="alert">${c(this.conversationError)}</p>`:""}
11
- <div class="po-thread-list">${this.conversations.map(r=>{var d;return`
12
- <div class="po-thread-row ${r.id===((d=this.currentThread)==null?void 0:d.id)?"active":""}">
13
- <button class="po-thread" data-thread="${c(r.id)}" ${this.asking?"disabled":""}>
14
- <strong>${c(r.title)}</strong><span>${C(r.created_at)}</span>
10
+ ${this.conversationError?`<p class="po-conversation-error" role="alert">${l(this.conversationError)}</p>`:""}
11
+ <div class="po-thread-list">${this.conversations.map(a=>{var p;return`
12
+ <div class="po-thread-row ${a.id===((p=this.currentThread)==null?void 0:p.id)?"active":""}">
13
+ <button class="po-thread" data-thread="${l(a.id)}" ${this.asking?"disabled":""}>
14
+ <strong>${l(a.title)}</strong><span>${C(a.created_at)}</span>
15
15
  </button>
16
- <button class="po-thread-delete" type="button" data-delete-thread="${c(r.id)}" aria-label="删除会话:${c(r.title)}" title="删除会话" ${this.asking||this.deletingThreadId===r.id?"disabled":""}><span class="po-trash-icon" aria-hidden="true"></span></button>
16
+ <button class="po-thread-delete" type="button" data-delete-thread="${l(a.id)}" aria-label="删除会话:${l(a.title)}" title="删除会话" ${this.asking||this.deletingThreadId===a.id?"disabled":""}><span class="po-trash-icon" aria-hidden="true"></span></button>
17
17
  </div>`}).join("")}</div>
18
18
  </aside>
19
19
  <main class="po-chat">
20
- <header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread?c(this.currentThread.title):"未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${l}</div></div></header>
20
+ <header><div class="po-chat-title"><p>问数回答</p><h2>${this.currentThread?l(this.currentThread.title):"未选择问答"}</h2></div><div class="po-audience"><span>回答角色</span><div class="po-audience-options" role="group" aria-label="回答角色">${c}</div></div></header>
21
21
  <section class="po-messages">
22
- ${this.messages.map(r=>`<article class="po-message ${r.role}"><b>${r.role==="user"?"你":"PageOps 分析"}</b><div>${r.role==="assistant"?b(r.content):c(r.content)}</div></article>`).join("")}
22
+ ${this.messages.map(a=>this.renderMessage(a)).join("")}
23
23
  ${this.renderAnswerState()}
24
24
  </section>
25
- <form class="po-composer"><textarea ${i?"disabled":""} placeholder="${c(s)}"></textarea>${n}</form>
25
+ <form class="po-composer"><textarea ${i?"disabled":""} placeholder="${l(s)}"></textarea>${n}</form>
26
26
  </main>
27
27
  <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}${this.renderSteps()}</section></aside>
28
- `,this.bindPanelEvents(),e){const r=this.panel.querySelector(".po-messages");r&&(r.scrollTop=r.scrollHeight)}}renderAnswerState(){const e=this.asking&&this.waitingForFirstContent?'<article class="po-message assistant waiting" role="status" aria-live="polite"><b>PageOps 分析</b><div class="po-ai-waiting"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在理解问题并检索证据</span></div></article>':"",t=this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div><span data-streaming-content>${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>${c(this.answerError)}</div></article>`:"",i=this.answerStopped?'<div class="po-stream-stopped" role="status">已停止输出</div>':"";return`${e}${t}${i}${s}`}renderSourceUploader(){const e=this.sourceLoadError?"暂时无法读取项目共享代码包,连接恢复后将自动重试。":"当前项目暂无代码包,请先上传后再提问。";return`
28
+ `,this.bindPanelEvents(),e){const a=this.panel.querySelector(".po-messages");a&&(a.scrollTop=a.scrollHeight)}}renderAnswerState(){const e=this.asking&&this.waitingForFirstContent?'<article class="po-message assistant waiting" role="status" aria-live="polite"><b>PageOps 分析</b><div class="po-ai-waiting"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在理解问题并检索证据</span></div></article>':"",t=this.streaming?`<article class="po-message assistant streaming"><b>PageOps 分析</b><div><span data-streaming-content>${$(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`${e}${t}${i}${s}`}renderMessage(e){const t=P(e),s=t&&t===this.selectedAgentRunId,i=this.copiedAgentRunId===t,n=this.copiedAgentRunId===`error:${t}`,c=e.role==="assistant"&&t?`<footer class="po-answer-meta ${s?"selected":""}">
29
+ <span class="po-run-id" title="${l(t)}">问答流水号 <code>${l(t)}</code></span>
30
+ <button type="button" data-copy-run="${l(t)}">${i?"已复制":n?"复制失败":"复制流水号"}</button>
31
+ <button type="button" data-view-run="${l(t)}" aria-pressed="${s}">${s?"正在查看":"查看执行过程"}</button>
32
+ </footer>`:"";return`<article class="po-message ${e.role} ${s?"run-selected":""}" data-message="${l(e.id)}">
33
+ <b>${e.role==="user"?"你":"PageOps 分析"}</b>
34
+ <div>${e.role==="assistant"?$(e.content):l(e.content)}</div>
35
+ ${c}
36
+ </article>`}renderSourceUploader(){const e=this.sourceLoadError?"暂时无法读取项目共享代码包,连接恢复后将自动重试。":"当前项目暂无代码包,请先上传后再提问。";return`
29
37
  <div class="po-source-uploader">
30
38
  <strong>源码包</strong>
31
39
  <p>同一项目的所有回答角色共享代码包。上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
@@ -33,9 +41,16 @@
33
41
  <span>${this.sourceUploading?"上传中...":"选择代码包"}</span>
34
42
  <input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
35
43
  </label>
36
- ${this.sourceUploadStatus?`<p class="po-upload-status">${c(this.sourceUploadStatus)}</p>`:""}
44
+ ${this.sourceUploadStatus?`<p class="po-upload-status">${l(this.sourceUploadStatus)}</p>`:""}
37
45
  ${this.sourceSnapshots.length?`<div class="po-source-list">${this.sourceSnapshots.map(t=>this.renderSourceItem(t)).join("")}</div>`:`<p class="po-upload-empty">${e}</p>`}
38
- ${this.sourceLoadError?`<p class="po-upload-error">${c(this.sourceLoadError)}</p>`:""}
39
- ${this.sourceUploadError?`<p class="po-upload-error">${c(this.sourceUploadError)}</p>`:""}
46
+ ${this.sourceLoadError?`<p class="po-upload-error">${l(this.sourceLoadError)}</p>`:""}
47
+ ${this.sourceUploadError?`<p class="po-upload-error">${l(this.sourceUploadError)}</p>`:""}
40
48
  </div>
41
- `}renderSourceItem(e){var r,d,g;const t=e.filename||"未命名代码包",s=e.created_at?C(e.created_at):"刚刚上传",i=O(e.archive_bytes||e.total_bytes||0),n=String((d=(r=e.metadata)==null?void 0:r.analysis_status)!=null?d:"unknown"),l=(g={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[n])!=null?g:"项目记忆状态未知";return`<article class="po-source-item"><strong>${c(t)}</strong><span>${c(s)} · ${c(i)}</span><span>${c(l)}</span></article>`}renderSteps(){return(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",details:{message:"发送消息后展示执行过程。"}}]).map(t=>{var s;return`<details class="po-step ${t.status}" ${t.status==="running"||t.status==="failed"?"open":""}><summary><strong>${c(t.title)}</strong><span>${F(t.status)}</span></summary><pre>${c(JSON.stringify((s=t.details)!=null?s:{},null,2))}</pre></details>`}).join("")}bindPanelEvents(){var e,t,s,i,n,l,r,d,g,S,T,A,I,x,k;(t=(e=this.panel)==null?void 0:e.querySelector('[data-action="new"]'))==null||t.addEventListener("click",()=>void this.newConversation()),(i=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||i.addEventListener("click",()=>this.close()),(l=(n=this.panel)==null?void 0:n.querySelector('[data-action="stop-answer"]'))==null||l.addEventListener("click",()=>this.cancelActiveAnswer(!0)),(r=this.panel)==null||r.querySelectorAll("[data-audience]").forEach(p=>{p.addEventListener("click",()=>{var h;return void this.changeAnswerAudience((h=p.dataset.audience)!=null?h:"")})}),(g=(d=this.panel)==null?void 0:d.querySelector('[data-action="upload-source"]'))==null||g.addEventListener("change",p=>{var f;const h=(f=p.target.files)==null?void 0:f[0];h&&this.uploadSource(h)}),(S=this.panel)==null||S.querySelectorAll("[data-thread]").forEach(p=>{p.addEventListener("click",()=>{const h=this.conversations.find(f=>f.id===p.dataset.thread);h&&this.selectThread(h)})}),(T=this.panel)==null||T.querySelectorAll("[data-delete-thread]").forEach(p=>{p.addEventListener("click",h=>{h.stopPropagation();const f=this.conversations.find(v=>v.id===p.dataset.deleteThread);f&&this.deleteConversation(f)})}),(I=(A=this.panel)==null?void 0:A.querySelector("form"))==null||I.addEventListener("submit",p=>{var v;p.preventDefault();const h=(v=this.panel)==null?void 0:v.querySelector("textarea"),f=h==null?void 0:h.value.trim();f&&(h.value="",this.ask(f))}),(k=(x=this.panel)==null?void 0:x.querySelector("textarea"))==null||k.addEventListener("keydown",p=>{var f,v;const h=p;h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),(v=(f=this.panel)==null?void 0:f.querySelector("form"))==null||v.requestSubmit())})}}function c(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function C(o){return new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(new Date(o))}function O(o){if(!o)return"0 B";const e=["B","KB","MB","GB"];let t=o,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s+=1;return`${t>=10||s===0?t.toFixed(0):t.toFixed(1)} ${e[s]}`}function F(o){return{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",cancelled:"已停止"}[o]}const j=new K;m.PageOpsSDK=j,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
49
+ `}renderSourceItem(e){var a,p,g;const t=e.filename||"未命名代码包",s=e.created_at?C(e.created_at):"刚刚上传",i=j(e.archive_bytes||e.total_bytes||0),n=String((p=(a=e.metadata)==null?void 0:a.analysis_status)!=null?p:"unknown"),c=(g={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[n])!=null?g:"项目记忆状态未知";return`<article class="po-source-item"><strong>${l(t)}</strong><span>${l(s)} · ${l(i)}</span><span>${l(c)}</span></article>`}renderSteps(){return this.runLoading?'<div class="po-trace-state"><span class="po-ai-spinner" aria-hidden="true"></span><span>正在恢复本次执行过程</span></div>':this.runLoadError?`<div class="po-trace-state failed" role="alert">${l(this.runLoadError)}</div>`:(this.steps.length?this.steps:[{id:"idle",title:"等待任务",status:"pending",summary:"发送问题后,这里会展示完整分析过程。"}]).map(t=>{var c,a,p;const s=(c=t.metrics)!=null&&c.length?`<div class="po-step-metrics">${t.metrics.map(g=>`<span>${l(g)}</span>`).join("")}</div>`:"",i=(a=t.details)!=null&&a.length?`<div class="po-step-details">${t.details.map(g=>`<div><span>${l(g.label)}</span><p>${l(g.value)}</p></div>`).join("")}</div>`:"",n=!!(s||i);return`<details class="po-step ${t.status}" ${t.status==="running"||t.status==="failed"?"open":""} ${n?"":"data-static"}>
50
+ <summary>
51
+ <span class="po-step-dot" aria-hidden="true"></span>
52
+ <span class="po-step-copy"><strong>${l(t.title)}</strong><small>${l((p=t.summary)!=null?p:"")}</small></span>
53
+ <span class="po-step-status">${O(t.status)}</span>
54
+ </summary>
55
+ ${s}${i}
56
+ </details>`}).join("")}bindPanelEvents(){var e,t,s,i,n,c,a,p,g,b,R,T,I,k,x,L,q;(t=(e=this.panel)==null?void 0:e.querySelector('[data-action="new"]'))==null||t.addEventListener("click",()=>void this.newConversation()),(i=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||i.addEventListener("click",()=>this.close()),(c=(n=this.panel)==null?void 0:n.querySelector('[data-action="stop-answer"]'))==null||c.addEventListener("click",()=>this.cancelActiveAnswer(!0)),(a=this.panel)==null||a.querySelectorAll("[data-audience]").forEach(d=>{d.addEventListener("click",()=>{var h;return void this.changeAnswerAudience((h=d.dataset.audience)!=null?h:"")})}),(g=(p=this.panel)==null?void 0:p.querySelector('[data-action="upload-source"]'))==null||g.addEventListener("change",d=>{var u;const h=(u=d.target.files)==null?void 0:u[0];h&&this.uploadSource(h)}),(b=this.panel)==null||b.querySelectorAll("[data-thread]").forEach(d=>{d.addEventListener("click",()=>{const h=this.conversations.find(u=>u.id===d.dataset.thread);h&&this.selectThread(h)})}),(R=this.panel)==null||R.querySelectorAll("[data-delete-thread]").forEach(d=>{d.addEventListener("click",h=>{h.stopPropagation();const u=this.conversations.find(v=>v.id===d.dataset.deleteThread);u&&this.deleteConversation(u)})}),(T=this.panel)==null||T.querySelectorAll("[data-view-run]").forEach(d=>{d.addEventListener("click",h=>{var u;h.stopPropagation(),this.loadAgentRun((u=d.dataset.viewRun)!=null?u:"")})}),(I=this.panel)==null||I.querySelectorAll("[data-copy-run]").forEach(d=>{d.addEventListener("click",h=>{var u;h.stopPropagation(),this.copyAgentRunId((u=d.dataset.copyRun)!=null?u:"")})}),(x=(k=this.panel)==null?void 0:k.querySelector("form"))==null||x.addEventListener("submit",d=>{var v;d.preventDefault();const h=(v=this.panel)==null?void 0:v.querySelector("textarea"),u=h==null?void 0:h.value.trim();u&&(h.value="",this.ask(u))}),(q=(L=this.panel)==null?void 0:L.querySelector("textarea"))==null||q.addEventListener("keydown",d=>{var u,v;const h=d;h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),(v=(u=this.panel)==null?void 0:u.querySelector("form"))==null||v.requestSubmit())})}}function l(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function P(o){var t;const e=(t=o.metadata_json)==null?void 0:t.agent_run_id;return typeof e=="string"?e:""}function C(o){return new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(new Date(o))}function j(o){if(!o)return"0 B";const e=["B","KB","MB","GB"];let t=o,s=0;for(;t>=1024&&s<e.length-1;)t/=1024,s+=1;return`${t>=10||s===0?t.toFixed(0):t.toFixed(1)} ${e[s]}`}function O(o){return{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",cancelled:"已停止"}[o]}const D=new _;f.PageOpsSDK=D,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
package/dist/types.d.ts CHANGED
@@ -43,7 +43,23 @@ export interface ExecutionStep {
43
43
  id: string;
44
44
  title: string;
45
45
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
46
- details?: Record<string, unknown>;
46
+ summary?: string;
47
+ metrics?: string[];
48
+ details?: Array<{
49
+ label: string;
50
+ value: string;
51
+ }>;
52
+ }
53
+ export interface AgentRunHistory {
54
+ run_id: string;
55
+ status: string;
56
+ started_at: string;
57
+ updated_at: string;
58
+ duration_ms: number;
59
+ turn_count: number;
60
+ tool_call_count: number;
61
+ active_skill?: string | null;
62
+ steps: ExecutionStep[];
47
63
  }
48
64
  export interface SourceSnapshot {
49
65
  id?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pageops/sdk",
3
- "version": "0.1.12",
3
+ "version": "0.1.13",
4
4
  "description": "PageOps embeddable frontend SDK",
5
5
  "type": "module",
6
6
  "main": "dist/pageops-sdk.umd.cjs",