vanspod 0.1.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/page.js CHANGED
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.modelStatus = modelStatus;
4
4
  exports.classroomBlocks = classroomBlocks;
5
5
  exports.renderPage = renderPage;
6
+ exports.renderInspectorPage = renderInspectorPage;
6
7
  const version_1 = require("./version");
7
8
  const appearance_1 = require("./appearance");
8
9
  const installProgress_1 = require("./installProgress");
@@ -12,6 +13,9 @@ const classroomUpdate_1 = require("./classroomUpdate");
12
13
  const connectionMascot_1 = require("./connectionMascot");
13
14
  const clientIcons_1 = require("./clientIcons");
14
15
  const environmentIcons_1 = require("./environmentIcons");
16
+ const promptCapture_1 = require("./promptCapture");
17
+ const inspectorView_1 = require("./inspectorView");
18
+ const versionUpdateView_1 = require("./versionUpdateView");
15
19
  const courseCatalog_1 = require("./courseCatalog");
16
20
  const PRODUCT = "VansPod";
17
21
  const VERSION = `v${version_1.VERSION}`;
@@ -556,7 +560,72 @@ function classroomBlocks(view) {
556
560
  stop: stopForm(),
557
561
  };
558
562
  }
559
- function basePage(view) {
563
+ const SIDE_PAGES = [
564
+ {
565
+ id: "settings",
566
+ href: "/",
567
+ label: "教室設定",
568
+ icon: `<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m9.5 3-.6 2.3-2 .9-2.1-.6-2.5 4.3 1.5 1.7v2.3l-1.5 1.7 2.5 4.3 2.1-.6 2 .9.6 2.3h5l.6-2.3 2-.9 2.1.6 2.5-4.3-1.5-1.7v-2.3l1.5-1.7-2.5-4.3-2.1.6-2-.9L14.5 3z"/><circle cx="12" cy="12" r="3"/></svg>`,
569
+ },
570
+ {
571
+ id: "inspector",
572
+ href: "/prompt-inspector",
573
+ label: "Prompt 觀察室",
574
+ icon: `<svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="6.5"/><path d="m20 20-4.4-4.4M8 9.5h6M8 12.5h4"/></svg>`,
575
+ },
576
+ ];
577
+ const BRAND = `<div class="brand"><div class="logo-badge"><img src="/brand-logo.png" alt=""></div><h1 class="brand-title">${PRODUCT}</h1><span class="ver">${VERSION}</span></div>`;
578
+ /** 兩頁共用的側欄:行動版頂列、抽屜遮罩、選單與外觀切換。 */
579
+ function sideMenu(current) {
580
+ const items = SIDE_PAGES.map((page) => `<a class="side-item" href="${page.href}"${page.id === current ? ' aria-current="page"' : ""}>${page.icon}<span>${page.label}</span></a>`).join("");
581
+ return `<div class="mobile-top"><button type="button" class="menu-toggle" aria-label="開啟選單" aria-expanded="false" aria-controls="side-menu"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg></button>${BRAND}</div><button type="button" class="drawer-scrim" aria-label="關閉選單"></button><header class="bar" id="side-menu">${BRAND}<nav aria-label="選單">${items}</nav><div class="side-foot"><button type="button" data-appearance-toggle aria-label="切換外觀"></button>${versionUpdateView_1.UPDATE_BUTTON}</div></header>`;
582
+ }
583
+ /** 兩頁共用的頁殼版面:側欄、行動版抽屜。 */
584
+ const SHELL_LAYOUT_STYLES = `
585
+ .tile { border: 1px solid light-dark(#e6e6e6, #3d3d3d); }
586
+ body { display: grid; grid-template-columns: 232px minmax(0, 1fr); min-height: 100dvh; }
587
+ .bar { position: sticky; top: 0; align-self: start; height: 100dvh; display: flex; flex-direction: column; align-items: stretch; justify-content: flex-start; gap: 4px; padding: 18px 14px; border-bottom: 0; border-right: 1px solid var(--line); }
588
+ .bar .brand { padding: 6px 8px 14px; }
589
+ .bar .logo-badge { width: 28px; height: 28px; }
590
+ .bar .brand-title, .mobile-top .brand-title { margin: 0; font-size: 16px; font-weight: 600; letter-spacing: 0; line-height: 26px; color: light-dark(#0d0d0d, #ececec); background: none; -webkit-text-fill-color: currentColor; white-space: nowrap; }
591
+ .brand .ver { align-self: center; flex: 0 0 auto; font-family: Consolas, "Cascadia Mono", monospace; font-size: 10px; line-height: 1.2; color: var(--muted); background: light-dark(#f4f4f4, #303030); border: 1px solid light-dark(#e6e6e6, #3d3d3d); padding: 2px 6px; border-radius: 999px; white-space: nowrap; }
592
+ .bar nav { display: flex; flex-direction: column; gap: 2px; }
593
+ .side-item { display: flex; align-items: center; gap: 8px; align-self: stretch; justify-content: flex-start; min-height: 36px; padding: 8px 10px; border-radius: 8px; background: transparent; color: var(--text); font-size: 13px; font-weight: 500; text-align: left; text-decoration: none; }
594
+ .side-item:hover { background: light-dark(rgba(13, 13, 13, 0.04), rgba(255, 255, 255, 0.05)); }
595
+ .side-item[aria-current="page"] { background: light-dark(rgba(13, 13, 13, 0.06), rgba(255, 255, 255, 0.09)); font-weight: 600; }
596
+ .side-item:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
597
+ .side-item svg { width: 18px; height: 18px; flex-shrink: 0; }
598
+ ${versionUpdateView_1.VERSION_UPDATE_STYLES}
599
+ .mobile-top, .drawer-scrim, .menu-toggle { display: none; }
600
+ main { justify-self: center; width: min(52rem, 100%); }
601
+ @media (max-width: 760px) {
602
+ body { display: block; }
603
+ .mobile-top { display: flex; position: sticky; top: 0; z-index: 20; align-items: center; gap: 4px; padding: 4px 10px; border-bottom: 1px solid var(--line); background: var(--bar); backdrop-filter: blur(24px) saturate(160%); }
604
+ .mobile-top .brand { flex: 1; min-width: 0; padding: 4px; }
605
+ .mobile-top .logo-badge { width: 32px; height: 32px; }
606
+ .mobile-top .brand-title { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
607
+ .menu-toggle { display: grid; place-items: center; width: 44px; height: 44px; min-height: 44px; padding: 0; border: 0; border-radius: 8px; background: transparent; color: var(--text); }
608
+ .menu-toggle svg { width: 20px; height: 20px; }
609
+ .bar { position: fixed; top: 0; left: 0; bottom: 0; z-index: 40; width: min(280px, 84vw); height: 100dvh; transform: translateX(-100%); visibility: hidden; border-right: 1px solid var(--line); background: light-dark(rgba(242, 242, 247, 0.97), rgba(12, 12, 14, 0.96)); }
610
+ .bar.open { transform: translateX(0); visibility: visible; }
611
+ .bar .brand { display: none; }
612
+ .drawer-scrim.show { display: block; position: fixed; inset: 0; z-index: 30; border: 0; padding: 0; background: light-dark(rgba(20, 20, 20, 0.32), rgba(0, 0, 0, 0.52)); }
613
+ main { width: min(52rem, 100%); margin: 0 auto; }
614
+ }
615
+ .tile-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
616
+ .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
617
+ [data-appearance="dark"] { --bg: #212121; }
618
+ @media (prefers-color-scheme: dark) {
619
+ :root:not([data-appearance="light"]) { --bg: #212121; }
620
+ }`;
621
+ /** 兩頁共用的頁首與按鈕樣式。 */
622
+ const SHELL_CONTROL_STYLES = `
623
+ .page-head { margin: 0.75rem 0 0.15rem; }
624
+ .page-head h2 { font-size: 20px; font-weight: 600; color: var(--text); letter-spacing: 0; }
625
+ .page-head p { margin-top: 4px; color: var(--muted); font-size: 14px; font-weight: 400; }
626
+ main button { min-height: 34px; padding: 8px 16px; border-radius: 999px; border: 1px solid transparent; background: var(--accent); color: var(--on-accent); font-size: 13px; font-weight: 500; }
627
+ main button.quiet { background: light-dark(#ffffff, #212121); color: light-dark(#0d0d0d, #ececec); border-color: light-dark(#e6e6e6, #3d3d3d); padding: 8px 16px; }`;
628
+ function documentHead() {
560
629
  return `<!DOCTYPE html>
561
630
  <html lang="zh-Hant">
562
631
  <head>
@@ -566,7 +635,10 @@ function basePage(view) {
566
635
  <link rel="icon" href="/favicon.ico" sizes="any">
567
636
  <style>${CSS}</style>
568
637
  <script>${appearanceScript()}</script>
569
- </head>
638
+ </head>`;
639
+ }
640
+ function basePage(view) {
641
+ return `${documentHead()}
570
642
  <body>
571
643
  <header class="bar">
572
644
  <div class="brand">
@@ -794,8 +866,7 @@ function renderPage(view) {
794
866
  ? `<span class="badge">已連線</span>`
795
867
  : `<span class="badge off">未連線</span>`;
796
868
  let html = basePage(view).replace(`<section class="tile"><h2>連線</h2>`, `<section class="tile"><div class="tile-head"><h2>連線</h2>${tag}</div>`);
797
- html = html.replace(`<header class="bar">`, `<div class="mobile-top"><button type="button" class="menu-toggle" aria-label="開啟選單" aria-expanded="false" aria-controls="side-menu"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg></button><div class="brand"><div class="logo-badge"><img src="/brand-logo.png" alt=""></div><h1 class="gradient-text">VansPod</h1></div></div><button type="button" class="drawer-scrim" aria-label="關閉選單"></button><header class="bar" id="side-menu">`);
798
- html = html.replace(`<button type="button" data-appearance-toggle aria-label="切換外觀"></button>`, `<nav aria-label="選單"><button type="button" class="side-item" aria-current="page"><svg viewBox="0 0 24 24" aria-hidden="true" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="m9.5 3-.6 2.3-2 .9-2.1-.6-2.5 4.3 1.5 1.7v2.3l-1.5 1.7 2.5 4.3 2.1-.6 2 .9.6 2.3h5l.6-2.3 2-.9 2.1.6 2.5-4.3-1.5-1.7v-2.3l1.5-1.7-2.5-4.3-2.1.6-2-.9L14.5 3z"/><circle cx="12" cy="12" r="3"/></svg><span>教室設定</span></button></nav><button type="button" data-appearance-toggle aria-label="切換外觀"></button>`);
869
+ html = html.replace(/<header class="bar">[\s\S]*?<\/header>/, sideMenu("settings"));
799
870
  html = html.replace(/<section class="tile"><h2>資料夾<\/h2>[\s\S]*?<\/section>/, "");
800
871
  const modelCount = view.allowedModels?.length ?? (view.modelId ? 1 : 0);
801
872
  const modelTag = modelCount
@@ -832,7 +903,6 @@ function renderPage(view) {
832
903
  html = html.replace(/<p class="class-label">[\s\S]*?<\/p>/, "");
833
904
  html = html.replace(`<p class="detail">Classroom API Key 已設定。</p>`, "");
834
905
  }
835
- html = html.replaceAll(`<h1 class="gradient-text">${PRODUCT}</h1>`, `<h1 class="brand-title">VansPod</h1><span class="ver">${VERSION}</span>`);
836
906
  html = html.replace(`<div class="modules">`, `<header class="page-head"><h2>教室設定</h2><p>連線、模型與開發環境。</p></header><div class="modules">`);
837
907
  if (view.catalog?.actions.length) {
838
908
  html = html.replace(/<table>[\s\S]*?<\/table>/, installActionCards(view));
@@ -840,35 +910,8 @@ function renderPage(view) {
840
910
  html = organizeSettings(html, view);
841
911
  html = splitCourseCards(html, view);
842
912
  const extra = `<style>
843
- .tile { border: 1px solid light-dark(#e6e6e6, #3d3d3d); }
844
913
  .display { display: none; }
845
- body { display: grid; grid-template-columns: 232px minmax(0, 1fr); min-height: 100dvh; }
846
- .bar { position: sticky; top: 0; align-self: start; height: 100dvh; display: flex; flex-direction: column; align-items: stretch; justify-content: flex-start; gap: 4px; padding: 18px 14px; border-bottom: 0; border-right: 1px solid var(--line); }
847
- .bar .brand { padding: 6px 8px 14px; }
848
- .bar .logo-badge { width: 28px; height: 28px; }
849
- .bar .brand-title, .mobile-top .brand-title { margin: 0; font-size: 16px; font-weight: 600; letter-spacing: 0; line-height: 26px; color: light-dark(#0d0d0d, #ececec); background: none; -webkit-text-fill-color: currentColor; white-space: nowrap; }
850
- .brand .ver { align-self: center; flex: 0 0 auto; font-family: Consolas, "Cascadia Mono", monospace; font-size: 10px; line-height: 1.2; color: var(--muted); background: light-dark(#f4f4f4, #303030); border: 1px solid light-dark(#e6e6e6, #3d3d3d); padding: 2px 6px; border-radius: 999px; white-space: nowrap; }
851
- .bar nav { display: flex; flex-direction: column; }
852
- .side-item { display: flex; align-items: center; gap: 8px; align-self: stretch; justify-content: flex-start; min-height: 36px; padding: 8px 10px; border-radius: 8px; background: light-dark(rgba(13, 13, 13, 0.06), rgba(255, 255, 255, 0.09)); color: var(--text); font-size: 13px; font-weight: 600; text-align: left; }
853
- .side-item svg { width: 18px; height: 18px; flex-shrink: 0; }
854
- .bar [data-appearance-toggle] { margin-top: auto; align-self: flex-start; }
855
- .mobile-top, .drawer-scrim, .menu-toggle { display: none; }
856
- main { justify-self: center; width: min(52rem, 100%); }
857
- @media (max-width: 760px) {
858
- body { display: block; }
859
- .mobile-top { display: flex; position: sticky; top: 0; z-index: 20; align-items: center; gap: 4px; padding: 4px 10px; border-bottom: 1px solid var(--line); background: var(--bar); backdrop-filter: blur(24px) saturate(160%); }
860
- .mobile-top .brand { flex: 1; min-width: 0; padding: 4px; }
861
- .mobile-top .logo-badge { width: 32px; height: 32px; }
862
- .mobile-top .brand-title { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
863
- .menu-toggle { display: grid; place-items: center; width: 44px; height: 44px; min-height: 44px; padding: 0; border: 0; border-radius: 8px; background: transparent; color: var(--text); }
864
- .menu-toggle svg { width: 20px; height: 20px; }
865
- .bar { position: fixed; top: 0; left: 0; bottom: 0; z-index: 40; width: min(280px, 84vw); height: 100dvh; transform: translateX(-100%); visibility: hidden; border-right: 1px solid var(--line); background: light-dark(rgba(242, 242, 247, 0.97), rgba(12, 12, 14, 0.96)); }
866
- .bar.open { transform: translateX(0); visibility: visible; }
867
- .bar .brand { display: none; }
868
- .drawer-scrim.show { display: block; position: fixed; inset: 0; z-index: 30; border: 0; padding: 0; background: light-dark(rgba(20, 20, 20, 0.32), rgba(0, 0, 0, 0.52)); }
869
- main { width: min(52rem, 100%); margin: 0 auto; }
870
- }
871
- .tile-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
914
+ ${SHELL_LAYOUT_STYLES}
872
915
  .course-section > summary { cursor: pointer; list-style: none; border-radius: 6px; }
873
916
  .course-section > summary::-webkit-details-marker { display: none; }
874
917
  .course-section > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; }
@@ -916,7 +959,6 @@ function renderPage(view) {
916
959
  main .snippet-card > button { flex-shrink: 0; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
917
960
  .snippet-card > button svg { width: 14px; height: 14px; }
918
961
  .snippet-card.copied > button svg { display: none; }
919
- .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
920
962
  .confirm-dialog { position: fixed; inset: 0; z-index: 90; display: grid; place-items: center; padding: 24px; background: light-dark(rgba(20, 20, 20, 0.32), rgba(0, 0, 0, 0.52)); }
921
963
  .confirm-panel { width: min(36rem, 100%); max-height: min(70dvh, 32rem); overflow: hidden; display: flex; flex-direction: column; gap: 12px; padding: 16px; border-radius: 16px; background: var(--tile); border: 1px solid var(--line); }
922
964
  .confirm-panel > :not(pre) { flex-shrink: 0; }
@@ -929,10 +971,6 @@ function renderPage(view) {
929
971
  .confirm-panel button { min-height: 34px; padding: 8px 16px; border-radius: 999px; border: 1px solid transparent; background: var(--accent); color: var(--on-accent); font-size: 13px; font-weight: 500; }
930
972
  .confirm-panel button.quiet { background: light-dark(#ffffff, #212121); color: light-dark(#0d0d0d, #ececec); border-color: light-dark(#e6e6e6, #3d3d3d); }
931
973
  .restart { color: light-dark(#9a4a08, #fbbf24); }
932
- [data-appearance="dark"] { --bg: #212121; }
933
- @media (prefers-color-scheme: dark) {
934
- :root:not([data-appearance="light"]) { --bg: #212121; }
935
- }
936
974
  .settings-grid { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
937
975
  .settings-card { gap: 16px; padding: 18px; }
938
976
  .settings-card .tile-head { padding-bottom: 12px; border-bottom: 1px solid var(--line); }
@@ -994,11 +1032,7 @@ function renderPage(view) {
994
1032
  .key-row p { color: var(--muted); font-size: 13px; }
995
1033
  .key-row form { flex-shrink: 0; }
996
1034
  ${connectionMascot_1.connectionMascotStyles}
997
- .page-head { margin: 0.75rem 0 0.15rem; }
998
- .page-head h2 { font-size: 20px; font-weight: 600; color: var(--text); letter-spacing: 0; }
999
- .page-head p { margin-top: 4px; color: var(--muted); font-size: 14px; font-weight: 400; }
1000
- main button { min-height: 34px; padding: 8px 16px; border-radius: 999px; border: 1px solid transparent; background: var(--accent); color: var(--on-accent); font-size: 13px; font-weight: 500; }
1001
- main button.quiet { background: light-dark(#ffffff, #212121); color: light-dark(#0d0d0d, #ececec); border-color: light-dark(#e6e6e6, #3d3d3d); padding: 8px 16px; }
1035
+ ${SHELL_CONTROL_STYLES}
1002
1036
  main button.stop { background: transparent; color: light-dark(#b91c1c, #f87171); border-color: light-dark(rgba(185, 28, 28, 0.35), rgba(248, 113, 113, 0.35)); }
1003
1037
  main .modes { border-radius: 999px; padding: 2px; background: light-dark(#f4f4f4, #303030); border: 1px solid light-dark(#e6e6e6, #3d3d3d); }
1004
1038
  main .modes button { background: transparent; color: var(--text); border-color: transparent; }
@@ -1014,3 +1048,75 @@ function renderPage(view) {
1014
1048
  </script>`;
1015
1049
  return html.replace("</body>", `${extra}</body>`);
1016
1050
  }
1051
+ function recorderBar(recording) {
1052
+ const state = recording
1053
+ ? `<span class="pi-rec-dot" aria-hidden="true"></span><div><strong>錄製中</strong>`
1054
+ : `<div><strong>未錄製</strong>`;
1055
+ const toggle = recording
1056
+ ? `<form method="post" action="/prompt-capture/pause"><button type="submit" class="quiet">暫停</button></form>`
1057
+ : `<form method="post" action="/prompt-capture/start"><button type="submit">開始錄製</button></form>`;
1058
+ return `<section class="tile pi-recorder"><div class="pi-rec-state">${state}<p class="hint">只記在這台電腦的記憶體,最多 ${promptCapture_1.CAPTURE_LIMIT} 筆,關掉 VansPod 就清除。只有切到「課堂」的客戶端會被記錄。</p></div></div><div class="pi-rec-actions">${toggle}<form method="post" action="/prompt-capture/clear"><button type="submit" class="quiet">清除</button></form></div></section>`;
1059
+ }
1060
+ // 法鬥超人在頁首標題右邊巡邏,一圈的時間依寬度重算。
1061
+ const headPatrol = (0, connectionMascot_1.fittedPatrol)(".pi-head");
1062
+ // 錄製列的按鈕改用 fetch 換掉錄製列,整頁不重載,法鬥才不會每按一次就重新進場。
1063
+ const recorderActionsScript = `
1064
+ document.addEventListener("submit", async function (event) {
1065
+ var form = event.target;
1066
+ if (!form?.matches?.('form[action^="/prompt-capture/"]')) return;
1067
+ event.preventDefault();
1068
+ var bar = form.closest(".pi-recorder");
1069
+ bar.querySelectorAll("button").forEach(function (button) { button.disabled = true; });
1070
+ try {
1071
+ var response = await fetch(form.action, { method: "POST" });
1072
+ if (!response.ok) throw new Error("recorder action failed");
1073
+ var next = new DOMParser().parseFromString(await response.text(), "text/html").querySelector(".pi-recorder");
1074
+ if (!next) throw new Error("recorder bar unavailable");
1075
+ bar.replaceWith(next);
1076
+ document.dispatchEvent(new Event("pi-refresh"));
1077
+ } catch (error) {
1078
+ bar.querySelectorAll("button").forEach(function (button) { button.disabled = false; });
1079
+ }
1080
+ });
1081
+ `;
1082
+ /** Prompt 觀察室:與教室設定共用頁殼、側欄、主題與行動版抽屜。 */
1083
+ function renderInspectorPage(view) {
1084
+ const list = { captures: view.captures, dropped: view.dropped };
1085
+ // 頁面腳本拿同一份資料接手重繪;JSON 裡的 < 不能結束 script 元素。
1086
+ const data = JSON.stringify(list).replace(/</g, "\\u003c");
1087
+ return `${documentHead()}
1088
+ <body>
1089
+ ${sideMenu("inspector")}
1090
+ <main class="inspector-main">
1091
+ <header class="page-head pi-head"><div class="pi-head-text"><h2>Prompt 觀察室</h2><p>看看 Coding Agent 每次送給模型的完整內容。</p></div>${connectionMascot_1.connectionMascot}</header>
1092
+ ${recorderBar(view.recording)}
1093
+ <div id="pi-app">${(0, inspectorView_1.inspectorBody)(list, { selected: null, view: "parts", raw: "sent" })}</div>
1094
+ </main>
1095
+ <script type="application/json" id="pi-data">${data}</script>
1096
+ <style>
1097
+ ${SHELL_LAYOUT_STYLES}
1098
+ ${SHELL_CONTROL_STYLES}
1099
+ main.inspector-main { width: min(72rem, 100%); }
1100
+ #pi-app { margin-top: 12px; }
1101
+ .inspector-main .tile { gap: 12px; padding: 18px; min-width: 0; }
1102
+ .inspector-main .hint { color: var(--muted); font-size: 13px; line-height: 1.6; }
1103
+ .pi-recorder { flex-direction: row; align-items: center; justify-content: space-between; flex-wrap: wrap; }
1104
+ .pi-rec-state { display: flex; align-items: flex-start; gap: 10px; min-width: 0; flex: 1 1 22rem; }
1105
+ .pi-rec-state strong { font-size: 14px; }
1106
+ .pi-rec-dot { width: 10px; height: 10px; margin-top: 5px; border-radius: 50%; background: #e5484d; box-shadow: 0 0 0 4px rgba(229, 72, 77, 0.15); flex-shrink: 0; animation: pi-pulse 1.6s ease-in-out infinite; }
1107
+ @keyframes pi-pulse { 50% { opacity: 0.35; } }
1108
+ @media (prefers-reduced-motion: reduce) { .pi-rec-dot { animation: none; } }
1109
+ .pi-rec-actions { display: flex; gap: 8px; }
1110
+ .pi-head { display: flex; align-items: flex-end; flex-wrap: wrap; gap: 0 16px; }
1111
+ .pi-head-text { flex: 0 1 auto; padding-bottom: 12px; }
1112
+ /* 巡邏範圍撐滿標題右邊;一圈的時間依寬度重算,步速與教室設定一致。 */
1113
+ .pi-head .connection-mascot { flex: 1 1 260px; height: 144px; }
1114
+ ${connectionMascot_1.connectionMascotStyles}
1115
+ ${headPatrol.styles}
1116
+ ${inspectorView_1.INSPECTOR_STYLES}
1117
+ </style>
1118
+ ${headPatrol.sheet}
1119
+ <script>${drawerScript()}${connectionMascot_1.connectionMascotScript}${headPatrol.script}${recorderActionsScript}${(0, inspectorView_1.inspectorScript)()}</script>
1120
+ </body>
1121
+ </html>`;
1122
+ }
@@ -0,0 +1,246 @@
1
+ "use strict";
2
+ // Prompt Capture 記錄器:只存在記憶體,每次啟動錄製都是關閉(ADR-0009)。
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.CAPTURE_LIMIT = void 0;
5
+ exports.createPromptCapture = createPromptCapture;
6
+ // 協定由送往 Router 的路徑判斷,不由客戶端判斷。新協定只要在這裡加一行。
7
+ const PROTOCOLS = [
8
+ { path: "/v1/messages", protocol: "messages", parse: parseMessages },
9
+ { path: "/v1/responses", protocol: "responses", parse: parseResponses },
10
+ { path: "/v1/chat/completions", protocol: "chat", parse: parseChat },
11
+ ];
12
+ function protocolFor(path) {
13
+ const route = path.split("?")[0].replace(/\/+$/, "");
14
+ return PROTOCOLS.find(entry => route.endsWith(entry.path));
15
+ }
16
+ const noop = () => { };
17
+ /** Captures kept in memory; older ones are dropped and only counted. */
18
+ exports.CAPTURE_LIMIT = 20;
19
+ function createPromptCapture() {
20
+ let recording = false;
21
+ let entries = [];
22
+ let dropped = 0;
23
+ let nextId = 1;
24
+ return {
25
+ get recording() { return recording; },
26
+ start() { recording = true; },
27
+ pause() { recording = false; },
28
+ clear() { entries = []; dropped = 0; },
29
+ record(request) {
30
+ const match = protocolFor(request.path);
31
+ if (!recording || !match)
32
+ return noop;
33
+ // withoutBase64 also copies both bodies, so later changes by the caller never reach the capture.
34
+ const sent = withoutBase64(request.sent);
35
+ const parsed = match.parse(isObject(sent) ? sent : {});
36
+ const entry = { ...request, sent, raw: withoutBase64(request.raw), id: nextId++, time: clock(new Date()),
37
+ protocol: match.protocol, parsed, freshFrom: freshFrom(entries, request.client, parsed) };
38
+ entries.push(entry);
39
+ if (entries.length > exports.CAPTURE_LIMIT) {
40
+ dropped += entries.length - exports.CAPTURE_LIMIT;
41
+ entries = entries.slice(-exports.CAPTURE_LIMIT);
42
+ }
43
+ return status => { entry.failedStatus = status; };
44
+ },
45
+ list() { return { captures: entries.map(view).reverse(), dropped }; },
46
+ };
47
+ }
48
+ // 圖片和檔案的 base64 內容換成「[圖片 N KB]」這類佔位文字,存下的是副本。
49
+ const DATA_URL = /^data:([\w.+-]+\/[\w.+-]+)?(?:;[^,;]*)*;base64,/i;
50
+ function placeholder(mediaType, base64) {
51
+ const bytes = Math.floor(base64.replace(/=+$/, "").length * 3 / 4);
52
+ return `[${mediaType.startsWith("image/") ? "圖片" : "檔案"} ${Math.max(1, Math.round(bytes / 1024))} KB]`;
53
+ }
54
+ function withoutBase64(value) {
55
+ if (typeof value === "string") {
56
+ const match = DATA_URL.exec(value);
57
+ return match ? placeholder(match[1] ?? "", value.slice(match[0].length)) : value;
58
+ }
59
+ if (Array.isArray(value))
60
+ return value.map(withoutBase64);
61
+ if (!isObject(value))
62
+ return value;
63
+ const copy = Object.fromEntries(Object.entries(value).map(([key, item]) => [key, withoutBase64(item)]));
64
+ if (value.type === "base64" && typeof value.data === "string")
65
+ copy.data = placeholder(String(value.media_type ?? ""), value.data);
66
+ return copy;
67
+ }
68
+ function clock(date) {
69
+ return [date.getHours(), date.getMinutes(), date.getSeconds()].map(part => String(part).padStart(2, "0")).join(":");
70
+ }
71
+ // 比對規則:往前找同一個客戶端、訊息序列剛好是本筆開頭的第一筆紀錄,超出的部分是本輪新增;
72
+ // 這樣能跨過交錯出現的子 agent 或背景請求。找不到就是新對話,全部都算新增。
73
+ // 錄下時就決定,之後較早的紀錄被捨去也不會改變。
74
+ function freshFrom(earlier, client, parsed) {
75
+ const match = [...earlier].reverse().find(other => other.client === client && startsWith(parsed.messages, other.parsed.messages));
76
+ return match ? match.parsed.messages.length : null;
77
+ }
78
+ function startsWith(messages, prefix) {
79
+ if (!prefix.length || prefix.length > messages.length)
80
+ return false;
81
+ return prefix.every((message, index) => sameMessage(message, messages[index]));
82
+ }
83
+ function sameMessage(a, b) {
84
+ return a.role === b.role && a.kind === b.kind && a.name === b.name && a.text === b.text;
85
+ }
86
+ function view(entry) {
87
+ const { parsed, freshFrom, sent } = entry;
88
+ const messages = parsed.messages.map((message, index) => ({ ...message, isNew: index >= (freshFrom ?? 0) }));
89
+ const sizes = { system: 0, tools: 0, reminder: 0, history: 0, fresh: 0 };
90
+ for (const text of parsed.system)
91
+ sizes.system += estimateTokens(text);
92
+ for (const tool of parsed.tools)
93
+ sizes.tools += estimateTokens(tool.name + tool.description + JSON.stringify(tool.schema ?? {}));
94
+ for (const message of messages) {
95
+ const size = estimateTokens((message.name ?? "") + message.text);
96
+ if (message.reminder)
97
+ sizes.reminder += size;
98
+ else if (message.isNew)
99
+ sizes.fresh += size;
100
+ else
101
+ sizes.history += size;
102
+ }
103
+ return {
104
+ id: entry.id, time: entry.time, client: entry.client, model: isObject(sent) && typeof sent.model === "string" ? sent.model : "",
105
+ protocol: entry.protocol, adapter: entry.adapter,
106
+ ...(entry.failedStatus !== undefined ? { failedStatus: entry.failedStatus } : {}),
107
+ webSearchFollowUp: entry.webSearchFollowUp === true, newConversation: freshFrom === null,
108
+ system: parsed.system, tools: parsed.tools, messages, sizes,
109
+ total: sizes.system + sizes.tools + sizes.reminder + sizes.history + sizes.fresh,
110
+ sent: entry.sent, raw: entry.raw, path: entry.path,
111
+ };
112
+ }
113
+ /** 中日韓字元每字算 1 個 token,其他字元每 4 個算 1 個。 */
114
+ function estimateTokens(text) {
115
+ const cjk = text.match(/[぀-ヿ㐀-鿿가-힯豈-﫿＀-￯]/g)?.length ?? 0;
116
+ return cjk + Math.ceil((text.length - cjk) / 4);
117
+ }
118
+ function isObject(value) {
119
+ return !!value && typeof value === "object" && !Array.isArray(value);
120
+ }
121
+ function blocks(content) {
122
+ if (typeof content === "string")
123
+ return [{ type: "text", text: content }];
124
+ return Array.isArray(content) ? content.filter(isObject) : [];
125
+ }
126
+ function plainText(content) {
127
+ if (typeof content === "string")
128
+ return content;
129
+ if (!Array.isArray(content))
130
+ return content == null ? "" : JSON.stringify(content, null, 2);
131
+ return blocks(content).map(block => typeof block.text === "string" ? block.text : `[${String(block.type)}]`).join("\n");
132
+ }
133
+ const isReminder = (text) => text.includes("<system-reminder>");
134
+ function textMessage(role, text) {
135
+ return { role, kind: "text", text, reminder: role === "user" && isReminder(text) };
136
+ }
137
+ const texts = (content) => blocks(content).map(block => typeof block.text === "string" ? block.text : "").filter(Boolean);
138
+ /** Each protocol keeps a tool's name and description in `fields` (the tool itself, or its `function`). */
139
+ function toolList(tools, definition) {
140
+ return (Array.isArray(tools) ? tools : []).filter(isObject).map(tool => {
141
+ const { fields, schema } = definition(tool);
142
+ return {
143
+ name: String(fields.name ?? tool.type ?? ""),
144
+ description: typeof fields.description === "string" ? fields.description : "",
145
+ schema: schema ?? null,
146
+ };
147
+ });
148
+ }
149
+ /** Names each tool result after the call it answers, matched by call id. */
150
+ function toolCalls() {
151
+ const names = new Map();
152
+ return {
153
+ use(id, name, text) {
154
+ const tool = String(name ?? "");
155
+ if (typeof id === "string")
156
+ names.set(id, tool);
157
+ return { role: "assistant", kind: "tool_use", name: tool, text, reminder: false };
158
+ },
159
+ result(id, output) {
160
+ const name = typeof id === "string" ? names.get(id) : undefined;
161
+ return { role: "tool", kind: "tool_result", ...(name ? { name } : {}), text: plainText(output), reminder: false };
162
+ },
163
+ };
164
+ }
165
+ /** Tool-call arguments arrive as a JSON string; lay them out like a Messages tool_use input. */
166
+ function callArguments(value) {
167
+ if (typeof value !== "string")
168
+ return JSON.stringify(value ?? {}, null, 2);
169
+ try {
170
+ return JSON.stringify(JSON.parse(value), null, 2);
171
+ }
172
+ catch {
173
+ return value;
174
+ }
175
+ }
176
+ function parseMessages(body) {
177
+ const system = texts(body.system);
178
+ const tools = toolList(body.tools, tool => ({ fields: tool, schema: tool.input_schema }));
179
+ const calls = toolCalls();
180
+ const messages = [];
181
+ for (const message of Array.isArray(body.messages) ? body.messages.filter(isObject) : []) {
182
+ const role = message.role === "assistant" ? "assistant" : "user";
183
+ for (const block of blocks(message.content)) {
184
+ if (block.type === "text" && typeof block.text === "string")
185
+ messages.push(textMessage(role, block.text));
186
+ else if (block.type === "tool_use")
187
+ messages.push(calls.use(block.id, block.name, JSON.stringify(block.input ?? {}, null, 2)));
188
+ else if (block.type === "tool_result")
189
+ messages.push(calls.result(block.tool_use_id, block.content));
190
+ }
191
+ }
192
+ return { system, tools, messages };
193
+ }
194
+ function parseResponses(body) {
195
+ const system = typeof body.instructions === "string" && body.instructions ? [body.instructions] : [];
196
+ const tools = toolList(body.tools, tool => ({ fields: tool, schema: tool.parameters }));
197
+ const calls = toolCalls();
198
+ const messages = [];
199
+ const items = typeof body.input === "string" ? [{ role: "user", content: body.input }] : Array.isArray(body.input) ? body.input.filter(isObject) : [];
200
+ for (const item of items) {
201
+ if (item.type === "function_call" || item.type === "custom_tool_call") {
202
+ messages.push(calls.use(item.call_id, item.name, item.type === "function_call" ? callArguments(item.arguments) : plainText(item.input)));
203
+ }
204
+ else if (item.type === "function_call_output" || item.type === "custom_tool_call_output") {
205
+ messages.push(calls.result(item.call_id, item.output));
206
+ }
207
+ else if (item.type === "input_text" && typeof item.text === "string") {
208
+ messages.push(textMessage("user", item.text));
209
+ }
210
+ else if (typeof item.role === "string" && (item.type === undefined || item.type === "message")) {
211
+ if (item.role === "system" || item.role === "developer")
212
+ system.push(...texts(item.content));
213
+ else
214
+ for (const text of texts(item.content))
215
+ messages.push(textMessage(item.role === "assistant" ? "assistant" : "user", text));
216
+ }
217
+ }
218
+ return { system, tools, messages };
219
+ }
220
+ function parseChat(body) {
221
+ const system = [];
222
+ const tools = toolList(body.tools, tool => {
223
+ const fields = isObject(tool.function) ? tool.function : tool;
224
+ return { fields, schema: fields.parameters };
225
+ });
226
+ const calls = toolCalls();
227
+ const messages = [];
228
+ for (const message of Array.isArray(body.messages) ? body.messages.filter(isObject) : []) {
229
+ if (message.role === "tool") {
230
+ messages.push(calls.result(message.tool_call_id, message.content));
231
+ continue;
232
+ }
233
+ if (message.role === "system" || message.role === "developer") {
234
+ system.push(...texts(message.content));
235
+ continue;
236
+ }
237
+ const role = message.role === "assistant" ? "assistant" : "user";
238
+ for (const text of texts(message.content))
239
+ messages.push(textMessage(role, text));
240
+ for (const call of Array.isArray(message.tool_calls) ? message.tool_calls.filter(isObject) : []) {
241
+ const fn = isObject(call.function) ? call.function : {};
242
+ messages.push(calls.use(call.id, fn.name, callArguments(fn.arguments)));
243
+ }
244
+ }
245
+ return { system, tools, messages };
246
+ }
package/dist/removal.js CHANGED
@@ -5,7 +5,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.removalPreview = removalPreview;
7
7
  exports.prepareRemoval = prepareRemoval;
8
- const node_child_process_1 = require("node:child_process");
9
8
  const promises_1 = __importDefault(require("node:fs/promises"));
10
9
  const node_path_1 = __importDefault(require("node:path"));
11
10
  const node_os_1 = __importDefault(require("node:os"));
@@ -21,21 +20,7 @@ async function prepareRemoval(waitForPid, instanceId) {
21
20
  const root = (0, instance_1.managementDirectory)();
22
21
  const script = node_path_1.default.join(root, "uninstall-tool.ps1");
23
22
  const plan = node_path_1.default.join(root, "uninstall-plan.json");
24
- await promises_1.default.writeFile(script, Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), await (0, desktop_1.asset)("uninstall.ps1")]));
23
+ await (0, desktop_1.writeTool)(script, "uninstall.ps1");
25
24
  await promises_1.default.writeFile(plan, JSON.stringify({ version: 1, root, dataRoot: (0, instance_1.dataDirectory)(), instanceId, pid: process.pid, waitForPid, headless: process.env.CLASSROOM_APP_HEADLESS === "1", installations: await (0, installations_1.installations)() }), { mode: 0o600 });
26
- return async () => {
27
- await promises_1.default.rm(node_path_1.default.join(root, "uninstall-ready"), { force: true });
28
- // Start-Process gives the helper its own hidden console. A PowerShell child
29
- // attached to the worker's console would die when that worker exits.
30
- const literal = (value) => `'${value.replaceAll("'", "''")}'`;
31
- const command = `Start-Process -FilePath powershell.exe -WindowStyle Hidden -ArgumentList @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', ${literal(`"${script}"`)}, '-Plan', ${literal(`"${plan}"`)})`;
32
- const child = (0, node_child_process_1.spawn)("powershell.exe", ["-NoProfile", "-EncodedCommand", Buffer.from(command, "utf16le").toString("base64")], { windowsHide: true, stdio: "ignore" });
33
- await new Promise((resolve, reject) => { child.once("error", reject); child.once("exit", code => code === 0 ? resolve() : reject(new Error("無法啟動移除工具。"))); });
34
- for (let attempt = 0; attempt < 100; attempt++) {
35
- if (await promises_1.default.stat(node_path_1.default.join(root, "uninstall-ready")).catch(() => undefined))
36
- return;
37
- await new Promise(resolve => setTimeout(resolve, 100));
38
- }
39
- throw new Error("移除工具未回應,請重試。");
40
- };
25
+ return () => (0, desktop_1.startHiddenTool)(script, plan, node_path_1.default.join(root, "uninstall-ready"), "移除工具");
41
26
  }