bom-pi 0.0.0-stage → 0.0.2

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.
Files changed (131) hide show
  1. package/README.md +33 -2
  2. package/apps/README.md +7 -0
  3. package/apps/web/README.md +21 -0
  4. package/apps/web/pocket-adapter.mjs +323 -0
  5. package/apps/web/public/LICENSE.pocket +21 -0
  6. package/apps/web/public/activity-fold.js +28 -0
  7. package/apps/web/public/agent-now.js +37 -0
  8. package/apps/web/public/agent-tile.js +79 -0
  9. package/apps/web/public/app.js +975 -0
  10. package/apps/web/public/apple-touch-icon.png +0 -0
  11. package/apps/web/public/artifact-bridge.js +687 -0
  12. package/apps/web/public/avatar.js +87 -0
  13. package/apps/web/public/back.js +554 -0
  14. package/apps/web/public/box-keys.js +216 -0
  15. package/apps/web/public/browser-panel.js +1097 -0
  16. package/apps/web/public/browser.js +68 -0
  17. package/apps/web/public/calls.js +139 -0
  18. package/apps/web/public/chat.js +919 -0
  19. package/apps/web/public/clock.js +34 -0
  20. package/apps/web/public/commands.js +578 -0
  21. package/apps/web/public/composer.js +2068 -0
  22. package/apps/web/public/diff-parse.js +672 -0
  23. package/apps/web/public/diff.js +1646 -0
  24. package/apps/web/public/dock.js +299 -0
  25. package/apps/web/public/extension-ui.js +2734 -0
  26. package/apps/web/public/files-panel.js +775 -0
  27. package/apps/web/public/files.js +368 -0
  28. package/apps/web/public/fonts/FiraCode-VF.woff2 +0 -0
  29. package/apps/web/public/fonts/Geist.woff2 +0 -0
  30. package/apps/web/public/fonts/IBMPlexMono-Variable-Italic.woff2 +0 -0
  31. package/apps/web/public/fonts/IBMPlexMono-Variable.woff2 +0 -0
  32. package/apps/web/public/fonts/InterVariable-Italic.woff2 +0 -0
  33. package/apps/web/public/fonts/InterVariable.woff2 +0 -0
  34. package/apps/web/public/fonts/Iosevka-Bold.woff2 +0 -0
  35. package/apps/web/public/fonts/Iosevka-BoldItalic.woff2 +0 -0
  36. package/apps/web/public/fonts/Iosevka-Italic.woff2 +0 -0
  37. package/apps/web/public/fonts/Iosevka-Regular.woff2 +0 -0
  38. package/apps/web/public/fonts/Iosevka-SemiBold.woff2 +0 -0
  39. package/apps/web/public/fonts/Iosevka-SemiBoldItalic.woff2 +0 -0
  40. package/apps/web/public/fonts/JetBrainsMono-Italic.woff2 +0 -0
  41. package/apps/web/public/fonts/JetBrainsMono.woff2 +0 -0
  42. package/apps/web/public/fonts/NerdFontsSymbolsMono.woff2 +0 -0
  43. package/apps/web/public/fonts/SOURCES.md +69 -0
  44. package/apps/web/public/gestures.js +610 -0
  45. package/apps/web/public/highlight.js +480 -0
  46. package/apps/web/public/history.js +70 -0
  47. package/apps/web/public/home.js +169 -0
  48. package/apps/web/public/icon-192.png +0 -0
  49. package/apps/web/public/icon-512.png +0 -0
  50. package/apps/web/public/icon-maskable-512.png +0 -0
  51. package/apps/web/public/icon.svg +16 -0
  52. package/apps/web/public/index.html +71 -0
  53. package/apps/web/public/launcher.js +1293 -0
  54. package/apps/web/public/linked-sessions.js +55 -0
  55. package/apps/web/public/live.js +39 -0
  56. package/apps/web/public/manifest.webmanifest +32 -0
  57. package/apps/web/public/model-refresh.js +73 -0
  58. package/apps/web/public/notify.js +251 -0
  59. package/apps/web/public/peeks.js +920 -0
  60. package/apps/web/public/pip-attachments.js +182 -0
  61. package/apps/web/public/pip-window.js +141 -0
  62. package/apps/web/public/pip.js +1217 -0
  63. package/apps/web/public/quote-reply.js +109 -0
  64. package/apps/web/public/quote-text.js +31 -0
  65. package/apps/web/public/rich.js +403 -0
  66. package/apps/web/public/run-frame.js +106 -0
  67. package/apps/web/public/safe-mode.js +71 -0
  68. package/apps/web/public/seen.js +169 -0
  69. package/apps/web/public/session-tree.js +117 -0
  70. package/apps/web/public/sessions.js +2695 -0
  71. package/apps/web/public/share.js +126 -0
  72. package/apps/web/public/sheets/appearance.js +820 -0
  73. package/apps/web/public/sheets/branch.js +353 -0
  74. package/apps/web/public/sheets/extensions.js +818 -0
  75. package/apps/web/public/sheets/file.js +318 -0
  76. package/apps/web/public/sheets/find.js +250 -0
  77. package/apps/web/public/sheets/folder.js +680 -0
  78. package/apps/web/public/sheets/gallery.js +2340 -0
  79. package/apps/web/public/sheets/hooks.js +350 -0
  80. package/apps/web/public/sheets/memory.js +531 -0
  81. package/apps/web/public/sheets/menu.js +580 -0
  82. package/apps/web/public/sheets/message.js +220 -0
  83. package/apps/web/public/sheets/model.js +412 -0
  84. package/apps/web/public/sheets/people.js +414 -0
  85. package/apps/web/public/sheets/pi-sessions.js +264 -0
  86. package/apps/web/public/sheets/providers.js +525 -0
  87. package/apps/web/public/sheets/running.js +130 -0
  88. package/apps/web/public/sheets/schedules.js +71 -0
  89. package/apps/web/public/sheets/session.js +249 -0
  90. package/apps/web/public/sheets/shortcuts.js +101 -0
  91. package/apps/web/public/sheets/spend.js +150 -0
  92. package/apps/web/public/sheets/text.js +53 -0
  93. package/apps/web/public/sheets/viewers.js +363 -0
  94. package/apps/web/public/sheets/worktree.js +50 -0
  95. package/apps/web/public/sheets.js +410 -0
  96. package/apps/web/public/signin.js +57 -0
  97. package/apps/web/public/slots.js +208 -0
  98. package/apps/web/public/store.js +1760 -0
  99. package/apps/web/public/style.css +18625 -0
  100. package/apps/web/public/subagents-board.js +879 -0
  101. package/apps/web/public/subagents.js +273 -0
  102. package/apps/web/public/sw.js +169 -0
  103. package/apps/web/public/taps.js +26 -0
  104. package/apps/web/public/theme-surface.d.ts +4 -0
  105. package/apps/web/public/theme-surface.js +266 -0
  106. package/apps/web/public/theme.js +845 -0
  107. package/apps/web/public/themes/lantern/colors.toml +25 -0
  108. package/apps/web/public/themes/lantern/direction.css +60 -0
  109. package/apps/web/public/themes/lantern/frame.css +254 -0
  110. package/apps/web/public/themes/lantern/theme.css +10 -0
  111. package/apps/web/public/themes/lantern/theme.json +7 -0
  112. package/apps/web/public/themes/pocket/theme.css +189 -0
  113. package/apps/web/public/themes/pocket/theme.json +6 -0
  114. package/apps/web/public/themes.js +556 -0
  115. package/apps/web/public/transcript.js +3348 -0
  116. package/apps/web/public/trust.js +295 -0
  117. package/apps/web/public/turns.js +507 -0
  118. package/apps/web/public/ui.js +1910 -0
  119. package/apps/web/public/voice.js +345 -0
  120. package/apps/web/server.mjs +774 -0
  121. package/package.json +43 -4
  122. package/packages/cli/src/bom-pi.mjs +452 -0
  123. package/packages/cli/templates/blank.factory.json +7 -0
  124. package/packages/cli/templates/dev.factory.json +11 -0
  125. package/packages/cli/templates/docs.factory.json +12 -0
  126. package/packages/cli/templates/ops.factory.json +14 -0
  127. package/packages/cli/templates/triage.factory.json +10 -0
  128. package/packages/core/src/daemon.mjs +2047 -0
  129. package/packages/core/src/limit-gate.mjs +192 -0
  130. package/packages/core/src/rpc-client.mjs +66 -0
  131. package/systemd/README.md +11 -0
@@ -0,0 +1,774 @@
1
+ #!/usr/bin/env node
2
+ // bom-web — client web minimal của bom-core (M3: transcript + submit + live events).
3
+ // Không dependency. Chạy: node apps/web/server.mjs [--port 8787] [--listen 127.0.0.1]
4
+ //
5
+ // Auth: đặt BOM_PI_TOKEN thì mọi request cần token (REST: Authorization: Bearer;
6
+ // SSE: /api/events?token=…). Không token → chỉ bind 127.0.0.1 (hoặc --listen
7
+ // 0.0.0.0 tự chịu trách nhiệm — dùng tailscale/lan cá nhân).
8
+ // Truy cập từ phone: chạy trên máy có daemon + tailscale, mở http://<ts-ip>:8787/?token=…
9
+
10
+ import { createServer, connect } from 'node:net';
11
+ import { createServer as createHttpServer } from 'node:http';
12
+ import { userInfo } from 'node:os';
13
+ import { join, resolve, dirname, extname, normalize, sep } from 'node:path';
14
+ import { readFile } from 'node:fs/promises';
15
+ import { fileURLToPath } from 'node:url';
16
+ import process from 'node:process';
17
+ import { COOKIE, makePocketAdapter } from './pocket-adapter.mjs';
18
+
19
+ // UI pocket (clone từ TannerMidd/pi-pocket, MIT) nằm ở public/ — serve tĩnh
20
+ const HERE = dirname(fileURLToPath(import.meta.url));
21
+ const PUBLIC = join(HERE, 'public');
22
+ const VENDOR = {
23
+ 'preact.mjs': ['preact', 'dist', 'preact.mjs'],
24
+ 'preact-hooks.mjs': ['preact', 'hooks', 'dist', 'hooks.mjs'],
25
+ 'htm.mjs': ['htm', 'dist', 'htm.module.js'],
26
+ 'marked.mjs': ['marked', 'lib', 'marked.esm.js'],
27
+ 'purify.mjs': ['dompurify', 'dist', 'purify.es.mjs'],
28
+ };
29
+ const MIME = {
30
+ '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8',
31
+ '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.json': 'application/json',
32
+ '.webmanifest': 'application/manifest+json', '.woff2': 'font/woff2', '.md': 'text/markdown; charset=utf-8',
33
+ '.ts': 'text/plain; charset=utf-8',
34
+ };
35
+ async function serveFile(res, file) {
36
+ try {
37
+ const buf = await readFile(file);
38
+ res.writeHead(200, { 'content-type': MIME[extname(file)] ?? 'application/octet-stream', ...CORS });
39
+ res.end(buf);
40
+ return true;
41
+ } catch { return false; }
42
+ }
43
+ // static public/ + /vendor từ node_modules — KHÔNG cần token (shell công khai, API mới là cổng)
44
+ async function serveStatic(res, url) {
45
+ if (url.pathname === '/') return serveFile(res, join(PUBLIC, 'index.html'));
46
+ if (url.pathname.startsWith('/vendor/')) {
47
+ const v = VENDOR[url.pathname.slice('/vendor/'.length)];
48
+ if (!v) return false;
49
+ // monorepo workspace: npm có thể hoist về root — thử apps/web rồi root
50
+ const local = join(HERE, 'node_modules', ...v);
51
+ if (await serveFile(res, local)) return true;
52
+ return serveFile(res, join(HERE, '..', '..', 'node_modules', ...v));
53
+ }
54
+ const rel = normalize(url.pathname).replace(/^([/\\])+/, '');
55
+ if (rel.includes('..')) return false;
56
+ return serveFile(res, join(PUBLIC, rel));
57
+ }
58
+
59
+ const TOKEN = process.env.BOM_PI_TOKEN || null;
60
+ const socketPath = process.env.BOM_PI_SOCKET || resolve(process.env.XDG_RUNTIME_DIR || `/tmp/run-${userInfo().uid}`, 'bom-pi.sock');
61
+
62
+ function arg(name, fallback) {
63
+ const i = process.argv.indexOf(`--${name}`);
64
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback;
65
+ }
66
+ const PORT = Number(arg('port', 8791));
67
+ // M8: mặc định 0.0.0.0 — phone pair qua LAN bằng code (bom-pi pair); API vẫn khóa per-device
68
+ const LISTEN = arg('listen', '0.0.0.0');
69
+
70
+ // ---- client của bom-core (NDJSON JSON-RPC trên unix socket) ----
71
+ function rpcConn() {
72
+ return new Promise((done, fail) => {
73
+ const conn = connect(socketPath);
74
+ conn.once('connect', () => done(conn));
75
+ conn.once('error', (e) => fail(new Error(`cannot reach bom-core at ${socketPath}: ${e.message}`)));
76
+ });
77
+ }
78
+ async function rpc(method, params) {
79
+ const conn = await rpcConn();
80
+ return new Promise((done, fail) => {
81
+ let buf = '';
82
+ const t = setTimeout(() => { conn.destroy(); fail(new Error('timeout after 8s')); }, 8000);
83
+ conn.on('data', (c) => {
84
+ buf += c.toString('utf8');
85
+ const nl = buf.indexOf('\n');
86
+ if (nl >= 0) {
87
+ conn.end();
88
+ clearTimeout(t);
89
+ try {
90
+ const res = JSON.parse(buf.slice(0, nl));
91
+ if (res.error) fail(new Error(`${res.error.code}: ${res.error.message}`));
92
+ else done(res.result);
93
+ } catch (e) { fail(e); }
94
+ }
95
+ });
96
+ conn.on('close', () => { clearTimeout(t); fail(new Error('bom-core closed without a reply')); });
97
+ conn.on('error', (e) => { clearTimeout(t); fail(e); });
98
+ conn.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method, params: params ?? {} }) + '\n');
99
+ });
100
+ }
101
+
102
+ // ---- Auth (M8 + security review): /api/* LUÔN cần token (master BOM_PI_TOKEN hoặc
103
+ // device token bom_… từ pairing — verify MỖI request qua daemon, revoke tức thì).
104
+ // Static UI (/, /pair, PWA) public — không dữ liệu. FAIL-CLOSED: chưa pair / daemon không
105
+ // phản hồi ⇒ 401 (vá lỗ bootstrap-mở + catch-true: kẻ khác trên LAN cross-origin điều khiển
106
+ // được API — kể cả approvals.answer = RCE — trong giai đoạn chưa pair). ----
107
+ async function verifyDeviceToken(token) {
108
+ if (!/^bom_[A-Za-z0-9_-]{43}$/.test(token ?? '')) return false;
109
+ try { return (await rpc('devices.verify', { token })).ok === true; } catch { return false; }
110
+ }
111
+ const authorized = async (req, url) => {
112
+ if (url.pathname === '/api/pair/start') return true; // public — tự vệ bằng code + rate-limit daemon
113
+ if (!url.pathname.startsWith('/api/')) return true; // static UI/PWA — không dữ liệu
114
+ const header = req.headers.authorization ?? '';
115
+ const bearer = header.startsWith('Bearer ') ? header.slice(7) : null;
116
+ const qToken = url.searchParams.get('token');
117
+ if (TOKEN && (bearer === TOKEN || qToken === TOKEN)) return true; // master
118
+ for (const t of [bearer, qToken]) {
119
+ if (t && (await verifyDeviceToken(t))) return true; // device token (SSE qua ?token=)
120
+ }
121
+ return false;
122
+ };
123
+
124
+ // ---- Events fan-out cho pocket adapter: một socket dài, events.update của daemon
125
+ // báo mọi client SSE pocket làm mới (pull-on-push). ----
126
+ const eventListeners = new Set();
127
+ const watchedConvs = new Set();
128
+ let eventsSocket = null;
129
+ async function ensureEventsSocket(cid) {
130
+ if (eventsSocket) {
131
+ // subscribe thêm conversation đang mở (events.subscribe rỗng chỉ watch active conv)
132
+ if (Number.isInteger(cid) && cid > 0 && !watchedConvs.has(cid)) {
133
+ watchedConvs.add(cid);
134
+ eventsSocket.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'events.subscribe', params: { conversationId: cid } }) + '\n');
135
+ }
136
+ return;
137
+ }
138
+ const conn = await rpcConn();
139
+ eventsSocket = conn;
140
+ let buf = '';
141
+ conn.on('data', (c) => {
142
+ buf += c.toString('utf8');
143
+ let nl;
144
+ while ((nl = buf.indexOf('\n')) >= 0) {
145
+ const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
146
+ try {
147
+ const msg = JSON.parse(line);
148
+ if (msg.method === 'events.update') for (const fn of eventListeners) fn(msg.params);
149
+ } catch { /* dòng chưa trọn */ }
150
+ }
151
+ });
152
+ conn.on('close', () => { eventsSocket = null; watchedConvs.clear(); });
153
+ conn.on('error', () => { eventsSocket = null; });
154
+ conn.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'events.subscribe', params: {} }) + '\n');
155
+ if (Number.isInteger(cid) && cid > 0) {
156
+ watchedConvs.add(cid);
157
+ conn.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'events.subscribe', params: { conversationId: cid } }) + '\n');
158
+ }
159
+ }
160
+ rpc.__subscribeEvents = async (cid, onChange) => {
161
+ await ensureEventsSocket(cid);
162
+ eventListeners.add(onChange);
163
+ return { close() { eventListeners.delete(onChange); } };
164
+ };
165
+
166
+ // ---- pocket wire (cookie pocket_auth — sign-in qua /login?token= sau khi pair) ----
167
+ const cookieToken = (req) => (req.headers.cookie ?? '').match(new RegExp(`${COOKIE}=([^;]+)`))?.[1] ?? null;
168
+ const pocketCookieOk = async (req) => { const t = cookieToken(req); return t && (TOKEN ? t === TOKEN || await verifyDeviceToken(t) : await verifyDeviceToken(t)); };
169
+ const pocketRoute = makePocketAdapter({ rpc, checkToken: async (t) => (TOKEN ? t === TOKEN : false) || (await verifyDeviceToken(t)) });
170
+
171
+ // ---- HTML (mobile-first, không framework) ----
172
+ const HTML = `<!doctype html>
173
+ <html lang="en"><head>
174
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
175
+ <meta name="theme-color" content="#101418"><link rel="manifest" href="/manifest.webmanifest"><link rel="icon" href="/icon.svg" type="image/svg+xml">
176
+ <title>bom</title><style>
177
+ :root{color-scheme:dark}body{font:15px/1.45 system-ui,sans-serif;background:#101418;color:#e6edf3;margin:0;padding:12px;max-width:1200px;margin-inline:auto}
178
+ h1{font-size:16px;margin:4px 0 12px;display:flex;justify-content:space-between;align-items:baseline}
179
+ #conn{font-size:12px;color:#7d8590}#conn.ok{color:#3fb950}#conn.bad{color:#f85149}
180
+ #app{display:grid;grid-template-columns:230px 1fr 340px;gap:12px;align-items:start}
181
+ @media(max-width:900px){#app{grid-template-columns:1fr}}
182
+ .side{border:1px solid #21262d;border-radius:10px;padding:10px}
183
+ .side h2{font-size:12px;color:#7d8590;margin:2px 0 8px;text-transform:uppercase;letter-spacing:.04em}
184
+ .fac{padding:7px 9px;border-radius:8px;cursor:pointer;margin:2px 0;display:flex;gap:8px;align-items:center}
185
+ .fac:hover{background:#161b22}.fac.on{background:#131c26;border:1px solid #30363d}
186
+ .fac .dot{width:8px;height:8px;border-radius:50%;background:#3fb950;flex:none}.fac .dot.off{background:#484f58}
187
+ .pg{padding:6px 9px 6px 18px;border-radius:8px;cursor:pointer;margin:2px 0;color:#9198a1}
188
+ .pg:hover{background:#161b22}.pg.on{background:#131c26;color:#e6edf3}
189
+ #tabs{display:flex;gap:6px;margin-bottom:8px}
190
+ #tabs button{background:#161b22;color:#9198a1;padding:6px 12px}
191
+ #tabs button.on{background:#1f6feb;color:#fff}
192
+ #page{display:none;border:1px solid #21262d;border-radius:10px;padding:14px 16px;overflow:auto}
193
+ #page h1,#page h2,#page h3{margin:14px 0 6px}#page h1{font-size:20px}#page h2{font-size:17px}
194
+ #page code{background:#161b22;border-radius:4px;padding:1px 5px;font-size:13px}
195
+ #page pre{background:#161b22;border-radius:8px;padding:10px;overflow:auto}
196
+ #page pre code{background:none;padding:0}
197
+ #page a{color:#58a6ff}#page ul{padding-left:20px;margin:6px 0}
198
+ #box{display:flex;gap:8px;margin-bottom:10px}
199
+ #text{flex:1;background:#161b22;color:#e6edf3;border:1px solid #30363d;border-radius:8px;padding:9px}
200
+ button{background:#1f6feb;color:#fff;border:0;border-radius:8px;padding:9px 14px;font-weight:600}
201
+ button:disabled{opacity:.5}
202
+ #model{background:#161b22;color:#e6edf3;border:1px solid #30363d;border-radius:8px;padding:9px;max-width:46%}
203
+ .e{border:1px solid #21262d;border-radius:10px;padding:8px 10px;margin:8px 0;white-space:pre-wrap;word-break:break-word}
204
+ .e.user{background:#131c26}.e.assistant{background:#14171c}.e .k{font-size:11px;color:#7d8590;margin-bottom:3px}
205
+ .e.error{border-color:#5a1d1d;color:#ffa198}
206
+ form{margin:0}
207
+ </style></head><body>
208
+ <h1><span>bom</span><span><button id="bell" title="Notify on pending approvals" style="padding:2px 7px;font-size:12px;background:#161b22">🔔</button> <span id="conn">connecting…</span></span></h1>
209
+ <div id="app">
210
+ <div class="side" id="sidefac">
211
+ <h2>Factories</h2>
212
+ <div id="faclist"><div style="color:#7d8590">—</div></div>
213
+ <h2 style="margin-top:12px">Pages</h2>
214
+ <div id="pagelist"><div style="color:#7d8590">no factory</div></div>
215
+ <h2 style="margin-top:12px">Fleet hosts</h2>
216
+ <div id="hostlist"><div style="color:#7d8590">just this machine</div></div>
217
+ <div style="display:flex;gap:6px;margin-top:6px">
218
+ <input id="nhost" placeholder="http://host:8791" style="flex:1;background:#161b22;color:#e6edf3;border:1px solid #30363d;border-radius:8px;padding:6px 8px;font-size:13px">
219
+ <button onclick="addHost()" style="padding:6px 10px">+</button>
220
+ </div>
221
+ <input id="ntoken" placeholder="token (if that host uses one)" style="width:calc(100% - 16px);box-sizing:border-box;background:#161b22;color:#e6edf3;border:1px solid #30363d;border-radius:8px;padding:6px 8px;font-size:13px;margin-top:6px">
222
+ </div>
223
+ <div id="focus">
224
+ <div id="tabs">
225
+ <button id="tabTr" class="on">Transcript</button>
226
+ <button id="tabPg">Page</button>
227
+ <button id="tabMt">Metrics</button>
228
+ </div>
229
+ <div id="list"></div>
230
+ <div id="page"></div>
231
+ <div id="metrics" style="display:none"></div>
232
+ </div>
233
+ <div class="side">
234
+ <div id="box2" style="display:flex;gap:8px;margin-bottom:8px">
235
+ <select id="conv" style="flex:1;background:#161b22;color:#e6edf3;border:1px solid #30363d;border-radius:8px;padding:8px"></select>
236
+ <button id="newconv" title="New conversation">+</button>
237
+ </div>
238
+ <form id="f"><div id="box">
239
+ <select id="model"></select>
240
+ <input id="text" autocomplete="off" placeholder="Message bom-core…">
241
+ <button id="reset" title="Fresh context (same conversation)">↺</button>
242
+ <button id="send">Send</button>
243
+ </div></form>
244
+ <div id="approvals"></div>
245
+ </div>
246
+ </div>
247
+ <script>
248
+ const q=new URLSearchParams(location.search),TOKEN=q.get('token');
249
+ // M8: device token từ pairing (localStorage) — dùng khi host không có token riêng
250
+ const DEV=(()=>{try{return JSON.parse(localStorage.getItem('bom.device')||'null')}catch(e){return null}})();
251
+ const H={};if(TOKEN)H.Authorization='Bearer '+TOKEN;
252
+ // ---- Fleet (M5c2): danh sách {host,token} trong localStorage, fan-out gộp danh sách ----
253
+ // host '' = máy này. Chọn factory host nào ⇒ transcript/pages/chat host đó.
254
+ let HOSTS=[{host:'',token:TOKEN||''}];
255
+ try{const s=JSON.parse(localStorage.getItem('bom.hosts')||'[]');if(Array.isArray(s)&&s.length)HOSTS=[{host:'',token:TOKEN||''},...s.filter(x=>x&&typeof x.host==='string'&&x.host)];}catch(e){}
256
+ let CUR=''; // host đang thao tác (conversation/pages/chat)
257
+ function saveHosts(){localStorage.setItem('bom.hosts',JSON.stringify(HOSTS.filter(h=>h.host)));}
258
+ function hh(host){const h=HOSTS.find(x=>x.host===host)||HOSTS[0];return h.token?{Authorization:'Bearer '+h.token}:(DEV?{Authorization:'Bearer '+DEV.token}:{});}
259
+ function api(host,path,opts){const h=HOSTS.find(x=>x.host===host)||HOSTS[0];return fetch(h.host+path,Object.assign({},opts,{headers:Object.assign({},hh(host),opts&&opts.headers||{})}));}
260
+ const $=id=>document.getElementById(id);
261
+ const esc=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
262
+ function render(e){
263
+ const d=document.createElement('div');
264
+ d.className='e '+e.kind.replace('pi.','')+(e.error?' error':'');
265
+ d.innerHTML='<div class="k">'+esc(e.kind)+' · #'+esc(e.id)+'</div>'+esc(e.text||'')+(e.error?'<div class="k">'+esc(e.error)+'</div>':'');
266
+ return d;
267
+ }
268
+ function setEntries(list){const L=$('list');L.innerHTML='';for(const e of list)L.appendChild(render(e));window.scrollTo(0,document.body.scrollHeight);}
269
+ // ---- markdown renderer mini (~40 dòng: heading/bold/code/fence/list/link) — M5c1 ----
270
+ function md(src){
271
+ const FENCE='\`\`\`';
272
+ const ls=String(src??'').split('\\n');let out='',inFence=false,list=false;
273
+ const inline=s=>esc(s)
274
+ .replace(new RegExp('\`([^\`]+)\`','g'),'<code>$1</code>')
275
+ .replace(/\\*\\*([^*]+)\\*\\*/g,'<b>$1</b>')
276
+ .replace(/\\[([^\\]]+)\\]\\((https?:[^)\\s]+)\\)/g,'<a href="$2" target="_blank" rel="noopener">$1</a>');
277
+ for(const l of ls){
278
+ if(l.startsWith(FENCE)){out+=inFence?'</code></pre>':'<pre><code>';inFence=!inFence;continue;}
279
+ if(inFence){out+=esc(l)+'\\n';continue;}
280
+ const h=l.match(/^(#{1,6})\\s+(.*)$/);
281
+ if(h){if(list){out+='</ul>';list=false;}out+='<h'+h[1].length+'>'+inline(h[2])+'</h'+h[1].length+'>';continue;}
282
+ const li=l.match(/^\\s*[-*]\\s+(.*)$/);
283
+ if(li){if(!list){out+='<ul>';list=true;}out+='<li>'+inline(li[1])+'</li>';continue;}
284
+ if(list){out+='</ul>';list=false;}
285
+ out+=l.trim()?('<p>'+inline(l)+'</p>'):'';
286
+ }
287
+ if(list)out+='</ul>';if(inFence)out+='</code></pre>';
288
+ return out;
289
+ }
290
+ let CID=null,FID=null,PGNAME=null;
291
+ function showTab(pg){ // 'tr' | 'pg' | 'mt' (Metrics M6c)
292
+ $('tabTr').className=pg==='tr'?'on':'';
293
+ $('tabPg').className=pg==='pg'?'on':'';
294
+ $('tabMt').className=pg==='mt'?'on':'';
295
+ $('list').style.display=pg==='tr'?'block':'none';
296
+ $('page').style.display=pg==='pg'?'block':'none';
297
+ $('metrics').style.display=pg==='mt'?'block':'none';
298
+ if(pg==='mt')loadMetrics();
299
+ }
300
+ $('tabTr').onclick=()=>showTab('tr');$('tabPg').onclick=()=>showTab('pg');$('tabMt').onclick=()=>showTab('mt');
301
+ // ---- M6c: dashboard số đo trust ladder (merges/tuần · deny-rate · can thiệp · usage) ----
302
+ async function loadMetrics(){
303
+ try{
304
+ const r=await api(CUR,'/api/metrics').then(x=>x.json());
305
+ const w=r.window7d,d=r.window24h;
306
+ const row=(label,x)=>'<div style="display:flex;gap:14px;flex-wrap:wrap;margin:4px 0">'+
307
+ '<span><b>'+x.merges.merged+'</b>/'+x.merges.proposed+' merges</span>'+
308
+ '<span>review ✓'+x.merges.reviewApprove+' ✗'+x.merges.reviewRequestChanges+'</span>'+
309
+ '<span>deny-rate <b>'+(x.approvals.denyRate*100).toFixed(0)+'%</b> ('+x.approvals.denied+'/'+x.approvals.total+')</span>'+
310
+ '<span>can thiệp <b>'+x.interventions.total+'</b> (abort '+x.interventions.aborts+' · stop '+x.interventions.stops+' · tự hạ '+x.interventions.demotions+')</span></div>';
311
+ let html='<div class="k">trust ladder · G2 mục tiêu ≥'+w.merges.mergesPerWeekTarget+' merge/tuần</div>'+
312
+ row('7d',w)+row('24h',d)+
313
+ '<table style="width:100%;border-collapse:collapse;margin-top:8px;font-size:13px"><tr style="color:#7d8590"><th align="left">factory</th><th>autonomy</th><th>can thiệp 24h</th><th>7d</th><th>merges 7d</th></tr>'+
314
+ (r.factories||[]).map(f=>'<tr><td>'+esc(f.name||f.id)+'</td><td align="center"><b>'+esc(f.autonomy)+'</b></td><td align="center">'+f.interventions24h+'</td><td align="center">'+f.interventions7d+'</td><td align="center">'+f.merges7d+'</td></tr>').join('')+'</table>'+
315
+ '<div class="k" style="margin-top:10px">usage (daemon-wide)</div><pre style="color:#9198a1;font-size:12px;white-space:pre-wrap">'+esc(JSON.stringify(r.usage,null,1))+'</pre>';
316
+ $('metrics').innerHTML=html;
317
+ }catch(e){$('metrics').innerHTML='<div class="e error">'+esc(e.message)+'</div>';}
318
+ }
319
+ async function loadFactories(){
320
+ // fan-out mọi host trong fleet — gộp danh sách (spec §12), label host khi >1
321
+ const all=await Promise.all(HOSTS.map(h=>api(h.host,'/api/factories').then(r=>r.json()).then(j=>(j.factories||[]).map(f=>({...f,host:h.host}))).catch(()=>[])));
322
+ const flat=all.flat();
323
+ const multi=HOSTS.length>1;
324
+ $('faclist').innerHTML=flat.length?flat.map(f=>
325
+ '<div class="fac'+(f.id===FID&&f.host===CUR?' on':'')+'" onclick="pickFactory(\\''+esc(f.host)+'\\',\\''+esc(f.id)+'\\')">'+
326
+ '<span class="dot'+(f.status==='mounted'?'':' off')+'"></span>'+
327
+ '<span><b>'+esc(f.name||f.id)+'</b>'+(multi?'<small style="color:#7d8590"> @'+esc(f.host||'local')+'</small>':'')+
328
+ '<br><small style="color:#7d8590">sched '+f.schedules.enabled+'/'+f.schedules.total+' · pages '+f.pages+'</small></span></div>').join('')
329
+ :'<div style="color:#7d8590">no factories — bom-pi factory init</div>';
330
+ }
331
+ async function loadPages(){
332
+ if(!FID){$('pagelist').innerHTML='<div style="color:#7d8590">no factory</div>';return;}
333
+ try{
334
+ const r=await api(CUR,'/api/pages?factoryId='+encodeURIComponent(FID)).then(x=>x.json());
335
+ $('pagelist').innerHTML=r.pages&&r.pages.length?r.pages.map(p=>
336
+ '<div class="pg'+(p.name===PGNAME?' on':'')+'" onclick="pickPage(\\''+esc(p.name)+'\\')">'+esc(p.title||p.name)+'</div>').join('')
337
+ :'<div style="color:#7d8590;padding-left:8px">no pages yet</div>';
338
+ }catch(e){}
339
+ }
340
+ window.pickFactory=async (host,id)=>{CUR=host||'';FID=id;PGNAME=null;await loadFactories();await loadPages();await loadConversations();openEvents();refresh();};
341
+ window.pickPage=async name=>{
342
+ PGNAME=name;await loadPages();
343
+ try{
344
+ const r=await api(CUR,'/api/pages/get?factoryId='+encodeURIComponent(FID)+'&name='+encodeURIComponent(name));
345
+ const j=await r.json();
346
+ if(!r.ok)throw new Error(j.error||r.statusText);
347
+ $('page').innerHTML='<div style="font-size:11px;color:#7d8590;margin-bottom:8px">'+esc(name)+' · '+esc(FID)+(CUR?' · '+esc(CUR):'')+'</div>'+md(j.content);
348
+ showTab('pg');
349
+ }catch(e){$('page').innerHTML='<div class="e error">'+esc(e.message)+'</div>';showTab('pg');}
350
+ };
351
+ async function loadConversations(keep){
352
+ const r=await api(CUR,'/api/sessions').then(x=>x.json());
353
+ const sel=$('conv');
354
+ sel.innerHTML=r.conversations.map(c=>'<option value="'+c.id+'">'+esc((c.root?'#'+c.id:c.id)+(c.active?' · active':'')+' — '+(c.model?c.model.provider+'/'+c.model.modelId:'no model'))+'</option>').join('');
355
+ if(keep!=null)CID=keep;
356
+ sel.value=String(CID!=null?CID:r.active);
357
+ CID=Number(sel.value);
358
+ }
359
+ async function refresh(){
360
+ const [tr]=await Promise.all([api(CUR,'/api/transcript'+(CID!=null?'?cid='+CID:'')).then(r=>r.json())]);
361
+ setEntries(tr.entries);
362
+ }
363
+ (async()=>{
364
+ try{
365
+ const [hello,ml]=await Promise.all([
366
+ api('','/api/hello').then(r=>r.json()),
367
+ api('','/api/models').then(r=>r.json()),
368
+ ]);
369
+ document.title='bom · '+hello.version;
370
+ const sel=$('model');sel.innerHTML='<option value="">model (as configured)</option>'+
371
+ ml.models.map(m=>'<option value="'+esc(m.provider+'/'+m.id)+'">'+esc(m.provider+'/'+m.id)+'</option>').join('');
372
+ const last=localStorage.getItem('bom.model');if(last)sel.value=last;
373
+ await loadConversations();
374
+ await loadFactories();
375
+ await loadPages();
376
+ await refresh();
377
+ }catch(e){$('conn').textContent='error: '+e.message;$('conn').className='bad';}
378
+ })();
379
+ let es=null;
380
+ function openEvents(){
381
+ if(es)es.close();
382
+ const h=HOSTS.find(x=>x.host===CUR)||HOSTS[0];
383
+ const q=new URLSearchParams();if(h.token)q.set('token',h.token);else if(DEV)q.set('token',DEV.token);if(CID!=null)q.set('cid',CID);
384
+ es=new EventSource(h.host+'/api/events?'+q);
385
+ es.onopen=()=>{$('conn').textContent='live';$('conn').className='ok';};
386
+ es.onerror=()=>{$('conn').textContent='disconnected';$('conn').className='bad';};
387
+ es.addEventListener('update',ev=>{const p=JSON.parse(ev.data);setEntries(p.entries);});
388
+ es.addEventListener('heartbeat',()=>{if($('conn').className!=='bad'){$('conn').textContent='live · '+new Date().toLocaleTimeString();}});
389
+ }
390
+ openEvents();
391
+ $('conv').onchange=async()=>{
392
+ CID=Number($('conv').value);
393
+ try{await api(CUR,'/api/session/switch',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id:CID})});}catch(e){}
394
+ openEvents();refresh();
395
+ };
396
+ $('newconv').onclick=async()=>{
397
+ const model=$('model').value;
398
+ try{
399
+ const r=await api(CUR,'/api/session/new',{method:'POST',headers:{'Content-Type':'application/json'},
400
+ body:JSON.stringify({model:model||undefined})});
401
+ const j=await r.json();
402
+ if(!r.ok)throw new Error(j.error||r.statusText);
403
+ await loadConversations(j.conversationId);
404
+ openEvents();refresh();
405
+ }catch(e){alert('new conversation failed: '+e.message);}
406
+ };
407
+ $('reset').onclick=async ev=>{
408
+ ev.preventDefault();
409
+ if(!confirm('Reset context? Fresh start, same conversation.'))return;
410
+ try{await api(CUR,'/api/reset',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});}catch(e){alert('reset failed: '+e.message);}
411
+ };
412
+ // ---- Fleet UI: thêm/xoá host (localStorage) ----
413
+ function renderHosts(){
414
+ const el=$('hostlist');if(!el)return;
415
+ el.innerHTML=HOSTS.filter(h=>h.host).map(h=>
416
+ '<div class="pg" style="display:flex;justify-content:space-between"><span>'+esc(h.host)+'</span>'+
417
+ '<button style="padding:2px 8px" onclick="rmHost(\\''+esc(h.host)+'\\')">✕</button></div>').join('');
418
+ }
419
+ window.addHost=()=>{
420
+ const host=$('nhost').value.trim().replace(/\\/+$/,''),token=$('ntoken').value.trim();
421
+ if(!host)return;
422
+ if(HOSTS.some(h=>h.host===host))return;
423
+ HOSTS.push({host,token});
424
+ saveHosts();renderHosts();loadFactories();
425
+ $('nhost').value='';$('ntoken').value='';
426
+ };
427
+ window.rmHost=host=>{HOSTS=HOSTS.filter(h=>h.host!==host);if(CUR===host)CUR='';saveHosts();renderHosts();loadFactories();};
428
+ // ---- approvals: poll 3s FAN-OUT mọi host, thẻ chờ với Allow/Deny (answer về đúng host) ----
429
+ async function pollApprovals(){
430
+ try{
431
+ const per=await Promise.all(HOSTS.map(h=>api(h.host,'/api/approvals').then(r=>r.json()).then(j=>(j.pending||[]).map(a=>({...a,host:h.host}))).catch(()=>[])));
432
+ const pending=per.flat();
433
+ notifyApprovals(pending);
434
+ const box=$('approvals');
435
+ if(!pending.length){if(box.innerHTML)box.innerHTML='';return;}
436
+ box.innerHTML=pending.map(a=>{
437
+ // M6a: merge approval hiện branch → base + title + commits thay vì dòng lệnh
438
+ const body=a.type==='merge'
439
+ ?'<div><b>merge</b> '+esc(a.branch)+' → '+esc(a.base)+' · '+esc(a.title)+'</div>'+
440
+ (a.summary?'<div style="opacity:.8">'+esc(a.summary)+'</div>':'')+
441
+ (a.review&&a.review.verdict?'<div style="margin-top:2px">review: <b>'+esc(a.review.verdict)+'</b>'+(a.review.page?' · page <i>'+esc(a.review.page)+'</i>':'')+'</div>':'')+
442
+ (a.commits&&a.commits.length?'<div style="opacity:.65;font-size:12px;margin-top:4px">'+a.commits.slice(0,10).map(esc).join('<br>')+(a.commits.length>10?'<br>…':'')+'</div>':'')
443
+ :'<div>$ '+esc(a.command)+'</div>';
444
+ return '<div class="e user"><div class="k">approval chờ · conv '+esc(a.conversationId)+' · '+esc(a.type==='merge'?'merge':a.tool)+(a.host?' · '+esc(a.host):'')+'</div>'+
445
+ body+
446
+ '<div style="margin-top:6px;display:flex;gap:8px">'+
447
+ '<button onclick="answerApproval(\\''+esc(a.host||'')+'\\',\\''+esc(a.id)+'\\',true)">Allow</button>'+
448
+ '<button onclick="answerApproval(\\''+esc(a.host||'')+'\\',\\''+esc(a.id)+'\\',false)">Deny</button></div></div>';}).join('');
449
+ }catch(e){}
450
+ }
451
+ window.answerApproval=async(host,id,allow)=>{
452
+ try{
453
+ const r=await api(host,'/api/approvals/answer',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({id,allow})});
454
+ if(!r.ok)throw new Error((await r.json()).error||r.statusText);
455
+ pollApprovals();
456
+ }catch(e){alert('answer failed: '+e.message);}
457
+ };
458
+ setInterval(pollApprovals,3000);pollApprovals();renderHosts();
459
+ // ---- M8: PWA + notification approvals (tab mở/kể cả nền) + badge tiêu đề ----
460
+ if('serviceWorker' in navigator)navigator.serviceWorker.register('/sw.js').catch(()=>{});
461
+ $('bell').onclick=async()=>{
462
+ if(!('Notification' in window)){alert('no Notification API');return;}
463
+ const p=await Notification.requestPermission();
464
+ $('bell').style.background=p==='granted'?'#1f6feb':'#161b22';
465
+ if(p==='granted')new Notification('bom',{body:'Will notify when approvals are pending'});
466
+ };
467
+ let seenApprovals=new Set();
468
+ function notifyApprovals(pending){
469
+ const ids=pending.map(a=>a.id);
470
+ document.title=(ids.length?'('+ids.length+') ':'')+'bom';
471
+ if(Notification.permission!=='granted'||!ids.length){seenApprovals=new Set(ids);return;}
472
+ for(const a of pending){
473
+ if(seenApprovals.has(a.id))continue;
474
+ new Notification(a.type==='merge'?('merge: '+(a.review&&a.review.verdict?a.review.verdict+' · ':'')+a.title):('approval: '+a.tool),{body:a.type==='merge'?((a.branch||'')+' → '+(a.base||'')):String(a.command||'').slice(0,120),tag:a.id});
475
+ }
476
+ seenApprovals=new Set(ids);
477
+ }
478
+ $('f').onsubmit=async ev=>{
479
+ ev.preventDefault();
480
+ const text=$('text').value.trim();if(!text)return;
481
+ const model=$('model').value;localStorage.setItem('bom.model',model);
482
+ $('send').disabled=true;
483
+ try{
484
+ const r=await api(CUR,'/api/submit',{method:'POST',headers:{'Content-Type':'application/json'},
485
+ body:JSON.stringify({text,model:model||undefined})});
486
+ const j=await r.json();
487
+ if(!r.ok)throw new Error(j.error||r.statusText);
488
+ $('text').value='';
489
+ }catch(e){alert('submit failed: '+e.message);}
490
+ $('send').disabled=false;$('text').focus();
491
+ };
492
+ </script></body></html>`;
493
+
494
+ // ---- HTTP ----
495
+ // CORS (M5c2): fleet view fan-out cross-origin từ phone — ACAO * + preflight OPTIONS;
496
+ // token vẫn kiểm tra trước khi trả nội dung (ACAO chỉ cho browser ĐỌC khi đã authorized)
497
+ const CORS = {
498
+ 'access-control-allow-origin': '*',
499
+ 'access-control-allow-methods': 'GET,POST,OPTIONS',
500
+ 'access-control-allow-headers': 'Authorization,Content-Type',
501
+ };
502
+ const json2 = (res, code, obj) => { res.writeHead(code, { 'content-type': 'application/json', ...CORS }); res.end(JSON.stringify(obj)); };
503
+
504
+ // ---- Pairing UI (M8): nhập code từ `bom-pi pair` — token về localStorage, dùng lại mãi ----
505
+ const PAIR_HTML = `<!doctype html><html lang="en"><head>
506
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
507
+ <title>bom · pair device</title><style>
508
+ :root{color-scheme:dark}body{font:15px/1.5 system-ui,sans-serif;background:#101418;color:#e6edf3;display:grid;place-items:center;min-height:100vh;margin:0}
509
+ form{border:1px solid #21262d;border-radius:12px;padding:22px;width:min(340px,92vw);background:#0d1117}
510
+ h1{font-size:17px;margin:0 0 6px}p{color:#7d8590;font-size:13px;margin:4px 0 14px}
511
+ input{width:100%;box-sizing:border-box;background:#161b22;color:#e6edf3;border:1px solid #30363d;border-radius:8px;padding:11px;font-size:16px;margin:4px 0 10px;text-transform:uppercase;letter-spacing:.12em}
512
+ input:disabled{opacity:.55}#name{text-transform:none;letter-spacing:normal}
513
+ #code{font-weight:700}
514
+ button{width:100%;background:#1f6feb;color:#fff;border:0;border-radius:8px;padding:12px;font-weight:600;font-size:15px}
515
+ #msg{font-size:13px;margin-top:10px;min-height:18px}#msg.ok{color:#3fb950}#msg.err{color:#f85149}
516
+ </style></head><body><form onsubmit="return go()">
517
+ <h1>Pair this device</h1>
518
+ <p>Run <code>bom-pi pair</code> on your machine — scan the QR or open the link it prints.</p>
519
+ <p id="who" style="display:none;color:#58a6ff;font-weight:600"></p>
520
+ <p id="hint">Or type the one-time code (5 min) below.</p>
521
+ <input id="code" placeholder="CODE" autocomplete="off" autofocus>
522
+ <input id="name" placeholder="device name (e.g. phone)" autocomplete="off">
523
+ <button>Pair</button><div id="display" style="text-align:center;font-weight:700;letter-spacing:.08em;color:#58a6ff;font-size:14px"></div><div id="msg"></div></form>
524
+ <script>
525
+ // Link từ 'bom-pi pair' mang OFFER trong fragment (#O=<base64url JSON> — khuôn paseo/spin):
526
+ // name + url + code + fp (danh tính daemon) + exp. Fragment không gửi lên server.
527
+ // Đọc một lần rồi xoá khỏi address bar để offer không lisp lại (history/screen-share).
528
+ // #C=<code> vẫn nhận — đường gõ tay khi không quét được.
529
+ (function(){
530
+ const mO=/^#O=([A-Za-z0-9_-]+)$/.exec(location.hash);
531
+ const mC=/^#C=([A-Z2-7]{8})$/i.exec(location.hash);
532
+ let code=null,who='';
533
+ if(mO){
534
+ try{
535
+ const o=JSON.parse(atob(mO[1].replace(/-/g,'+').replace(/_/g,'/')));
536
+ if(o.v===1&&/^[A-Z2-7]{8}$/.test(String(o.code||''))&&/^[0-9A-F]{8}$/.test(String(o.fp||''))){
537
+ code=o.code;who=(o.name||'?')+' · fp '+o.fp;
538
+ window.__bomFp=String(o.fp||''); // pin cùng token khi pair xong (dùng khi bật chữ ký)
539
+ if(o.pub)window.__bomPub=String(o.pub); // daemonPublicKeyB64 (khuôn paseo)
540
+ if(o.exp&&Date.now()>o.exp){document.getElementById('msg').className='err';document.getElementById('msg').textContent='This link expired — run bom-pi pair again.';return;}
541
+ }
542
+ }catch(e){/* offer hỏng — rơi về nhập tay */}
543
+ }else if(mC){code=mC[1].toUpperCase();}
544
+ // Đoán tên thiết bị từ userAgent — offer đã mang code thì không chờ ai gõ gì cả
545
+ function guessName(){
546
+ const u=navigator.userAgent;
547
+ const os=/iPad/.test(u)?'iPad':/iPhone/.test(u)?'iPhone':/Android/.test(u)?'Android':/Windows/.test(u)?'Windows':/Mac/.test(u)?'Mac':'Device';
548
+ const br=/Edg\//.test(u)?'Edge':/CriOS|Chrome\//.test(u)?'Chrome':/FxiOS|Firefox\//.test(u)?'Firefox':/Safari\//.test(u)?'Safari':'Browser';
549
+ return os+' · '+br;
550
+ }
551
+ if(!code)return;
552
+ const ci=document.getElementById('code');
553
+ ci.value=code;
554
+ history.replaceState(null,'',location.pathname);
555
+ const nm=document.getElementById('name');
556
+ if(who){ // offer mang code ⇒ khóa ô code, tự đề xuất tên — chỉ còn bấm Pair
557
+ ci.disabled=true;
558
+ nm.value=guessName();nm.focus();nm.select();
559
+ document.getElementById('who').textContent='Pairing with: '+who+' — match this with bom-pi status';
560
+ document.getElementById('who').style.display='block';
561
+ document.getElementById('hint').textContent='Loaded from link — adjust the name if you like, then Pair.';
562
+ }else{nm.focus();}
563
+ })();
564
+ async function go(){
565
+ const m=document.getElementById('msg');
566
+ m.className='';m.textContent='…';
567
+ try{
568
+ // Chiều 1: gửi code + tên ⇒ enrollment PENDING (chưa có token)
569
+ const r=await fetch('/api/pair/start',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({code:document.getElementById('code').value,name:document.getElementById('name').value})});
570
+ const j=await r.json();
571
+ if(!r.ok)throw new Error(j.error||r.statusText);
572
+ m.className='ok';
573
+ m.textContent='WAITING FOR APPROVAL — on your machine run: bom-pi pair pending';
574
+ const disp=document.getElementById('display');
575
+ disp.textContent='match this code: '+(j.displayId||'?');
576
+ // Chiều 2: poll chờ operator duyệt tại máy
577
+ for(;;){
578
+ await new Promise(s=>setTimeout(s,j.pollAfterMs||1500));
579
+ const pr=await fetch('/api/pair/poll',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({enrollId:j.enrollId})});
580
+ const pj=await pr.json();
581
+ if(pj.status==='approved'){
582
+ localStorage.setItem('bom.device',JSON.stringify({token:pj.deviceToken,deviceId:pj.deviceId,fp:window.__bomFp||null,pub:window.__bomPub||null}));
583
+ m.textContent='Paired — redirecting…';
584
+ // /login set cookie pocket_auth cho UI pocket rồi vào app
585
+ setTimeout(()=>location.href='/login?token='+encodeURIComponent(pj.deviceToken),600);
586
+ return false;
587
+ }
588
+ if(pj.status==='rejected'){m.className='err';m.textContent='Rejected by operator.';return false;}
589
+ if(!pr.ok){m.className='err';m.textContent=pj.error||'expired';return false;}
590
+ }
591
+ }catch(e){m.className='err';m.textContent=e.message;}
592
+ return false;
593
+ }
594
+ </script></body></html>`;
595
+
596
+ // ---- PWA (M8): install màn hình chính + notification approvals ----
597
+ const MANIFEST = {
598
+ name: 'bom', short_name: 'bom', start_url: '/', display: 'standalone',
599
+ background_color: '#101418', theme_color: '#101418',
600
+ icons: [{ src: '/icon.svg', sizes: 'any', type: 'image/svg+xml', purpose: 'any' }],
601
+ };
602
+ const ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><rect width="100" height="100" rx="20" fill="#101418"/><text x="50" y="68" font-size="56" text-anchor="middle" fill="#58a6ff" font-family="monospace" font-weight="bold">b</text></svg>`;
603
+ const SW_JS = `// bom service worker — network-first, không cache (app luôn tươi; SW chỉ để installable PWA)
604
+ self.addEventListener('install', () => self.skipWaiting());
605
+ self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()));
606
+ self.addEventListener('fetch', () => {});`;
607
+
608
+ const http = createHttpServer(async (req, res) => {
609
+ const url = new URL(req.url, 'http://x');
610
+ if (req.method === 'OPTIONS') { res.writeHead(204, CORS); return res.end(); }
611
+ // M8 pairing: /pair UI + start public (code tự vệ) — rồi mới tới cổng auth
612
+ if (req.method === 'GET' && url.pathname === '/pair') {
613
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...CORS });
614
+ return res.end(PAIR_HTML);
615
+ }
616
+ if (req.method === 'POST' && url.pathname === '/api/pair/start') {
617
+ const body = await new Promise((done) => { let b = ''; req.on('data', (c) => (b += c)); req.on('end', () => done(b)); });
618
+ let p; try { p = JSON.parse(body || '{}'); } catch { return json2(res, 400, { error: 'invalid JSON' }); }
619
+ try { return json2(res, 200, await rpc('pair.start', { code: p.code, name: p.name })); }
620
+ catch (e) { return json2(res, 401, { error: e.message.replace(/^\d+: /, '') }); }
621
+ }
622
+ if (req.method === 'POST' && url.pathname === '/api/pair/poll') {
623
+ // device chờ operator duyệt tại máy (2 chiều) — enrollId 32-hex tự vệ + rate-limit daemon
624
+ const body = await new Promise((done) => { let b = ''; req.on('data', (c) => (b += c)); req.on('end', () => done(b)); });
625
+ let p; try { p = JSON.parse(body || '{}'); } catch { return json2(res, 400, { error: 'invalid JSON' }); }
626
+ try { return json2(res, 200, await rpc('pair.poll', { enrollId: p.enrollId })); }
627
+ catch (e) { return json2(res, 404, { error: e.message.replace(/^\d+: /, '') }); }
628
+ }
629
+ if (req.method === 'GET' && url.pathname === '/manifest.webmanifest') {
630
+ res.writeHead(200, { 'content-type': 'application/manifest+json', ...CORS });
631
+ return res.end(JSON.stringify(MANIFEST));
632
+ }
633
+ if (req.method === 'GET' && url.pathname === '/icon.svg') {
634
+ res.writeHead(200, { 'content-type': 'image/svg+xml', ...CORS });
635
+ return res.end(ICON_SVG);
636
+ }
637
+ if (req.method === 'GET' && url.pathname === '/sw.js') {
638
+ res.writeHead(200, { 'content-type': 'application/javascript', ...CORS });
639
+ return res.end(SW_JS);
640
+ }
641
+ // ---- UI pocket (public/): shell + module + vendor tĩnh, KHÔNG cần token ----
642
+ if (req.method === 'GET' && await serveStatic(res, url)) return;
643
+ // ---- /login?token= : sign-in pocket UI bằng device token (sau pair) hoặc master ----
644
+ if (req.method === 'GET' && url.pathname === '/login') {
645
+ const t = url.searchParams.get('token') ?? '';
646
+ const ok = (TOKEN && t === TOKEN) || (await verifyDeviceToken(t));
647
+ if (!ok) { res.writeHead(401, { 'content-type': 'text/html; charset=utf-8' }); return res.end('invalid token — open /pair and enter the code from `bom-pi pair`'); }
648
+ res.writeHead(302, { 'set-cookie': `${COOKIE}=${t}; Path=/; HttpOnly; SameSite=Lax`, location: '/' });
649
+ return res.end();
650
+ }
651
+ // ---- pocket wire: /api/* theo contract pi-pocket — auth bằng cookie pocket_auth ----
652
+ if (url.pathname.startsWith('/api/') && (await pocketCookieOk(req))) {
653
+ if (await pocketRoute(req, res, url)) return;
654
+ } else if (url.pathname.startsWith('/api/') && req.headers['x-pocket'] === '1') {
655
+ res.writeHead(401, { 'content-type': 'application/json', ...CORS });
656
+ return res.end(JSON.stringify({ error: 'unauthorized — sign in at /pair (code from `bom-pi pair`), then /login?token=…' }));
657
+ }
658
+ if (!(await authorized(req, url))) { res.writeHead(401, { 'content-type': 'application/json', ...CORS }); return res.end(JSON.stringify({ error: 'unauthorized — open /pair and enter the code from `bom-pi pair`' })); }
659
+
660
+ if (req.method === 'GET' && url.pathname === '/') {
661
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', ...CORS });
662
+ return res.end(HTML);
663
+ }
664
+ const json = (code, obj) => { res.writeHead(code, { 'content-type': 'application/json', ...CORS }); res.end(JSON.stringify(obj)); };
665
+
666
+ try {
667
+ if (req.method === 'GET' && url.pathname === '/api/hello') return json(200, await rpc('hello'));
668
+ if (req.method === 'GET' && url.pathname === '/api/status') return json(200, await rpc('status'));
669
+ if (req.method === 'GET' && url.pathname === '/api/models') return json(200, await rpc('models.list'));
670
+ if (req.method === 'GET' && url.pathname === '/api/sessions') return json(200, await rpc('session.list'));
671
+ if (req.method === 'GET' && url.pathname === '/api/factories') return json(200, await rpc('factory.list'));
672
+ if (req.method === 'GET' && url.pathname === '/api/metrics') return json(200, await rpc('metrics.summary')); // M6c
673
+ if (req.method === 'GET' && url.pathname === '/api/pages') {
674
+ const factoryId = url.searchParams.get('factoryId') ?? '';
675
+ return json(200, await rpc('pages.list', { factoryId }));
676
+ }
677
+ if (req.method === 'GET' && url.pathname === '/api/pages/get') {
678
+ const factoryId = url.searchParams.get('factoryId') ?? '';
679
+ const name = url.searchParams.get('name') ?? '';
680
+ return json(200, await rpc('pages.get', { factoryId, name }));
681
+ }
682
+ if (req.method === 'POST' && url.pathname === '/api/session/new') {
683
+ const body = await new Promise((done) => { let b = ''; req.on('data', (c) => (b += c)); req.on('end', () => done(b)); });
684
+ let p = {}; try { p = JSON.parse(body || '{}'); } catch {}
685
+ const params = {};
686
+ if (typeof p.model === 'string' && p.model.includes('/')) { const [provider, modelId] = p.model.split('/'); params.model = { provider, modelId }; }
687
+ if (typeof p.cwd === 'string' && p.cwd.trim()) params.cwd = p.cwd.trim();
688
+ return json(200, await rpc('session.new', params));
689
+ }
690
+ if (req.method === 'POST' && url.pathname === '/api/session/switch') {
691
+ const body = await new Promise((done) => { let b = ''; req.on('data', (c) => (b += c)); req.on('end', () => done(b)); });
692
+ let p = {}; try { p = JSON.parse(body || '{}'); } catch {}
693
+ if (!Number.isInteger(p.id)) return json(400, { error: 'id (number) required' });
694
+ return json(200, await rpc('session.switch', { id: p.id }));
695
+ }
696
+ if (req.method === 'GET' && url.pathname === '/api/transcript') {
697
+ const cid = Number(url.searchParams.get('cid'));
698
+ return json(200, await rpc('transcript.get', { limit: 100, ...(Number.isInteger(cid) ? { conversationId: cid } : {}) }));
699
+ }
700
+
701
+ if (req.method === 'GET' && url.pathname === '/api/events') {
702
+ // SSE: 1 socket bom-core cho mỗi browser — subscribe rồi forward notification
703
+ const conn = await rpcConn();
704
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', connection: 'keep-alive', ...CORS });
705
+ res.write('retry: 3000\n\n');
706
+ let buf = '';
707
+ conn.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'events.subscribe', params: (() => { const c = Number(url.searchParams.get('cid')); return Number.isInteger(c) ? { conversationId: c } : {}; })() }) + '\n');
708
+ conn.on('data', (c) => {
709
+ buf += c.toString('utf8');
710
+ let nl;
711
+ while ((nl = buf.indexOf('\n')) >= 0) {
712
+ const line = buf.slice(0, nl).trim();
713
+ buf = buf.slice(nl + 1);
714
+ if (!line) continue;
715
+ let msg; try { msg = JSON.parse(line); } catch { continue; }
716
+ if (msg.id === 1 && msg.result) {
717
+ res.write(`event: update\ndata: ${JSON.stringify({ entries: msg.result.snapshot })}\n\n`);
718
+ } else if (msg.method === 'events.update') {
719
+ res.write(`event: update\ndata: ${JSON.stringify({ seq: msg.params.seq, entries: msg.params.entries })}\n\n`);
720
+ } else if (msg.method === 'events.heartbeat') {
721
+ res.write(`event: heartbeat\ndata: ${JSON.stringify(msg.params)}\n\n`);
722
+ }
723
+ }
724
+ });
725
+ const drop = () => { try { conn.destroy(); } catch {} };
726
+ req.on('close', drop);
727
+ conn.on('error', drop);
728
+ return;
729
+ }
730
+
731
+ if (req.method === 'POST' && url.pathname === '/api/reset') {
732
+ const body = await new Promise((done) => { let b = ''; req.on('data', (c) => (b += c)); req.on('end', () => done(b)); });
733
+ let p = {}; try { p = JSON.parse(body || '{}'); } catch {}
734
+ return json(200, await rpc('session.reset', typeof p.handoff === 'string' && p.handoff.trim() ? { handoff: p.handoff.trim() } : {}));
735
+ }
736
+
737
+ if (req.method === 'GET' && url.pathname === '/api/approvals') return json(200, await rpc('approvals.list'));
738
+ if (req.method === 'POST' && url.pathname === '/api/approvals/answer') {
739
+ const body = await new Promise((done) => { let b = ''; req.on('data', (c) => (b += c)); req.on('end', () => done(b)); });
740
+ let p = {}; try { p = JSON.parse(body || '{}'); } catch {}
741
+ if (typeof p.id !== 'string' || !p.id) return json(400, { error: 'id required' });
742
+ return json(200, await rpc('approvals.answer', { id: p.id, allow: p.allow === true, by: 'web' }));
743
+ }
744
+
745
+ // M5d (spec §5.3): webhook — POST /api/hook/:factoryId (body = text, ?id= cho idempotent).
746
+ // Mở đường cron ngoài / CI / phone shortcut kích agent — cross-host qua tailscale.
747
+ if (req.method === 'POST' && url.pathname.startsWith('/api/hook/')) {
748
+ const factoryId = decodeURIComponent(url.pathname.slice('/api/hook/'.length));
749
+ const body = await new Promise((done) => { let b = ''; req.on('data', (c) => (b += c)); req.on('end', () => done(b)); });
750
+ const id = url.searchParams.get('id') ?? undefined;
751
+ return json(200, await rpc('factory.hook', { factoryId, body, ...(id ? { id } : {}) }));
752
+ }
753
+
754
+ if (req.method === 'POST' && url.pathname === '/api/submit') {
755
+ const body = await new Promise((done) => { let b = ''; req.on('data', (c) => (b += c)); req.on('end', () => done(b)); });
756
+ let p; try { p = JSON.parse(body || '{}'); } catch { return json(400, { error: 'invalid JSON' }); }
757
+ if (typeof p.text !== 'string' || !p.text.trim()) return json(400, { error: 'text required' });
758
+ const params = { text: p.text, requestId: `web-${Date.now()}` };
759
+ if (p.model && typeof p.model === 'string' && p.model.includes('/')) {
760
+ const [provider, modelId] = p.model.split('/');
761
+ params.model = { provider, modelId };
762
+ }
763
+ return json(200, await rpc('session.submit', params));
764
+ }
765
+
766
+ return json(404, { error: 'not found' });
767
+ } catch (e) {
768
+ return json(502, { error: e.message });
769
+ }
770
+ });
771
+
772
+ http.listen(PORT, LISTEN, () => {
773
+ console.error(`bom-web listening http://${LISTEN}:${PORT} — bom-core at ${socketPath}${TOKEN ? ' — token required' : ' — NO TOKEN (loopback only)'}`);
774
+ });