@pageops/sdk 0.1.28 → 0.1.30

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/index.d.ts CHANGED
@@ -36,6 +36,8 @@ declare class PageOpsSDKController {
36
36
  private streamFailure;
37
37
  private streamDone;
38
38
  private answerAudience;
39
+ private floatingRatio;
40
+ private floatingCleanup;
39
41
  private typewriter;
40
42
  mount(options: PageOpsMountOptions): void;
41
43
  unmount(): void;
@@ -43,6 +45,12 @@ declare class PageOpsSDKController {
43
45
  close(): void;
44
46
  updateContext(options: Partial<PageOpsMountOptions>): void;
45
47
  private renderClosed;
48
+ private floatingStorageKey;
49
+ private loadFloatingRatio;
50
+ private saveFloatingRatio;
51
+ private setFloatingPosition;
52
+ private bindFloatingLauncher;
53
+ private cleanupFloatingLauncher;
46
54
  private ensureContext;
47
55
  private getPageContext;
48
56
  private answerAudienceStorageKey;
@@ -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,.pageops-sdk select{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-steps{display:grid;gap:12px}.po-source-uploader{display:grid;gap:8px;padding-bottom:4px}.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:6px;background:#eff6ff;color:var(--po-primary-dark);padding:8px 10px;font-weight:750;cursor:pointer}.po-source-reference{display:grid;grid-template-columns:1fr 1fr;overflow:hidden;border:1px solid #cbd5e1;border-radius:6px;background:#fff}.po-source-reference label{display:flex;align-items:center;justify-content:center;gap:6px;min-height:32px;color:#475569;font-size:12px;font-weight:700;cursor:pointer}.po-source-reference label+label{border-left:1px solid #cbd5e1}.po-source-reference label:has(input:checked){background:#eef2ff;color:var(--po-primary-dark)}.po-source-reference input{accent-color:var(--po-primary)}.po-source-reference-value,.po-source-remark{box-sizing:border-box;width:100%;border:1px solid #cbd5e1;border-radius:6px;background:#fff;color:var(--po-text);padding:8px 9px;font:inherit;font-size:12px;outline:none}.po-source-reference-value:focus,.po-source-remark:focus{border-color:var(--po-primary);box-shadow:0 0 0 2px #4f46e51f}.po-source-remark{min-height:54px;resize:vertical}.po-upload-button input{display:none}.po-upload-status{color:#166534!important}.po-upload-progress{height:7px;overflow:hidden;border-radius:999px;background:#dbeafe}.po-upload-progress span{display:block;height:100%;border-radius:inherit;background:linear-gradient(90deg,#2563eb,#14b8a6);transition:width .2s ease}.po-upload-empty{color:#92400e!important}.po-source-selector{display:grid;gap:5px;color:var(--po-muted);font-size:12px;font-weight:700}.po-source-selector select{width:100%;border:1px solid #cbd5e1;border-radius:6px;background:#fff;color:var(--po-text);padding:7px 8px;font-size:12px;outline:none}.po-source-selector select:focus{border-color:var(--po-primary);box-shadow:0 0 0 2px #4f46e51f}.po-source-selector select:disabled{cursor:not-allowed;opacity:.62}.po-source-list{display:grid;gap:6px}.po-source-item{display:grid;gap:3px;border:1px solid #dbeafe;border-radius:6px;background:#f8fbff;padding:8px}.po-source-item.selected{border-color:#93c5fd;background:#eff6ff;box-shadow:0 0 0 1px #3b82f61f}.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}.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
+ .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,.pageops-sdk select{font:inherit}.pageops-sdk button{cursor:pointer}.po-fab{position:fixed;top:var(--pageops-fab-top,50%);right:24px;bottom:auto;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;transform:translateY(-50%);cursor:grab;touch-action:none;user-select:none;-webkit-user-select:none}.po-fab.po-fab-dragging{cursor:grabbing}.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-steps{display:grid;gap:12px}.po-source-uploader{display:grid;gap:8px;padding-bottom:4px}.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:6px;background:#eff6ff;color:var(--po-primary-dark);padding:8px 10px;font-weight:750;cursor:pointer}.po-source-reference{display:grid;grid-template-columns:1fr 1fr;overflow:hidden;border:1px solid #cbd5e1;border-radius:6px;background:#fff}.po-source-reference label{display:flex;align-items:center;justify-content:center;gap:6px;min-height:32px;color:#475569;font-size:12px;font-weight:700;cursor:pointer}.po-source-reference label+label{border-left:1px solid #cbd5e1}.po-source-reference label:has(input:checked){background:#eef2ff;color:var(--po-primary-dark)}.po-source-reference input{accent-color:var(--po-primary)}.po-source-reference-value,.po-source-remark{box-sizing:border-box;width:100%;border:1px solid #cbd5e1;border-radius:6px;background:#fff;color:var(--po-text);padding:8px 9px;font:inherit;font-size:12px;outline:none}.po-source-reference-value:focus,.po-source-remark:focus{border-color:var(--po-primary);box-shadow:0 0 0 2px #4f46e51f}.po-source-remark{min-height:54px;resize:vertical}.po-upload-button input{display:none}.po-upload-status{color:#166534!important}.po-upload-progress{height:7px;overflow:hidden;border-radius:999px;background:#dbeafe}.po-upload-progress span{display:block;height:100%;border-radius:inherit;background:linear-gradient(90deg,#2563eb,#14b8a6);transition:width .2s ease}.po-upload-empty{color:#92400e!important}.po-source-selector{display:grid;gap:5px;color:var(--po-muted);font-size:12px;font-weight:700}.po-source-selector select{width:100%;border:1px solid #cbd5e1;border-radius:6px;background:#fff;color:var(--po-text);padding:7px 8px;font-size:12px;outline:none}.po-source-selector select:focus{border-color:var(--po-primary);box-shadow:0 0 0 2px #4f46e51f}.po-source-selector select:disabled{cursor:not-allowed;opacity:.62}.po-source-list{display:grid;gap:6px}.po-source-item{display:grid;gap:3px;border:1px solid #dbeafe;border-radius:6px;background:#f8fbff;padding:8px}.po-source-item.selected{border-color:#93c5fd;background:#eff6ff;box-shadow:0 0 0 1px #3b82f61f}.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}.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(max-width:600px){.po-fab{right:12px}}@media(prefers-reduced-motion:reduce){.po-ai-spinner,.po-step-dot,.po-typing-cursor{animation:none}}
@@ -1,7 +1,7 @@
1
1
  var W = Object.defineProperty;
2
2
  var H = (a, e, t) => e in a ? W(a, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : a[e] = t;
3
3
  var i = (a, e, t) => H(a, typeof e != "symbol" ? e + "" : e, t);
4
- const UPLOAD_CHUNK_BYTES = 50 * 1024 * 1024;
4
+ const UPLOAD_MAX_BYTES = 500 * 1024 * 1024;
5
5
  class K {
6
6
  constructor(e) {
7
7
  this.options = e;
@@ -20,7 +20,7 @@ class K {
20
20
  tenant_id: e.tenantId,
21
21
  user_role: e.userRole,
22
22
  build_version: e.buildVersion,
23
- source_snapshot_id: typeof e.sourceSnapshotId == "number" ? e.sourceSnapshotId : e.sourceSnapshotId ? Number(e.sourceSnapshotId) : void 0
23
+ source_snapshot_id: e.sourceSnapshotId == null ? void 0 : e.sourceSnapshotId
24
24
  })
25
25
  });
26
26
  }
@@ -48,21 +48,10 @@ class K {
48
48
  return (await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources;
49
49
  }
50
50
  uploadSource(e, t) {
51
- if (e.size && e.size > UPLOAD_CHUNK_BYTES) return this.uploadSourceInChunks(e, t);
51
+ if (e.size && e.size > UPLOAD_MAX_BYTES) throw new Error("源码包超过 500M,请压缩后重新上传。");
52
52
  const s = new FormData();
53
53
  return s.append("file", e), t.tag && s.append("tag", t.tag), t.branch && s.append("branch", t.branch), t.remark && s.append("remark", t.remark), s.append("uploader", t.uploader || "未知用户"), this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`, { method: "POST", body: s, headers: {} }).then((r) => (t.onProgress && t.onProgress({ loaded: e.size || 0, total: e.size || 0, percent: 100, chunkIndex: 1, totalChunks: 1 }), r));
54
54
  }
55
- async uploadSourceInChunks(e, t) {
56
- const s = `${Date.now()}-${Math.random().toString(36).slice(2)}`, r = Math.max(1, Math.ceil(e.size / UPLOAD_CHUNK_BYTES));
57
- let n;
58
- t.onProgress && t.onProgress({ loaded: 0, total: e.size || 0, percent: 0, chunkIndex: 0, totalChunks: r });
59
- for (let c = 0; c < r; c += 1) {
60
- const p = new FormData(), m = c * UPLOAD_CHUNK_BYTES, g = Math.min(e.size, m + UPLOAD_CHUNK_BYTES);
61
- p.append("file", e.slice(m, g), e.name || "source.archive"), p.append("upload_id", s), p.append("chunk_index", String(c)), p.append("total_chunks", String(r)), p.append("total_size", String(e.size || 0)), p.append("filename", e.name || "source.archive"), t.tag && p.append("tag", t.tag), t.branch && p.append("branch", t.branch), t.remark && p.append("remark", t.remark), p.append("uploader", t.uploader || "未知用户"), n = await this.request(`/sources/upload/chunk?project_id=${encodeURIComponent(this.options.appId)}`, { method: "POST", body: p, headers: {} });
62
- t.onProgress && t.onProgress({ loaded: g, total: e.size || 0, percent: Math.round(g / (e.size || g || 1) * 100), chunkIndex: c + 1, totalChunks: r });
63
- }
64
- return n;
65
- }
66
55
  streamQuestion(e, t, s, r) {
67
56
  return fetch(`${this.base()}/question/stream`, {
68
57
  method: "POST",
@@ -221,6 +210,8 @@ class V {
221
210
  i(this, "streamFailure", "");
222
211
  i(this, "streamDone", null);
223
212
  i(this, "answerAudience", "business");
213
+ i(this, "floatingRatio", 0.5);
214
+ i(this, "floatingCleanup", null);
224
215
  i(this, "typewriter", new Q((e) => {
225
216
  this.streaming += e, this.updateStreamingMessage();
226
217
  }));
@@ -231,10 +222,10 @@ class V {
231
222
  }
232
223
  unmount() {
233
224
  var e;
234
- 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.selectedSourceSnapshotId = null, this.sourceUploadStatus = "", this.sourceUploadProgress = null, this.sourceUploadError = "", this.sourceLoadError = "", this.sourceUploading = !1, this.answerAudience = "business";
225
+ this.cleanupFloatingLauncher(), 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.selectedSourceSnapshotId = null, this.sourceUploadStatus = "", this.sourceUploadProgress = null, this.sourceUploadError = "", this.sourceLoadError = "", this.sourceUploading = !1, this.answerAudience = "business";
235
226
  }
236
227
  open() {
237
- 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());
228
+ this.root && (this.cleanupFloatingLauncher(), this.root.innerHTML = "", this.panel = document.createElement("div"), this.panel.className = "po-panel", this.root.appendChild(this.panel), this.loadSources(), this.loadConversations(), this.renderPanel());
238
229
  }
239
230
  close() {
240
231
  this.stopSourceRefresh(), this.cancelActiveAnswer(!1), this.renderClosed();
@@ -246,7 +237,58 @@ class V {
246
237
  }
247
238
  renderClosed() {
248
239
  var e;
249
- this.root && (this.root.innerHTML = '<button class="po-fab" type="button">多轮问答</button>', (e = this.root.querySelector("button")) == null || e.addEventListener("click", () => this.open()));
240
+ this.root && (this.cleanupFloatingLauncher(), this.root.innerHTML = '<button class="po-fab" type="button">多轮问答</button>', e = this.root.querySelector("button"), e && (this.bindFloatingLauncher(e), e.addEventListener("click", () => this.open())));
241
+ }
242
+ floatingStorageKey() {
243
+ var e;
244
+ return `pageops:floating-position:${((e = this.options) == null ? void 0 : e.appId) || "default"}`;
245
+ }
246
+ loadFloatingRatio() {
247
+ try {
248
+ const e = localStorage.getItem(this.floatingStorageKey());
249
+ if (e === null) return 0.5;
250
+ const t = Number(e);
251
+ return Number.isFinite(t) && t >= 0 && t <= 1 ? t : 0.5;
252
+ } catch (e) {
253
+ return 0.5;
254
+ }
255
+ }
256
+ saveFloatingRatio() {
257
+ try {
258
+ localStorage.setItem(this.floatingStorageKey(), String(this.floatingRatio));
259
+ } catch (e) {
260
+ }
261
+ }
262
+ setFloatingPosition(e, t) {
263
+ if (!this.root) return;
264
+ const s = Math.max(e.getBoundingClientRect().height / 2, 24), r = 12 + s, n = window.innerHeight - 12 - s, c = n < r ? (r + n) / 2 : Math.min(Math.max(t, r), n);
265
+ this.floatingRatio = window.innerHeight > 0 ? c / window.innerHeight : 0.5, this.root.style.setProperty("--pageops-fab-top", `${c}px`);
266
+ }
267
+ bindFloatingLauncher(e) {
268
+ this.cleanupFloatingLauncher(), this.floatingRatio = this.loadFloatingRatio(), this.setFloatingPosition(e, window.innerHeight * this.floatingRatio);
269
+ let t = null, s = !1;
270
+ const r = (o) => {
271
+ if (!t || o.pointerId !== t.pointerId) return;
272
+ s = t.moved, e.classList.remove("po-fab-dragging"), e.hasPointerCapture && e.hasPointerCapture(o.pointerId) && e.releasePointerCapture(o.pointerId), t.moved && this.saveFloatingRatio(), t = null;
273
+ }, n = (o) => {
274
+ if (typeof o.button == "number" && o.button !== 0) return;
275
+ const l = e.getBoundingClientRect();
276
+ t = { pointerId: o.pointerId, startClientY: o.clientY, startCenterY: l.top + l.height / 2, moved: !1 }, e.setPointerCapture && e.setPointerCapture(o.pointerId), e.classList.add("po-fab-dragging");
277
+ }, c = (o) => {
278
+ if (!t || o.pointerId !== t.pointerId) return;
279
+ const l = o.clientY - t.startClientY;
280
+ !t.moved && Math.abs(l) >= 4 && (t.moved = !0), t.moved && (o.preventDefault(), this.setFloatingPosition(e, t.startCenterY + l));
281
+ }, p = (o) => {
282
+ s && (s = !1, o.preventDefault(), o.stopImmediatePropagation());
283
+ }, m = () => {
284
+ e.isConnected && this.setFloatingPosition(e, window.innerHeight * this.floatingRatio);
285
+ };
286
+ e.addEventListener("pointerdown", n), e.addEventListener("pointermove", c), e.addEventListener("pointerup", r), e.addEventListener("pointercancel", r), e.addEventListener("click", p, !0), window.addEventListener("resize", m), this.floatingCleanup = () => {
287
+ e.removeEventListener("pointerdown", n), e.removeEventListener("pointermove", c), e.removeEventListener("pointerup", r), e.removeEventListener("pointercancel", r), e.removeEventListener("click", p, !0), window.removeEventListener("resize", m);
288
+ };
289
+ }
290
+ cleanupFloatingLauncher() {
291
+ this.floatingCleanup && (this.floatingCleanup(), this.floatingCleanup = null), this.root && this.root.style.removeProperty("--pageops-fab-top");
250
292
  }
251
293
  async ensureContext() {
252
294
  if (!this.client || !this.options) throw new Error("PageOps SDK 未初始化");
@@ -255,10 +297,11 @@ class V {
255
297
  }
256
298
  getPageContext() {
257
299
  var e, t, s;
300
+ const r = this.selectedSourceSnapshot(), n = this.selectedSourceSnapshotId != null ? this.selectedSourceSnapshotId : r ? this.sourceSnapshotValue(r) : null;
258
301
  return {
259
302
  ...(s = (t = (e = this.options) == null ? void 0 : e.getPageContext) == null ? void 0 : t.call(e)) != null ? s : {},
260
303
  userRole: this.answerAudience,
261
- sourceSnapshotId: this.selectedSourceSnapshotId
304
+ sourceSnapshotId: n == null ? void 0 : n
262
305
  };
263
306
  }
264
307
  answerAudienceStorageKey(e) {
@@ -297,7 +340,7 @@ class V {
297
340
  }
298
341
  selectSourceSnapshot(e) {
299
342
  if (this.asking) return;
300
- const t = e ? Number(e) : null, s = t == null || Number.isNaN(t) ? null : t;
343
+ const s = e === "" ? null : e;
301
344
  if ((this.selectedSourceSnapshotId == null ? "" : String(this.selectedSourceSnapshotId)) === (s == null ? "" : String(s))) return;
302
345
  this.selectedSourceSnapshotId = s, 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.renderPanel();
303
346
  }
@@ -313,7 +356,8 @@ class V {
313
356
  async loadSources() {
314
357
  if (this.client) {
315
358
  try {
316
- this.sourceSnapshots = await this.client.listSources(), this.sourceLoadError = "";
359
+ const e = await this.client.listSources(), t = e[0], s = t ? this.sourceSnapshotValue(t) : null, r = this.context && this.context.source_snapshot_id != null ? String(this.context.source_snapshot_id) : null, n = this.selectedSourceSnapshotId == null && s != null && r !== s && (this.context != null || this.currentThread != null);
360
+ this.sourceSnapshots = e, this.sourceLoadError = "", n && (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);
317
361
  } catch (e) {
318
362
  this.sourceLoadError = "源码包状态加载失败,连接恢复后将自动重试。";
319
363
  }
@@ -684,7 +728,7 @@ function l(a) {
684
728
  function M(a) {
685
729
  var t;
686
730
  const e = (t = a.metadata_json) == null ? void 0 : t.agent_run_id;
687
- return typeof e == "string" ? e : "";
731
+ return typeof e == "number" ? String(e) : typeof e == "string" ? e : "";
688
732
  }
689
733
  function O(a) {
690
734
  return new Intl.DateTimeFormat("zh-CN", {
@@ -1,39 +1,616 @@
1
- (function(y,m){typeof exports=="object"&&typeof module!="undefined"?m(exports):typeof define=="function"&&define.amd?define(["exports"],m):(y=typeof globalThis!="undefined"?globalThis:y||self,m(y.PageOpsSDK={}))})(this,(function(y){"use strict";var X=Object.defineProperty;var Y=(y,m,b)=>m in y?X(y,m,{enumerable:!0,configurable:!0,writable:!0,value:b}):y[m]=b;var i=(y,m,b)=>Y(y,typeof m!="symbol"?m+"":m,b);const U=50*1024*1024;class m{constructor(e){this.options=e}async createContext(e=(r=>(r=(t=>(s=>(s=(t=this.options).getPageContext)==null?void 0:s.call(t))())())!=null?r:{})()){var n,c,p;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:(p=e.menuPath)!=null?p:[],tenant_id:e.tenantId,user_role:e.userRole,build_version:e.buildVersion,source_snapshot_id:typeof e.sourceSnapshotId=="number"?e.sourceSnapshotId:e.sourceSnapshotId?Number(e.sourceSnapshotId):void 0})})}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,t){if(e.size&&e.size>U)return this.uploadSourceInChunks(e,t);const s=new FormData;return s.append("file",e),t.tag&&s.append("tag",t.tag),t.branch&&s.append("branch",t.branch),t.remark&&s.append("remark",t.remark),s.append("uploader",t.uploader||"未知用户"),this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:s,headers:{}}).then(r=>(t.onProgress&&t.onProgress({loaded:e.size||0,total:e.size||0,percent:100,chunkIndex:1,totalChunks:1}),r))}async uploadSourceInChunks(e,t){const s=`${Date.now()}-${Math.random().toString(36).slice(2)}`,r=Math.max(1,Math.ceil(e.size/U));let n;t.onProgress&&t.onProgress({loaded:0,total:e.size||0,percent:0,chunkIndex:0,totalChunks:r});for(let c=0;c<r;c+=1){const p=new FormData,m=c*U,g=Math.min(e.size,m+U);p.append("file",e.slice(m,g),e.name||"source.archive"),p.append("upload_id",s),p.append("chunk_index",String(c)),p.append("total_chunks",String(r)),p.append("total_size",String(e.size||0)),p.append("filename",e.name||"source.archive"),t.tag&&p.append("tag",t.tag),t.branch&&p.append("branch",t.branch),t.remark&&p.append("remark",t.remark),p.append("uploader",t.uploader||"未知用户"),n=await this.request(`/sources/upload/chunk?project_id=${encodeURIComponent(this.options.appId)}`,{method:"POST",body:p,headers:{}}),t.onProgress&&t.onProgress({loaded:g,total:e.size||0,percent:Math.round(g/(e.size||g||1)*100),chunkIndex:c+1,totalChunks:r})}return n}streamQuestion(e,t,s,r){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,user_role:s}),signal:r})}async request(e,t){var c,p;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:{}},r=await fetch(`${this.base()}${e}`,{...t,headers:s});if(r.status===204)return;const n=await r.json().catch(()=>null);if(!r.ok)throw new Error((p=n==null?void 0:n.message)!=null?p:r.status===413?"源码包超过网关上传大小限制,请压缩代码包或联系管理员调整上传限制。":"PageOps 请求失败");return n}base(){const e=this.options.apiBase.replace(/\/$/,"");return e.endsWith("/api")||e.endsWith("/dc/ai")?e:`${e}/dc/ai`}}async function b(a,e){const t=await a.json().catch(()=>null);return typeof(t==null?void 0:t.message)=="string"&&t.message.trim()?t.message:e}function x(a){return String(a==null?"":a).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function S(a){return x(a).replace(/`([^`]+)`/g,"<code>$1</code>").replace(/\*\*([^*]+)\*\*/g,"<strong>$1</strong>")}function H(a,e){const t=a[e],s=a[e+1];if(!(t!=null&&t.includes("|"))||!/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s!=null?s:""))return null;const r=[];let n=e;for(;n<a.length&&a[n].includes("|")&&a[n].trim();)r.push(a[n]),n+=1;const c=g=>g.trim().replace(/^\|/,"").replace(/\|$/,"").split("|").map(o=>S(o.trim())),p=c(r[0]).map(g=>`<th>${g}</th>`).join(""),f=r.slice(2).map(g=>`<tr>${c(g).map(o=>`<td>${o}</td>`).join("")}</tr>`).join("");return{html:`<table><thead><tr>${p}</tr></thead><tbody>${f}</tbody></table>`,next:n}}function k(a){const e=a.split(`
2
- `),t=[];for(let s=0;s<e.length;s+=1){const r=e[s];if(r.trim().startsWith("```")){const c=[];for(s+=1;s<e.length&&!e[s].trim().startsWith("```");)c.push(e[s]),s+=1;t.push(`<pre><code>${x(c.join(`
3
- `))}</code></pre>`);continue}const n=H(e,s);if(n){t.push(n.html),s=n.next-1;continue}r.startsWith("### ")?t.push(`<h4>${S(r.slice(4))}</h4>`):r.startsWith("## ")?t.push(`<h3>${S(r.slice(3))}</h3>`):r.startsWith("# ")?t.push(`<h2>${S(r.slice(2))}</h2>`):r.startsWith("- ")?t.push(`<li>${S(r.slice(2))}</li>`):r.trim()?t.push(`<p>${S(r)}</p>`):t.push("<br>")}return t.join("")}async function z(a,e){var n;const t=a.getReader(),s=new TextDecoder;let r="";for(;;){const{done:c,value:p}=await t.read();if(c){r+=s.decode();break}r+=s.decode(p,{stream:!0});const f=r.split(/\r?\n\r?\n/);r=(n=f.pop())!=null?n:"";for(const g of f)q(g,e)}r.trim()&&q(r,e)}function q(a,e){var r,n;const t=(r=a.match(/^event:\s*(.+)$/m))==null?void 0:r[1],s=(n=a.match(/^data:\s*(.+)$/m))==null?void 0:n[1];t&&s&&e(t,JSON.parse(s))}class N{constructor(e,t=16){i(this,"queue",[]);i(this,"timer",null);i(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 I=[{value:"product",label:"产品"},{value:"business",label:"业务"},{value:"developer",label:"研发"},{value:"tester",label:"测试"}];class J{constructor(){i(this,"client",null);i(this,"options",null);i(this,"root",null);i(this,"panel",null);i(this,"context",null);i(this,"contextKey","");i(this,"selectedPageKey","");i(this,"currentThread",null);i(this,"conversations",[]);i(this,"messages",[]);i(this,"steps",[]);i(this,"selectedAgentRunId","");i(this,"runLoading",!1);i(this,"runLoadError","");i(this,"copiedAgentRunId","");i(this,"copyFeedbackTimer",null);i(this,"sourceSnapshots",[]);i(this,"selectedSourceSnapshotId",null);i(this,"sourceUploadStatus","");i(this,"sourceUploadProgress",null);i(this,"sourceUploadError","");i(this,"sourceLoadError","");i(this,"sourceUploading",!1);i(this,"sourceRefreshTimer",null);i(this,"streaming","");i(this,"asking",!1);i(this,"waitingForFirstContent",!1);i(this,"abortController",null);i(this,"activeRunId",0);i(this,"stoppedRunId",-1);i(this,"answerStopped",!1);i(this,"answerError","");i(this,"conversationError","");i(this,"deletingThreadId","");i(this,"streamFailure","");i(this,"streamDone",null);i(this,"answerAudience","business");i(this,"typewriter",new N(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.selectedSourceSnapshotId=null,this.sourceUploadStatus="",this.sourceUploadProgress=null,this.sourceUploadError="",this.sourceLoadError="",this.sourceUploading=!1,this.answerAudience="business"}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.selectedSourceSnapshotId=null,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,sourceSnapshotId:this.selectedSourceSnapshotId}}answerAudienceStorageKey(e){return`pageops:answer-audience:${e}`}loadAnswerAudience(e){try{const t=localStorage.getItem(this.answerAudienceStorageKey(e));return I.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){}}changeAnswerAudience(e){var s;if(this.asking)return;const t=(s=I.find(r=>r.value===e))==null?void 0:s.value;!t||t===this.answerAudience||(this.answerAudience=t,this.saveAnswerAudience(),this.renderPanel())}getPageContextKey(e){var t,s,r,n;return JSON.stringify([(t=e.route)!=null?t:"",(s=e.url)!=null?s:location.href,(r=e.title)!=null?r:document.title,(n=e.menuPath)!=null?n:[],e.sourceSnapshotId==null?"":String(e.sourceSnapshotId)])}selectSourceSnapshot(e){if(this.asking)return;const t=e?Number(e):null,s=t==null||Number.isNaN(t)?null:t;if((this.selectedSourceSnapshotId==null?"":String(this.selectedSourceSnapshotId))===(s==null?"":String(s)))return;this.selectedSourceSnapshotId=s,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.renderPanel()}sourceSnapshotValue(e){var t,s;return String((s=(t=e.id)!=null?t:e.source_snapshot_id)!=null?s:"")}selectedSourceSnapshot(){if(this.selectedSourceSnapshotId==null)return this.sourceSnapshots[0];const e=String(this.selectedSourceSnapshotId);return this.sourceSnapshots.find(t=>this.sourceSnapshotValue(t)===e)}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(L).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,t){var s;if(this.client){this.sourceUploading=!0,this.sourceUploadProgress=0,this.sourceUploadStatus="上传中 0%",this.sourceUploadError="",this.renderPanel();try{await this.client.uploadSource(e,{...t,uploader:(s=this.options)==null?void 0:s.uploader,onProgress:r=>{this.sourceUploadProgress=Math.max(0,Math.min(100,Math.round(r.percent))),this.sourceUploadStatus=`上传中 ${this.sourceUploadProgress}%`,this.renderPanel()}}),this.sourceSnapshots=await this.client.listSources(),this.sourceUploadStatus=this.isProjectMemoryUpdating()?"源码上传完成,项目记忆更新中...":"上传完成",this.scheduleSourceRefresh()}catch(r){this.sourceUploadError=r instanceof Error?r.message:"源码包上传失败",this.sourceUploadStatus=""}finally{this.sourceUploading=!1,this.sourceUploadProgress=null,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,r=new AbortController;this.abortController=r,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,this.answerAudience,r.signal);if(!c.ok)throw new Error(await b(c,"服务暂时无法回答,请稍后重试。"));if(!c.body)throw new Error("服务未返回有效的流式响应,请稍后重试。");if(await z(c.body,(p,f)=>this.handleStreamEvent(p,f)),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");if(this.streamFailure)throw new Error(this.streamFailure);if(!this.streamDone)throw new Error("服务响应意外中断,请稍后重试。");if(await this.typewriter.drain(),s===this.stoppedRunId)throw new DOMException("输出已停止","AbortError");await this.selectThread(this.currentThread)}catch(n){if(s!==this.activeRunId)return;this.typewriter.clear(),this.waitingForFirstContent=!1,s===this.stoppedRunId?this.answerStopped=!0:(this.answerError=n instanceof Error?n.message:"服务异常,请稍后重试。",this.upsertStep({id:"error",title:"执行失败",status:"failed",summary:this.answerError}))}finally{if(s!==this.activeRunId)return;this.asking=!1,this.waitingForFirstContent=!1,this.abortController===r&&(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(r=>r.status==="running"?{...r,status:"cancelled"}:r);this.steps=s.some(r=>r.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,r;if(e==="step"){this.upsertStep(t),this.renderExecutionSteps(!0);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((r=t.message)!=null?r:"服务异常,请稍后重试。"))}updateStreamingMessage(){var s,r;const e=(s=this.panel)==null?void 0:s.querySelector("[data-streaming-content]");if(!e){this.renderPanel();return}e.innerHTML=k(this.streaming);const t=(r=this.panel)==null?void 0:r.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");if(s.value=e,s.style.position="fixed",s.style.opacity="0",document.body.appendChild(s),s.select(),!document.execCommand("copy"))throw new Error("copy_not_supported");s.remove()}this.copiedAgentRunId=e}catch(s){this.copiedAgentRunId=`error:${e}`}this.clearCopyFeedback(!1),this.copyFeedbackTimer=setTimeout(()=>{this.copiedAgentRunId="",this.copyFeedbackTimer=null,this.updateCopyFeedback()},1800),this.updateCopyFeedback()}}updateCopyFeedback(){var e;(e=this.panel)==null||e.querySelectorAll("[data-copy-run]").forEach(t=>{var r;const s=(r=t.dataset.copyRun)!=null?r:"";t.textContent=this.copiedAgentRunId===s?"已复制":this.copiedAgentRunId===`error:${s}`?"复制失败":"复制流水号"})}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.selectedSourceSnapshot())==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,t=!1){var g;if(!this.panel)return;const s=(g=this.panel.querySelector(".po-messages"))==null?void 0:g.scrollTop,r=this.questionUnavailableReason(),n=r||(this.asking?"回答生成中,请稍候":"请输入页面分析问题,Enter 发送,Shift + Enter 换行"),c=!!(r||this.asking),p=r?'<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>',f=I.map(o=>`
4
- <button type="button" data-audience="${o.value}" aria-pressed="${o.value===this.answerAudience}" ${this.asking?"disabled":""}>${o.label}</button>
5
- `).join("");if(this.panel.innerHTML=`
1
+ (function(g,f){typeof exports==='object'&&typeof module!=='undefined'?f(exports):typeof define==='function'&&define.amd?define(['exports'],f):(g=typeof globalThis!=='undefined'?globalThis:g||self,f(g.PageOpsSDK={}));})(this,(function(exports){'use strict';var W = Object.defineProperty;
2
+ var H = (a, e, t) => e in a ? W(a, e, { enumerable: true, configurable: true, writable: true, value: t }) : a[e] = t;
3
+ var i = (a, e, t) => H(a, typeof e != "symbol" ? e + "" : e, t);
4
+ const UPLOAD_MAX_BYTES = 500 * 1024 * 1024;
5
+ class K {
6
+ constructor(e) {
7
+ this.options = e;
8
+ }
9
+ async createContext(e = ((r) => (r = ((t) => ((s) => (s = (t = this.options).getPageContext) == null ? void 0 : s.call(t))())()) != null ? r : {})()) {
10
+ var n, c, p;
11
+ return this.request("/context/session", {
12
+ method: "POST",
13
+ body: JSON.stringify({
14
+ app_id: this.options.appId,
15
+ env: this.options.env,
16
+ route: e.route,
17
+ url: (n = e.url) != null ? n : location.href,
18
+ title: (c = e.title) != null ? c : document.title,
19
+ menu_path: (p = e.menuPath) != null ? p : [],
20
+ tenant_id: e.tenantId,
21
+ user_role: e.userRole,
22
+ build_version: e.buildVersion,
23
+ source_snapshot_id: e.sourceSnapshotId == null ? void 0 : e.sourceSnapshotId
24
+ })
25
+ });
26
+ }
27
+ async listConversations() {
28
+ return (await this.request(`/conversations?app_id=${encodeURIComponent(this.options.appId)}`)).conversations;
29
+ }
30
+ async createConversation(e, t) {
31
+ return this.request("/conversations", {
32
+ method: "POST",
33
+ body: JSON.stringify({ app_id: this.options.appId, context_session_id: e, title: t })
34
+ });
35
+ }
36
+ async deleteConversation(e) {
37
+ return this.request(`/conversations/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`, {
38
+ method: "DELETE"
39
+ });
40
+ }
41
+ async listMessages(e) {
42
+ return (await this.request(`/conversations/${encodeURIComponent(e)}/messages?app_id=${encodeURIComponent(this.options.appId)}`)).messages;
43
+ }
44
+ async getAgentRun(e) {
45
+ return this.request(`/question/runs/${encodeURIComponent(e)}?app_id=${encodeURIComponent(this.options.appId)}`);
46
+ }
47
+ async listSources() {
48
+ return (await this.request(`/sources?project_id=${encodeURIComponent(this.options.appId)}`)).sources;
49
+ }
50
+ uploadSource(e, t) {
51
+ if (e.size && e.size > UPLOAD_MAX_BYTES) throw new Error("源码包超过 500M,请压缩后重新上传。");
52
+ const s = new FormData();
53
+ return s.append("file", e), t.tag && s.append("tag", t.tag), t.branch && s.append("branch", t.branch), t.remark && s.append("remark", t.remark), s.append("uploader", t.uploader || "未知用户"), this.request(`/sources/upload?project_id=${encodeURIComponent(this.options.appId)}`, { method: "POST", body: s, headers: {} }).then((r) => (t.onProgress && t.onProgress({ loaded: e.size || 0, total: e.size || 0, percent: 100, chunkIndex: 1, totalChunks: 1 }), r));
54
+ }
55
+ streamQuestion(e, t, s, r) {
56
+ return fetch(`${this.base()}/question/stream`, {
57
+ method: "POST",
58
+ headers: { "content-type": "application/json" },
59
+ body: JSON.stringify({ app_id: this.options.appId, thread_id: e, question: t, user_role: s }),
60
+ signal: r
61
+ });
62
+ }
63
+ async request(e, t) {
64
+ var c, p;
65
+ 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 : {} }, r = await fetch(`${this.base()}${e}`, { ...t, headers: s });
66
+ if (r.status === 204) return;
67
+ const n = await r.json().catch(() => null);
68
+ if (!r.ok) throw new Error((p = n == null ? void 0 : n.message) != null ? p : r.status === 413 ? "源码包超过网关上传大小限制,请压缩代码包或联系管理员调整上传限制。" : "PageOps 请求失败");
69
+ return n;
70
+ }
71
+ base() {
72
+ const e = this.options.apiBase.replace(/\/$/, "");
73
+ return e.endsWith("/api") || e.endsWith("/dc/ai") ? e : `${e}/dc/ai`;
74
+ }
75
+ }
76
+ async function z(a, e) {
77
+ const t = await a.json().catch(() => null);
78
+ return typeof (t == null ? void 0 : t.message) == "string" && t.message.trim() ? t.message : e;
79
+ }
80
+ function D(a) {
81
+ return String(a == null ? "" : a).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
82
+ }
83
+ function v(a) {
84
+ return D(a).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
85
+ }
86
+ function N(a, e) {
87
+ const t = a[e], s = a[e + 1];
88
+ if (!(t != null && t.includes("|")) || !/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(s != null ? s : "")) return null;
89
+ const r = [];
90
+ let n = e;
91
+ for (; n < a.length && a[n].includes("|") && a[n].trim(); )
92
+ r.push(a[n]), n += 1;
93
+ const c = (g) => g.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((o) => v(o.trim())), p = c(r[0]).map((g) => `<th>${g}</th>`).join(""), m = r.slice(2).map((g) => `<tr>${c(g).map((o) => `<td>${o}</td>`).join("")}</tr>`).join("");
94
+ return { html: `<table><thead><tr>${p}</tr></thead><tbody>${m}</tbody></table>`, next: n };
95
+ }
96
+ function R(a) {
97
+ const e = a.split(`
98
+ `), t = [];
99
+ for (let s = 0; s < e.length; s += 1) {
100
+ const r = e[s];
101
+ if (r.trim().startsWith("```")) {
102
+ const c = [];
103
+ for (s += 1; s < e.length && !e[s].trim().startsWith("```"); )
104
+ c.push(e[s]), s += 1;
105
+ t.push(`<pre><code>${D(c.join(`
106
+ `))}</code></pre>`);
107
+ continue;
108
+ }
109
+ const n = N(e, s);
110
+ if (n) {
111
+ t.push(n.html), s = n.next - 1;
112
+ continue;
113
+ }
114
+ r.startsWith("### ") ? t.push(`<h4>${v(r.slice(4))}</h4>`) : r.startsWith("## ") ? t.push(`<h3>${v(r.slice(3))}</h3>`) : r.startsWith("# ") ? t.push(`<h2>${v(r.slice(2))}</h2>`) : r.startsWith("- ") ? t.push(`<li>${v(r.slice(2))}</li>`) : r.trim() ? t.push(`<p>${v(r)}</p>`) : t.push("<br>");
115
+ }
116
+ return t.join("");
117
+ }
118
+ async function J(a, e) {
119
+ var n;
120
+ const t = a.getReader(), s = new TextDecoder();
121
+ let r = "";
122
+ for (; ; ) {
123
+ const { done: c, value: p } = await t.read();
124
+ if (c) {
125
+ r += s.decode();
126
+ break;
127
+ }
128
+ r += s.decode(p, { stream: true });
129
+ const m = r.split(/\r?\n\r?\n/);
130
+ r = (n = m.pop()) != null ? n : "";
131
+ for (const g of m) j(g, e);
132
+ }
133
+ r.trim() && j(r, e);
134
+ }
135
+ function j(a, e) {
136
+ var r, n;
137
+ const t = (r = a.match(/^event:\s*(.+)$/m)) == null ? void 0 : r[1], s = (n = a.match(/^data:\s*(.+)$/m)) == null ? void 0 : n[1];
138
+ t && s && e(t, JSON.parse(s));
139
+ }
140
+ class Q {
141
+ constructor(e, t = 16) {
142
+ i(this, "queue", []);
143
+ i(this, "timer", null);
144
+ i(this, "drainWaiters", []);
145
+ this.onChunk = e, this.interval = t;
146
+ }
147
+ enqueue(e) {
148
+ this.queue.push(...Array.from(e)), this.timer || this.tick();
149
+ }
150
+ async drain() {
151
+ !this.timer && !this.queue.length || await new Promise((e) => this.drainWaiters.push(e));
152
+ }
153
+ clear() {
154
+ this.timer && clearTimeout(this.timer), this.timer = null, this.queue = [], this.resolveDrainWaiters();
155
+ }
156
+ tick() {
157
+ const e = Math.max(1, Math.ceil(this.queue.length / 90)), t = this.queue.splice(0, e).join("");
158
+ if (t && this.onChunk(t), !this.queue.length) {
159
+ this.timer = null, this.resolveDrainWaiters();
160
+ return;
161
+ }
162
+ this.timer = setTimeout(() => this.tick(), this.interval);
163
+ }
164
+ resolveDrainWaiters() {
165
+ for (const e of this.drainWaiters.splice(0)) e();
166
+ }
167
+ }
168
+ const C = [
169
+ { value: "product", label: "产品" },
170
+ { value: "business", label: "业务" },
171
+ { value: "developer", label: "研发" },
172
+ { value: "tester", label: "测试" }
173
+ ];
174
+ class V {
175
+ constructor() {
176
+ i(this, "client", null);
177
+ i(this, "options", null);
178
+ i(this, "root", null);
179
+ i(this, "panel", null);
180
+ i(this, "context", null);
181
+ i(this, "contextKey", "");
182
+ i(this, "selectedPageKey", "");
183
+ i(this, "currentThread", null);
184
+ i(this, "conversations", []);
185
+ i(this, "messages", []);
186
+ i(this, "steps", []);
187
+ i(this, "selectedAgentRunId", "");
188
+ i(this, "runLoading", false);
189
+ i(this, "runLoadError", "");
190
+ i(this, "copiedAgentRunId", "");
191
+ i(this, "copyFeedbackTimer", null);
192
+ i(this, "sourceSnapshots", []);
193
+ i(this, "selectedSourceSnapshotId", null);
194
+ i(this, "sourceUploadStatus", "");
195
+ i(this, "sourceUploadProgress", null);
196
+ i(this, "sourceUploadError", "");
197
+ i(this, "sourceLoadError", "");
198
+ i(this, "sourceUploading", false);
199
+ i(this, "sourceRefreshTimer", null);
200
+ i(this, "streaming", "");
201
+ i(this, "asking", false);
202
+ i(this, "waitingForFirstContent", false);
203
+ i(this, "abortController", null);
204
+ i(this, "activeRunId", 0);
205
+ i(this, "stoppedRunId", -1);
206
+ i(this, "answerStopped", false);
207
+ i(this, "answerError", "");
208
+ i(this, "conversationError", "");
209
+ i(this, "deletingThreadId", "");
210
+ i(this, "streamFailure", "");
211
+ i(this, "streamDone", null);
212
+ i(this, "answerAudience", "business");
213
+ i(this, "floatingRatio", 0.5);
214
+ i(this, "floatingCleanup", null);
215
+ i(this, "typewriter", new Q((e) => {
216
+ this.streaming += e, this.updateStreamingMessage();
217
+ }));
218
+ }
219
+ mount(e) {
220
+ var t;
221
+ this.unmount(), this.options = e, this.client = new K(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();
222
+ }
223
+ unmount() {
224
+ var e;
225
+ this.cleanupFloatingLauncher(), this.stopSourceRefresh(), this.cancelActiveAnswer(false), 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 = false, this.runLoadError = "", this.clearCopyFeedback(), this.sourceSnapshots = [], this.selectedSourceSnapshotId = null, this.sourceUploadStatus = "", this.sourceUploadProgress = null, this.sourceUploadError = "", this.sourceLoadError = "", this.sourceUploading = false, this.answerAudience = "business";
226
+ }
227
+ open() {
228
+ this.root && (this.cleanupFloatingLauncher(), this.root.innerHTML = "", this.panel = document.createElement("div"), this.panel.className = "po-panel", this.root.appendChild(this.panel), this.loadSources(), this.loadConversations(), this.renderPanel());
229
+ }
230
+ close() {
231
+ this.stopSourceRefresh(), this.cancelActiveAnswer(false), this.renderClosed();
232
+ }
233
+ updateContext(e) {
234
+ if (!this.options) return;
235
+ const t = this.options.appId;
236
+ this.options = { ...this.options, ...e }, this.client = new K(this.options), this.options.appId !== t && (this.answerAudience = this.loadAnswerAudience(this.options.appId), this.selectedSourceSnapshotId = null, this.currentThread = null, this.selectedPageKey = "", this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = ""), this.context = null, this.contextKey = "", this.renderPanel();
237
+ }
238
+ renderClosed() {
239
+ var e;
240
+ this.root && (this.cleanupFloatingLauncher(), this.root.innerHTML = '<button class="po-fab" type="button">多轮问答</button>', e = this.root.querySelector("button"), e && (this.bindFloatingLauncher(e), e.addEventListener("click", () => this.open())));
241
+ }
242
+ floatingStorageKey() {
243
+ var e;
244
+ return `pageops:floating-position:${((e = this.options) == null ? void 0 : e.appId) || "default"}`;
245
+ }
246
+ loadFloatingRatio() {
247
+ try {
248
+ const e = localStorage.getItem(this.floatingStorageKey());
249
+ if (e === null) return 0.5;
250
+ const t = Number(e);
251
+ return Number.isFinite(t) && t >= 0 && t <= 1 ? t : 0.5;
252
+ } catch (e) {
253
+ return 0.5;
254
+ }
255
+ }
256
+ saveFloatingRatio() {
257
+ try {
258
+ localStorage.setItem(this.floatingStorageKey(), String(this.floatingRatio));
259
+ } catch (e) {
260
+ }
261
+ }
262
+ setFloatingPosition(e, t) {
263
+ if (!this.root) return;
264
+ const s = Math.max(e.getBoundingClientRect().height / 2, 24), r = 12 + s, n = window.innerHeight - 12 - s, c = n < r ? (r + n) / 2 : Math.min(Math.max(t, r), n);
265
+ this.floatingRatio = window.innerHeight > 0 ? c / window.innerHeight : 0.5, this.root.style.setProperty("--pageops-fab-top", `${c}px`);
266
+ }
267
+ bindFloatingLauncher(e) {
268
+ this.cleanupFloatingLauncher(), this.floatingRatio = this.loadFloatingRatio(), this.setFloatingPosition(e, window.innerHeight * this.floatingRatio);
269
+ let t = null, s = false;
270
+ const r = (o) => {
271
+ if (!t || o.pointerId !== t.pointerId) return;
272
+ s = t.moved, e.classList.remove("po-fab-dragging"), e.hasPointerCapture && e.hasPointerCapture(o.pointerId) && e.releasePointerCapture(o.pointerId), t.moved && this.saveFloatingRatio(), t = null;
273
+ }, n = (o) => {
274
+ if (typeof o.button == "number" && o.button !== 0) return;
275
+ const l = e.getBoundingClientRect();
276
+ t = { pointerId: o.pointerId, startClientY: o.clientY, startCenterY: l.top + l.height / 2, moved: false }, e.setPointerCapture && e.setPointerCapture(o.pointerId), e.classList.add("po-fab-dragging");
277
+ }, c = (o) => {
278
+ if (!t || o.pointerId !== t.pointerId) return;
279
+ const l = o.clientY - t.startClientY;
280
+ !t.moved && Math.abs(l) >= 4 && (t.moved = true), t.moved && (o.preventDefault(), this.setFloatingPosition(e, t.startCenterY + l));
281
+ }, p = (o) => {
282
+ s && (s = false, o.preventDefault(), o.stopImmediatePropagation());
283
+ }, m = () => {
284
+ e.isConnected && this.setFloatingPosition(e, window.innerHeight * this.floatingRatio);
285
+ };
286
+ e.addEventListener("pointerdown", n), e.addEventListener("pointermove", c), e.addEventListener("pointerup", r), e.addEventListener("pointercancel", r), e.addEventListener("click", p, true), window.addEventListener("resize", m), this.floatingCleanup = () => {
287
+ e.removeEventListener("pointerdown", n), e.removeEventListener("pointermove", c), e.removeEventListener("pointerup", r), e.removeEventListener("pointercancel", r), e.removeEventListener("click", p, true), window.removeEventListener("resize", m);
288
+ };
289
+ }
290
+ cleanupFloatingLauncher() {
291
+ this.floatingCleanup && (this.floatingCleanup(), this.floatingCleanup = null), this.root && this.root.style.removeProperty("--pageops-fab-top");
292
+ }
293
+ async ensureContext() {
294
+ if (!this.client || !this.options) throw new Error("PageOps SDK 未初始化");
295
+ const e = this.getPageContext(), t = this.getPageContextKey(e);
296
+ return this.context && this.contextKey === t ? this.context : (this.context = await this.client.createContext(e), this.contextKey = t, this.context);
297
+ }
298
+ getPageContext() {
299
+ var e, t, s;
300
+ const r = this.selectedSourceSnapshot(), n = this.selectedSourceSnapshotId != null ? this.selectedSourceSnapshotId : r ? this.sourceSnapshotValue(r) : null;
301
+ return {
302
+ ...(s = (t = (e = this.options) == null ? void 0 : e.getPageContext) == null ? void 0 : t.call(e)) != null ? s : {},
303
+ userRole: this.answerAudience,
304
+ sourceSnapshotId: n == null ? void 0 : n
305
+ };
306
+ }
307
+ answerAudienceStorageKey(e) {
308
+ return `pageops:answer-audience:${e}`;
309
+ }
310
+ loadAnswerAudience(e) {
311
+ try {
312
+ const t = localStorage.getItem(this.answerAudienceStorageKey(e));
313
+ return C.some((s) => s.value === t) ? t : "business";
314
+ } catch (t) {
315
+ return "business";
316
+ }
317
+ }
318
+ saveAnswerAudience() {
319
+ if (this.options)
320
+ try {
321
+ localStorage.setItem(this.answerAudienceStorageKey(this.options.appId), this.answerAudience);
322
+ } catch (e) {
323
+ }
324
+ }
325
+ changeAnswerAudience(e) {
326
+ var s;
327
+ if (this.asking) return;
328
+ const t = (s = C.find((r) => r.value === e)) == null ? void 0 : s.value;
329
+ !t || t === this.answerAudience || (this.answerAudience = t, this.saveAnswerAudience(), this.renderPanel());
330
+ }
331
+ getPageContextKey(e) {
332
+ var t, s, r, n;
333
+ return JSON.stringify([
334
+ (t = e.route) != null ? t : "",
335
+ (s = e.url) != null ? s : location.href,
336
+ (r = e.title) != null ? r : document.title,
337
+ (n = e.menuPath) != null ? n : [],
338
+ e.sourceSnapshotId == null ? "" : String(e.sourceSnapshotId)
339
+ ]);
340
+ }
341
+ selectSourceSnapshot(e) {
342
+ if (this.asking) return;
343
+ const s = e === "" ? null : e;
344
+ if ((this.selectedSourceSnapshotId == null ? "" : String(this.selectedSourceSnapshotId)) === (s == null ? "" : String(s))) return;
345
+ this.selectedSourceSnapshotId = s, this.context = null, this.contextKey = "", this.selectedPageKey = "", this.currentThread = null, this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.streaming = "", this.answerError = "", this.answerStopped = false, this.renderPanel();
346
+ }
347
+ sourceSnapshotValue(e) {
348
+ var t, s;
349
+ return String((s = (t = e.id) != null ? t : e.source_snapshot_id) != null ? s : "");
350
+ }
351
+ selectedSourceSnapshot() {
352
+ if (this.selectedSourceSnapshotId == null) return this.sourceSnapshots[0];
353
+ const e = String(this.selectedSourceSnapshotId);
354
+ return this.sourceSnapshots.find((t) => this.sourceSnapshotValue(t) === e);
355
+ }
356
+ async loadSources() {
357
+ if (this.client) {
358
+ try {
359
+ const e = await this.client.listSources(), t = e[0], s = t ? this.sourceSnapshotValue(t) : null, r = this.context && this.context.source_snapshot_id != null ? String(this.context.source_snapshot_id) : null, n = this.selectedSourceSnapshotId == null && s != null && r !== s && (this.context != null || this.currentThread != null);
360
+ this.sourceSnapshots = e, this.sourceLoadError = "", n && (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);
361
+ } catch (e) {
362
+ this.sourceLoadError = "源码包状态加载失败,连接恢复后将自动重试。";
363
+ }
364
+ this.scheduleSourceRefresh(), this.renderPanel();
365
+ }
366
+ }
367
+ async loadConversations() {
368
+ this.client && (this.conversations = await this.client.listConversations(), this.renderPanel());
369
+ }
370
+ async newConversation() {
371
+ var s;
372
+ if (!this.client) return;
373
+ const e = await this.ensureContext(), t = (s = e.menu_path) != null && s.length ? e.menu_path.join(" / ") : e.route || document.title || "新的问答";
374
+ 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 = false, this.renderPanel();
375
+ }
376
+ async selectThread(e) {
377
+ if (!this.client) return;
378
+ 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 = false, this.renderPanel();
379
+ const t = [...this.messages].reverse().map(M).find(Boolean);
380
+ t && await this.loadAgentRun(t);
381
+ }
382
+ async deleteConversation(e) {
383
+ var t;
384
+ if (!(!this.client || this.asking || this.deletingThreadId) && window.confirm(`确定删除会话“${e.title}”吗?此操作无法撤销。`)) {
385
+ this.deletingThreadId = e.id, this.conversationError = "", this.renderPanel();
386
+ try {
387
+ 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) {
388
+ this.currentThread = null, this.messages = [], this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.streaming = "", this.answerError = "", this.answerStopped = !1;
389
+ const s = this.conversations[0];
390
+ s && await this.selectThread(s);
391
+ }
392
+ } catch (s) {
393
+ this.conversationError = s instanceof Error ? s.message : "删除问答会话失败";
394
+ } finally {
395
+ this.deletingThreadId = "", this.renderPanel();
396
+ }
397
+ }
398
+ }
399
+ async uploadSource(e, t) {
400
+ var s;
401
+ if (this.client) {
402
+ this.sourceUploading = true, this.sourceUploadProgress = 0, this.sourceUploadStatus = "上传中 0%", this.sourceUploadError = "", this.renderPanel();
403
+ try {
404
+ await this.client.uploadSource(e, { ...t, uploader: (s = this.options) == null ? void 0 : s.uploader, onProgress: (r) => {
405
+ this.sourceUploadProgress = Math.max(0, Math.min(100, Math.round(r.percent))), this.sourceUploadStatus = `上传中 ${this.sourceUploadProgress}%`, this.renderPanel();
406
+ } }), this.sourceSnapshots = await this.client.listSources(), this.sourceUploadStatus = this.isProjectMemoryUpdating() ? "源码上传完成,项目记忆更新中..." : "上传完成", this.scheduleSourceRefresh();
407
+ } catch (r) {
408
+ this.sourceUploadError = r instanceof Error ? r.message : "源码包上传失败", this.sourceUploadStatus = "";
409
+ } finally {
410
+ this.sourceUploading = false, this.sourceUploadProgress = null, this.renderPanel();
411
+ }
412
+ }
413
+ }
414
+ async ask(e) {
415
+ if (!this.client || this.asking) return;
416
+ const t = this.questionUnavailableReason();
417
+ if (t) {
418
+ this.sourceUploadError = t, this.renderPanel();
419
+ return;
420
+ }
421
+ this.resetAnswerState();
422
+ const s = ++this.activeRunId, r = new AbortController();
423
+ this.abortController = r, this.stoppedRunId = -1, this.asking = true, this.waitingForFirstContent = true, this.renderPanel();
424
+ try {
425
+ const n = this.getPageContextKey(this.getPageContext());
426
+ if (this.currentThread && this.selectedPageKey && this.selectedPageKey !== n && (this.currentThread = null), this.currentThread || await this.newConversation(), !this.currentThread) throw new Error("无法创建问答会话,请稍后重试。");
427
+ this.messages.push({ id: `local-${Date.now()}`, role: "user", content: e, metadata_json: {} }), this.steps = [], this.selectedAgentRunId = "", this.runLoadError = "", this.renderPanel();
428
+ const c = await this.client.streamQuestion(this.currentThread.id, e, this.answerAudience, r.signal);
429
+ if (!c.ok) throw new Error(await z(c, "服务暂时无法回答,请稍后重试。"));
430
+ if (!c.body) throw new Error("服务未返回有效的流式响应,请稍后重试。");
431
+ if (await J(c.body, (p, m) => this.handleStreamEvent(p, m)), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
432
+ if (this.streamFailure) throw new Error(this.streamFailure);
433
+ if (!this.streamDone) throw new Error("服务响应意外中断,请稍后重试。");
434
+ if (await this.typewriter.drain(), s === this.stoppedRunId) throw new DOMException("输出已停止", "AbortError");
435
+ await this.selectThread(this.currentThread);
436
+ } catch (n) {
437
+ if (s !== this.activeRunId) return;
438
+ this.typewriter.clear(), this.waitingForFirstContent = false, s === this.stoppedRunId ? this.answerStopped = true : (this.answerError = n instanceof Error ? n.message : "服务异常,请稍后重试。", this.upsertStep({ id: "error", title: "执行失败", status: "failed", summary: this.answerError }));
439
+ } finally {
440
+ if (s !== this.activeRunId) return;
441
+ this.asking = false, this.waitingForFirstContent = false, this.abortController === r && (this.abortController = null), this.renderPanel(true);
442
+ }
443
+ }
444
+ cancelActiveAnswer(e) {
445
+ var t;
446
+ if (!(!this.asking && !this.abortController)) {
447
+ if (e) {
448
+ this.stoppedRunId = this.activeRunId, this.answerStopped = true;
449
+ const s = this.steps.map((r) => r.status === "running" ? { ...r, status: "cancelled" } : r);
450
+ this.steps = s.some((r) => r.status === "cancelled") ? s : [...s, { id: "stopped", title: "已停止", status: "cancelled" }];
451
+ } else
452
+ this.activeRunId += 1, this.asking = false;
453
+ this.typewriter.clear(), this.waitingForFirstContent = false, (t = this.abortController) == null || t.abort(), this.abortController = null, e && this.renderPanel();
454
+ }
455
+ }
456
+ handleStreamEvent(e, t) {
457
+ var s, r;
458
+ if (e === "step") {
459
+ this.upsertStep(t), this.renderExecutionSteps(true);
460
+ return;
461
+ }
462
+ if (e === "delta") {
463
+ const n = String((s = t.content) != null ? s : "");
464
+ if (!n) return;
465
+ this.waitingForFirstContent = false, this.typewriter.enqueue(n);
466
+ return;
467
+ }
468
+ e === "done" && (this.streamDone = t), e === "error" && (this.streamFailure = String((r = t.message) != null ? r : "服务异常,请稍后重试。"));
469
+ }
470
+ updateStreamingMessage() {
471
+ var s, r;
472
+ const e = (s = this.panel) == null ? void 0 : s.querySelector("[data-streaming-content]");
473
+ if (!e) {
474
+ this.renderPanel();
475
+ return;
476
+ }
477
+ e.innerHTML = R(this.streaming);
478
+ const t = (r = this.panel) == null ? void 0 : r.querySelector(".po-messages");
479
+ t && (t.scrollTop = t.scrollHeight);
480
+ }
481
+ resetAnswerState() {
482
+ this.typewriter.clear(), this.asking = false, this.waitingForFirstContent = false, this.answerError = "", this.answerStopped = false, this.streamFailure = "", this.streamDone = null, this.streaming = "";
483
+ }
484
+ upsertStep(e) {
485
+ const t = this.steps.findIndex((s) => s.id === e.id);
486
+ this.steps = t === -1 ? [...this.steps, e] : this.steps.map((s) => s.id === e.id ? { ...s, ...e } : s);
487
+ }
488
+ async loadAgentRun(e) {
489
+ if (!(!this.client || !e)) {
490
+ this.selectedAgentRunId = e, this.runLoading = true, this.runLoadError = "", this.renderPanel();
491
+ try {
492
+ const t = await this.client.getAgentRun(e);
493
+ if (this.selectedAgentRunId !== e) return;
494
+ this.steps = t.steps;
495
+ } catch (t) {
496
+ if (this.selectedAgentRunId !== e) return;
497
+ this.steps = [], this.runLoadError = t instanceof Error ? t.message : "执行过程加载失败";
498
+ } finally {
499
+ this.selectedAgentRunId === e && (this.runLoading = false, this.renderPanel());
500
+ }
501
+ }
502
+ }
503
+ async copyAgentRunId(e) {
504
+ var t;
505
+ if (e) {
506
+ try {
507
+ if ((t = navigator.clipboard) != null && t.writeText)
508
+ await navigator.clipboard.writeText(e);
509
+ else {
510
+ const s = document.createElement("textarea");
511
+ if (s.value = e, s.style.position = "fixed", s.style.opacity = "0", document.body.appendChild(s), s.select(), !document.execCommand("copy")) throw new Error("copy_not_supported");
512
+ s.remove();
513
+ }
514
+ this.copiedAgentRunId = e;
515
+ } catch (s) {
516
+ this.copiedAgentRunId = `error:${e}`;
517
+ }
518
+ this.clearCopyFeedback(false), this.copyFeedbackTimer = setTimeout(() => {
519
+ this.copiedAgentRunId = "", this.copyFeedbackTimer = null, this.updateCopyFeedback();
520
+ }, 1800), this.updateCopyFeedback();
521
+ }
522
+ }
523
+ updateCopyFeedback() {
524
+ var e;
525
+ (e = this.panel) == null || e.querySelectorAll("[data-copy-run]").forEach((t) => {
526
+ var r;
527
+ const s = (r = t.dataset.copyRun) != null ? r : "";
528
+ t.textContent = this.copiedAgentRunId === s ? "已复制" : this.copiedAgentRunId === `error:${s}` ? "复制失败" : "复制流水号";
529
+ });
530
+ }
531
+ clearCopyFeedback(e = true) {
532
+ this.copyFeedbackTimer && clearTimeout(this.copyFeedbackTimer), this.copyFeedbackTimer = null, e && (this.copiedAgentRunId = "");
533
+ }
534
+ latestAnalysisStatus() {
535
+ var e, t, s;
536
+ return String((s = (t = (e = this.selectedSourceSnapshot()) == null ? void 0 : e.metadata) == null ? void 0 : t.analysis_status) != null ? s : "");
537
+ }
538
+ isProjectMemoryUpdating() {
539
+ return ["pending", "running"].includes(this.latestAnalysisStatus());
540
+ }
541
+ questionUnavailableReason() {
542
+ return this.sourceLoadError && !this.sourceSnapshots.length ? "暂时无法读取项目共享代码包,请检查 PageOps 服务连接。" : this.sourceSnapshots.length ? this.isProjectMemoryUpdating() ? "项目记忆正在更新,完成前暂不能问答。" : this.latestAnalysisStatus() === "failed" ? "项目记忆更新失败,请重新上传或重新索引。" : "" : "请先上传代码包后再提问。";
543
+ }
544
+ scheduleSourceRefresh() {
545
+ this.stopSourceRefresh(), !(!this.sourceLoadError && !this.isProjectMemoryUpdating()) && (this.sourceRefreshTimer = setTimeout(() => void this.loadSources(), 1500));
546
+ }
547
+ stopSourceRefresh() {
548
+ this.sourceRefreshTimer && clearTimeout(this.sourceRefreshTimer), this.sourceRefreshTimer = null;
549
+ }
550
+ renderPanel(e = this.asking, t = false) {
551
+ var g;
552
+ if (!this.panel) return;
553
+ const s = (g = this.panel.querySelector(".po-messages")) == null ? void 0 : g.scrollTop, r = this.questionUnavailableReason(), n = r || (this.asking ? "回答生成中,请稍候" : "请输入页面分析问题,Enter 发送,Shift + Enter 换行"), c = !!(r || this.asking), p = r ? '<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>', m = C.map((o) => `
554
+ <button type="button" data-audience="${o.value}" aria-pressed="${o.value === this.answerAudience}" ${this.asking ? "disabled" : ""}>${o.label}</button>
555
+ `).join("");
556
+ if (this.panel.innerHTML = `
6
557
  <aside class="po-sidebar">
7
558
  <div class="po-brand"><div class="po-logo"></div><div><strong>PageOps 问答</strong><span>页面工程专家</span></div></div>
8
- <button class="po-new" data-action="new" ${this.asking?"disabled":""}>+ 新建问答</button>
559
+ <button class="po-new" data-action="new" ${this.asking ? "disabled" : ""}>+ 新建问答</button>
9
560
  <input class="po-search" placeholder="搜索问答" />
10
- ${this.conversationError?`<p class="po-conversation-error" role="alert">${l(this.conversationError)}</p>`:""}
11
- <div class="po-thread-list">${this.conversations.map(o=>{var w;return`
12
- <div class="po-thread-row ${o.id===((w=this.currentThread)==null?void 0:w.id)?"active":""}">
13
- <button class="po-thread" data-thread="${l(o.id)}" ${this.asking?"disabled":""}>
14
- <strong>${l(o.title)}</strong><span>${F(o.created_at)}</span>
561
+ ${this.conversationError ? `<p class="po-conversation-error" role="alert">${l(this.conversationError)}</p>` : ""}
562
+ <div class="po-thread-list">${this.conversations.map((o) => {
563
+ var y;
564
+ return `
565
+ <div class="po-thread-row ${o.id === ((y = this.currentThread) == null ? void 0 : y.id) ? "active" : ""}">
566
+ <button class="po-thread" data-thread="${l(o.id)}" ${this.asking ? "disabled" : ""}>
567
+ <strong>${l(o.title)}</strong><span>${O(o.created_at)}</span>
15
568
  </button>
16
- <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>
17
- </div>`}).join("")}</div>
569
+ <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>
570
+ </div>`;
571
+ }).join("")}</div>
18
572
  </aside>
19
573
  <main class="po-chat">
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="回答角色">${f}</div></div></header>
574
+ <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="回答角色">${m}</div></div></header>
21
575
  <section class="po-messages">
22
- ${this.messages.map(o=>this.renderMessage(o)).join("")}
576
+ ${this.messages.map((o) => this.renderMessage(o)).join("")}
23
577
  ${this.renderAnswerState()}
24
578
  </section>
25
- <form class="po-composer"><textarea ${c?"disabled":""} placeholder="${l(n)}"></textarea>${p}</form>
579
+ <form class="po-composer"><textarea ${c ? "disabled" : ""} placeholder="${l(n)}"></textarea>${p}</form>
26
580
  </main>
27
581
  <aside class="po-trace"><header><h2>执行过程</h2><button data-action="close">×</button></header><section>${this.renderSourceUploader()}<div class="po-steps">${this.renderSteps()}</div></section></aside>
28
- `,this.bindPanelEvents(),e){const o=this.panel.querySelector(".po-messages");o&&(o.scrollTop=o.scrollHeight)}else if(s!==void 0){const o=this.panel.querySelector(".po-messages");o&&(o.scrollTop=s)}if(t){const o=this.panel.querySelector(".po-trace > section");o&&(o.scrollTop=o.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>${k(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>`:"",r=this.answerStopped?'<div class="po-stream-stopped" role="status">已停止输出</div>':"";return`${e}${t}${r}${s}`}renderMessage(e){const t=L(e),s=t&&t===this.selectedAgentRunId,r=this.copiedAgentRunId===t,n=this.copiedAgentRunId===`error:${t}`,c=e.role==="assistant"&&t?`<footer class="po-answer-meta ${s?"selected":""}">
582
+ `, this.bindPanelEvents(), e) {
583
+ const o = this.panel.querySelector(".po-messages");
584
+ o && (o.scrollTop = o.scrollHeight);
585
+ } else if (s !== void 0) {
586
+ const o = this.panel.querySelector(".po-messages");
587
+ o && (o.scrollTop = s);
588
+ }
589
+ if (t) {
590
+ const o = this.panel.querySelector(".po-trace > section");
591
+ o && (o.scrollTop = o.scrollHeight);
592
+ }
593
+ }
594
+ renderAnswerState() {
595
+ 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>${R(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>` : "", r = this.answerStopped ? '<div class="po-stream-stopped" role="status">已停止输出</div>' : "";
596
+ return `${e}${t}${r}${s}`;
597
+ }
598
+ renderMessage(e) {
599
+ const t = M(e), s = t && t === this.selectedAgentRunId, r = this.copiedAgentRunId === t, n = this.copiedAgentRunId === `error:${t}`, c = e.role === "assistant" && t ? `<footer class="po-answer-meta ${s ? "selected" : ""}">
29
600
  <span class="po-run-id" title="${l(t)}">问答流水号 <code>${l(t)}</code></span>
30
- <button type="button" data-copy-run="${l(t)}">${r?"已复制":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"?k(e.content):l(e.content)}</div>
601
+ <button type="button" data-copy-run="${l(t)}">${r ? "已复制" : n ? "复制失败" : "复制流水号"}</button>
602
+ <button type="button" data-view-run="${l(t)}" aria-pressed="${s}">${s ? "正在查看" : "查看执行过程"}</button>
603
+ </footer>` : "";
604
+ return `<article class="po-message ${e.role} ${s ? "run-selected" : ""}" data-message="${l(e.id)}">
605
+ <b>${e.role === "user" ? "你" : "PageOps 分析"}</b>
606
+ <div>${e.role === "assistant" ? R(e.content) : l(e.content)}</div>
35
607
  ${c}
36
- </article>`}renderSourceUploader(){const e=this.sourceLoadError?"暂时无法读取项目共享代码包,连接恢复后将自动重试。":"当前项目暂无代码包,请先上传后再提问。",t=typeof this.sourceUploadProgress=="number"?Math.max(0,Math.min(100,Math.round(this.sourceUploadProgress))):0;return`
608
+ </article>`;
609
+ }
610
+ renderSourceUploader() {
611
+ const e = this.sourceLoadError ? "暂时无法读取项目共享代码包,连接恢复后将自动重试。" : "当前项目暂无代码包,请先上传后再提问。";
612
+ const t = typeof this.sourceUploadProgress == "number" ? Math.max(0, Math.min(100, Math.round(this.sourceUploadProgress))) : 0;
613
+ return `
37
614
  <div class="po-source-uploader">
38
615
  <strong>源码包</strong>
39
616
  <p>同一项目的所有回答角色共享代码包。上传 zip、tar、tar.gz 或 tgz 后,PageOps 将基于代码证据回答问题。</p>
@@ -44,20 +621,134 @@
44
621
  <input class="po-source-reference-value" type="text" maxlength="128" placeholder="请输入 Branch 名称" />
45
622
  <textarea class="po-source-remark" maxlength="500" placeholder="备注(选填)"></textarea>
46
623
  <label class="po-upload-button">
47
- <span>${this.sourceUploading?"上传中...":"选择代码包"}</span>
48
- <input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading?"disabled":""} />
624
+ <span>${this.sourceUploading ? "上传中..." : "选择代码包"}</span>
625
+ <input type="file" accept=".zip,.tar,.gz,.tgz" data-action="upload-source" ${this.sourceUploading ? "disabled" : ""} />
49
626
  </label>
50
- ${this.sourceUploadStatus?`<p class="po-upload-status">${l(this.sourceUploadStatus)}</p>`:""}
51
- ${this.sourceUploading?`<div class="po-upload-progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${t}"><span style="width:${t}%"></span></div>`:""}
52
- ${this.sourceSnapshots.length?`<label class="po-source-selector"><span>问答代码包</span><select data-action="select-source" ${this.asking?"disabled":""}><option value="" ${this.selectedSourceSnapshotId==null?"selected":""}>最新 ready 代码包(默认)</option>${this.sourceSnapshots.map(s=>this.renderSourceOption(s)).join("")}</select></label><div class="po-source-list">${this.sourceSnapshots.map(s=>this.renderSourceItem(s)).join("")}</div>`:`<p class="po-upload-empty">${e}</p>`}
53
- ${this.sourceLoadError?`<p class="po-upload-error">${l(this.sourceLoadError)}</p>`:""}
54
- ${this.sourceUploadError?`<p class="po-upload-error">${l(this.sourceUploadError)}</p>`:""}
627
+ ${this.sourceUploadStatus ? `<p class="po-upload-status">${l(this.sourceUploadStatus)}</p>` : ""}
628
+ ${this.sourceUploading ? `<div class="po-upload-progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${t}"><span style="width:${t}%"></span></div>` : ""}
629
+ ${this.sourceSnapshots.length ? `<label class="po-source-selector"><span>问答代码包</span><select data-action="select-source" ${this.asking ? "disabled" : ""}><option value="" ${this.selectedSourceSnapshotId == null ? "selected" : ""}>最新 ready 代码包(默认)</option>${this.sourceSnapshots.map((s) => this.renderSourceOption(s)).join("")}</select></label><div class="po-source-list">${this.sourceSnapshots.map((s) => this.renderSourceItem(s)).join("")}</div>` : `<p class="po-upload-empty">${e}</p>`}
630
+ ${this.sourceLoadError ? `<p class="po-upload-error">${l(this.sourceLoadError)}</p>` : ""}
631
+ ${this.sourceUploadError ? `<p class="po-upload-error">${l(this.sourceUploadError)}</p>` : ""}
55
632
  </div>
56
- `}renderSourceOption(e){var n,c,p;const t=this.sourceSnapshotValue(e),s=e.filename||`代码包 ${t}`,r=String((p=(c=(n=e.metadata)==null?void 0:n.analysis_status)!=null?c:e.status)!=null?p:"unknown");return`<option value="${l(t)}" ${this.selectedSourceSnapshotId!=null&&String(this.selectedSourceSnapshotId)===t?"selected":""}>${l(s)} · ${l(r)}</option>`}renderSourceItem(e){var $,E,A,T,R,C,P;const t=e.filename||"未命名代码包",s=e.created_at?F(e.created_at):"刚刚上传",r=Q(e.archive_bytes||e.total_bytes||0),n=String((E=($=e.metadata)==null?void 0:$.analysis_status)!=null?E:"unknown"),c=typeof((A=e.metadata)==null?void 0:A.tag)=="string"?e.metadata.tag:"",p=typeof((T=e.metadata)==null?void 0:T.branch)=="string"?e.metadata.branch:"",f=c?`Tag: ${c}`:p?`Branch: ${p}`:"未记录代码引用",g=typeof((R=e.metadata)==null?void 0:R.remark)=="string"&&e.metadata.remark?e.metadata.remark:"无备注",o=typeof((C=e.metadata)==null?void 0:C.uploader)=="string"?e.metadata.uploader:"未知用户",w=(P={pending:"项目记忆等待更新",running:"项目记忆更新中",ready:"项目记忆已就绪",failed:"项目记忆更新失败"}[n])!=null?P:"项目记忆状态未知";return`<article class="po-source-item ${this.selectedSourceSnapshotId!=null&&this.sourceSnapshotValue(e)===String(this.selectedSourceSnapshotId)||this.selectedSourceSnapshotId==null&&e===this.sourceSnapshots[0]?"selected":""}"><strong>${l(t)}</strong><span>${l(f)}</span><span>备注:${l(g)}</span><span>上传人:${l(o)} · ${l(s)} · ${l(r)}</span><span>${l(w)} · 当前问答${this.selectedSourceSnapshotId==null&&e===this.sourceSnapshots[0]?"默认":""}引用</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,p,f;const s=(c=t.metrics)!=null&&c.length?`<div class="po-step-metrics">${t.metrics.map(g=>`<span>${l(g)}</span>`).join("")}</div>`:"",r=(p=t.details)!=null&&p.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||r);return`<details class="po-step ${t.status}" ${t.status==="running"||t.status==="failed"?"open":""} ${n?"":"data-static"}>
633
+ `;
634
+ }
635
+ renderSourceOption(e) {
636
+ var n, c, p;
637
+ const t = this.sourceSnapshotValue(e), s = e.filename || `代码包 ${t}`, r = String((p = (c = (n = e.metadata) == null ? void 0 : n.analysis_status) != null ? c : e.status) != null ? p : "unknown");
638
+ return `<option value="${l(t)}" ${this.selectedSourceSnapshotId != null && String(this.selectedSourceSnapshotId) === t ? "selected" : ""}>${l(s)} · ${l(r)}</option>`;
639
+ }
640
+ renderSourceItem(e) {
641
+ var w, b, S, $, E, A, T;
642
+ const t = e.filename || "未命名代码包", s = e.created_at ? O(e.created_at) : "刚刚上传", r = G(e.archive_bytes || e.total_bytes || 0), n = String((b = (w = e.metadata) == null ? void 0 : w.analysis_status) != null ? b : "unknown"), c = typeof ((S = e.metadata) == null ? void 0 : S.tag) == "string" ? e.metadata.tag : "", p = typeof (($ = e.metadata) == null ? void 0 : $.branch) == "string" ? e.metadata.branch : "", m = c ? `Tag: ${c}` : p ? `Branch: ${p}` : "未记录代码引用", g = typeof ((E = e.metadata) == null ? void 0 : E.remark) == "string" && e.metadata.remark ? e.metadata.remark : "无备注", o = typeof ((A = e.metadata) == null ? void 0 : A.uploader) == "string" ? e.metadata.uploader : "未知用户", y = (T = { pending: "项目记忆等待更新", running: "项目记忆更新中", ready: "项目记忆已就绪", failed: "项目记忆更新失败" }[n]) != null ? T : "项目记忆状态未知";
643
+ return `<article class="po-source-item ${this.selectedSourceSnapshotId != null && this.sourceSnapshotValue(e) === String(this.selectedSourceSnapshotId) || this.selectedSourceSnapshotId == null && e === this.sourceSnapshots[0] ? "selected" : ""}"><strong>${l(t)}</strong><span>${l(m)}</span><span>备注:${l(g)}</span><span>上传人:${l(o)} · ${l(s)} · ${l(r)}</span><span>${l(y)} · 当前问答${this.selectedSourceSnapshotId == null && e === this.sourceSnapshots[0] ? "默认" : ""}引用</span></article>`;
644
+ }
645
+ renderSteps() {
646
+ 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) => {
647
+ var c, p, m;
648
+ const s = (c = t.metrics) != null && c.length ? `<div class="po-step-metrics">${t.metrics.map((g) => `<span>${l(g)}</span>`).join("")}</div>` : "", r = (p = t.details) != null && p.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 || r);
649
+ return `<details class="po-step ${t.status}" ${t.status === "running" || t.status === "failed" ? "open" : ""} ${n ? "" : "data-static"}>
57
650
  <summary>
58
651
  <span class="po-step-dot" aria-hidden="true"></span>
59
- <span class="po-step-copy"><strong>${l(t.title)}</strong><small>${l((f=t.summary)!=null?f:"")}</small>${s}</span>
60
- <span class="po-step-status">${V(t.status)}</span>
652
+ <span class="po-step-copy"><strong>${l(t.title)}</strong><small>${l((m = t.summary) != null ? m : "")}</small>${s}</span>
653
+ <span class="po-step-status">${Z(t.status)}</span>
61
654
  </summary>
62
655
  ${r}
63
- </details>`}).join("")}renderExecutionSteps(e=!1){var s,r;const t=(s=this.panel)==null?void 0:s.querySelector(".po-steps");if(t&&(t.innerHTML=this.renderSteps(),e)){const n=(r=this.panel)==null?void 0:r.querySelector(".po-trace > section");n&&(n.scrollTop=n.scrollHeight)}}bindPanelEvents(){var e,t,s,r,n,c,p,f,g,o,w,$,E,A,T,R,C,P,h,d;(t=(e=this.panel)==null?void 0:e.querySelector('[data-action="new"]'))==null||t.addEventListener("click",()=>void this.newConversation()),(r=(s=this.panel)==null?void 0:s.querySelector('[data-action="close"]'))==null||r.addEventListener("click",()=>this.close()),(c=(n=this.panel)==null?void 0:n.querySelector('[data-action="stop-answer"]'))==null||c.addEventListener("click",()=>this.cancelActiveAnswer(!0)),(p=this.panel)==null||p.querySelectorAll("[data-audience]").forEach(h=>{h.addEventListener("click",()=>{var d;return this.changeAnswerAudience((d=h.dataset.audience)!=null?d:"")})}),(g=(f=this.panel)==null?void 0:f.querySelector('[data-action="upload-source"]'))==null||g.addEventListener("change",h=>{var U,_,K,j,O,M,D,B,W;const d=(U=h.target.files)==null?void 0:U[0];if(!d)return;const u=(K=(_=this.panel)==null?void 0:_.querySelector('[name="source-reference"]:checked'))==null?void 0:K.value,v=(M=(O=(j=this.panel)==null?void 0:j.querySelector(".po-source-reference-value"))==null?void 0:O.value.trim())!=null?M:"",Z=(W=(B=(D=this.panel)==null?void 0:D.querySelector(".po-source-remark"))==null?void 0:B.value.trim())!=null?W:"";if(!v||u!=="tag"&&u!=="branch"){this.sourceUploadError="请选择 Tag 或 Branch,并填写对应名称。",this.renderPanel();return}this.uploadSource(d,{[u]:v,remark:Z})}),(o=this.panel)==null||o.querySelectorAll('[name="source-reference"]').forEach(h=>{h.addEventListener("change",()=>{var u;const d=(u=this.panel)==null?void 0:u.querySelector(".po-source-reference-value");d&&(d.placeholder=`请输入 ${h.value==="tag"?"Tag":"Branch"} 名称`)})}),(d=(h=this.panel)==null?void 0:h.querySelector('[data-action="select-source"]'))==null||d.addEventListener("change",u=>{this.selectSourceSnapshot(u.target.value)}),(w=this.panel)==null||w.querySelectorAll("[data-thread]").forEach(h=>{h.addEventListener("click",()=>{const d=this.conversations.find(u=>u.id===h.dataset.thread);d&&this.selectThread(d)})}),($=this.panel)==null||$.querySelectorAll("[data-delete-thread]").forEach(h=>{h.addEventListener("click",d=>{d.stopPropagation();const u=this.conversations.find(v=>v.id===h.dataset.deleteThread);u&&this.deleteConversation(u)})}),(E=this.panel)==null||E.querySelectorAll("[data-view-run]").forEach(h=>{h.addEventListener("click",d=>{var u;d.stopPropagation(),this.loadAgentRun((u=h.dataset.viewRun)!=null?u:"")})}),(A=this.panel)==null||A.querySelectorAll("[data-copy-run]").forEach(h=>{h.addEventListener("click",d=>{var u;d.stopPropagation(),this.copyAgentRunId((u=h.dataset.copyRun)!=null?u:"")})}),(R=(T=this.panel)==null?void 0:T.querySelector("form"))==null||R.addEventListener("submit",h=>{var v;h.preventDefault();const d=(v=this.panel)==null?void 0:v.querySelector("textarea"),u=d==null?void 0:d.value.trim();u&&(d.value="",this.ask(u))}),(P=(C=this.panel)==null?void 0:C.querySelector("textarea"))==null||P.addEventListener("keydown",h=>{var u,v;const d=h;d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),(v=(u=this.panel)==null?void 0:u.querySelector("form"))==null||v.requestSubmit())})}}function l(a){return String(a==null?"":a).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function L(a){var t;const e=(t=a.metadata_json)==null?void 0:t.agent_run_id;return typeof e=="string"?e:""}function F(a){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(a))}function Q(a){if(!a)return"0 B";const e=["B","KB","MB","GB"];let t=a,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 V(a){return{pending:"等待中",running:"执行中",completed:"已完成",failed:"失败",cancelled:"已停止"}[a]}const G=new J;y.PageOpsSDK=G,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"})}));
656
+ </details>`;
657
+ }).join("");
658
+ }
659
+ renderExecutionSteps(e = false) {
660
+ var s, r;
661
+ const t = (s = this.panel) == null ? void 0 : s.querySelector(".po-steps");
662
+ if (t && (t.innerHTML = this.renderSteps(), e)) {
663
+ const n = (r = this.panel) == null ? void 0 : r.querySelector(".po-trace > section");
664
+ n && (n.scrollTop = n.scrollHeight);
665
+ }
666
+ }
667
+ bindPanelEvents() {
668
+ var e, t, s, r, n, c, p, m, g, o, y, w, b, S, $, E, A, T, h, d;
669
+ (t = (e = this.panel) == null ? void 0 : e.querySelector('[data-action="new"]')) == null || t.addEventListener("click", () => void this.newConversation()), (r = (s = this.panel) == null ? void 0 : s.querySelector('[data-action="close"]')) == null || r.addEventListener("click", () => this.close()), (c = (n = this.panel) == null ? void 0 : n.querySelector('[data-action="stop-answer"]')) == null || c.addEventListener("click", () => this.cancelActiveAnswer(true)), (p = this.panel) == null || p.querySelectorAll("[data-audience]").forEach((h) => {
670
+ h.addEventListener("click", () => {
671
+ var d;
672
+ return this.changeAnswerAudience((d = h.dataset.audience) != null ? d : "");
673
+ });
674
+ }), (g = (m = this.panel) == null ? void 0 : m.querySelector('[data-action="upload-source"]')) == null || g.addEventListener("change", (h) => {
675
+ var k, P, I, x, q, L, F, U, _;
676
+ const d = (k = h.target.files) == null ? void 0 : k[0];
677
+ if (!d) return;
678
+ const u = (I = (P = this.panel) == null ? void 0 : P.querySelector('[name="source-reference"]:checked')) == null ? void 0 : I.value, f = (L = (q = (x = this.panel) == null ? void 0 : x.querySelector(".po-source-reference-value")) == null ? void 0 : q.value.trim()) != null ? L : "", B = (_ = (U = (F = this.panel) == null ? void 0 : F.querySelector(".po-source-remark")) == null ? void 0 : U.value.trim()) != null ? _ : "";
679
+ if (!f || u !== "tag" && u !== "branch") {
680
+ this.sourceUploadError = "请选择 Tag 或 Branch,并填写对应名称。", this.renderPanel();
681
+ return;
682
+ }
683
+ this.uploadSource(d, { [u]: f, remark: B });
684
+ }), (o = this.panel) == null || o.querySelectorAll('[name="source-reference"]').forEach((h) => {
685
+ h.addEventListener("change", () => {
686
+ var u;
687
+ const d = (u = this.panel) == null ? void 0 : u.querySelector(".po-source-reference-value");
688
+ d && (d.placeholder = `请输入 ${h.value === "tag" ? "Tag" : "Branch"} 名称`);
689
+ });
690
+ }), (d = (h = this.panel) == null ? void 0 : h.querySelector('[data-action="select-source"]')) == null || d.addEventListener("change", (u) => {
691
+ this.selectSourceSnapshot(u.target.value);
692
+ }), (y = this.panel) == null || y.querySelectorAll("[data-thread]").forEach((h) => {
693
+ h.addEventListener("click", () => {
694
+ const d = this.conversations.find((u) => u.id === h.dataset.thread);
695
+ d && this.selectThread(d);
696
+ });
697
+ }), (w = this.panel) == null || w.querySelectorAll("[data-delete-thread]").forEach((h) => {
698
+ h.addEventListener("click", (d) => {
699
+ d.stopPropagation();
700
+ const u = this.conversations.find((f) => f.id === h.dataset.deleteThread);
701
+ u && this.deleteConversation(u);
702
+ });
703
+ }), (b = this.panel) == null || b.querySelectorAll("[data-view-run]").forEach((h) => {
704
+ h.addEventListener("click", (d) => {
705
+ var u;
706
+ d.stopPropagation(), this.loadAgentRun((u = h.dataset.viewRun) != null ? u : "");
707
+ });
708
+ }), (S = this.panel) == null || S.querySelectorAll("[data-copy-run]").forEach((h) => {
709
+ h.addEventListener("click", (d) => {
710
+ var u;
711
+ d.stopPropagation(), this.copyAgentRunId((u = h.dataset.copyRun) != null ? u : "");
712
+ });
713
+ }), (E = ($ = this.panel) == null ? void 0 : $.querySelector("form")) == null || E.addEventListener("submit", (h) => {
714
+ var f;
715
+ h.preventDefault();
716
+ const d = (f = this.panel) == null ? void 0 : f.querySelector("textarea"), u = d == null ? void 0 : d.value.trim();
717
+ u && (d.value = "", this.ask(u));
718
+ }), (T = (A = this.panel) == null ? void 0 : A.querySelector("textarea")) == null || T.addEventListener("keydown", (h) => {
719
+ var u, f;
720
+ const d = h;
721
+ d.key === "Enter" && !d.shiftKey && (d.preventDefault(), (f = (u = this.panel) == null ? void 0 : u.querySelector("form")) == null || f.requestSubmit());
722
+ });
723
+ }
724
+ }
725
+ function l(a) {
726
+ return String(a == null ? "" : a).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
727
+ }
728
+ function M(a) {
729
+ var t;
730
+ const e = (t = a.metadata_json) == null ? void 0 : t.agent_run_id;
731
+ return typeof e == "number" ? String(e) : typeof e == "string" ? e : "";
732
+ }
733
+ function O(a) {
734
+ return new Intl.DateTimeFormat("zh-CN", {
735
+ timeZone: "Asia/Shanghai",
736
+ month: "2-digit",
737
+ day: "2-digit",
738
+ hour: "2-digit",
739
+ minute: "2-digit",
740
+ hourCycle: "h23"
741
+ }).format(new Date(a));
742
+ }
743
+ function G(a) {
744
+ if (!a) return "0 B";
745
+ const e = ["B", "KB", "MB", "GB"];
746
+ let t = a, s = 0;
747
+ for (; t >= 1024 && s < e.length - 1; )
748
+ t /= 1024, s += 1;
749
+ return `${t >= 10 || s === 0 ? t.toFixed(0) : t.toFixed(1)} ${e[s]}`;
750
+ }
751
+ function Z(a) {
752
+ return { pending: "等待中", running: "执行中", completed: "已完成", failed: "失败", cancelled: "已停止" }[a];
753
+ }
754
+ const Y = new V();exports.PageOpsSDK=Y;}));
package/dist/types.d.ts CHANGED
@@ -27,7 +27,7 @@ export interface ContextSession {
27
27
  tenant_id?: string;
28
28
  user_role?: string;
29
29
  build_version?: string;
30
- source_snapshot_id?: number | null;
30
+ source_snapshot_id?: number | string | null;
31
31
  }
32
32
  export interface ConversationThread {
33
33
  id: string;
@@ -65,8 +65,8 @@ export interface AgentRunHistory {
65
65
  steps: ExecutionStep[];
66
66
  }
67
67
  export interface SourceSnapshot {
68
- id?: string;
69
- source_snapshot_id?: string | null;
68
+ id?: number | string;
69
+ source_snapshot_id?: number | string | null;
70
70
  project_id?: string;
71
71
  filename?: string | null;
72
72
  archive_bytes?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pageops/sdk",
3
- "version": "0.1.28",
3
+ "version": "0.1.30",
4
4
  "description": "PageOps embeddable frontend SDK",
5
5
  "type": "module",
6
6
  "main": "dist/pageops-sdk.umd.cjs",