truemap-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/bin/truemap.js +7 -0
- package/kit/truemap.css +230 -0
- package/package.json +39 -4
- package/skills/truemap/SKILL.md +22 -0
- package/src/check.js +248 -0
- package/src/cli.js +361 -0
- package/src/common.js +99 -0
- package/src/guide.md +121 -0
- package/src/server.js +394 -0
- package/src/ui/sdk.js +141 -0
- package/src/ui/workspace.css +158 -0
- package/src/ui/workspace.html +73 -0
- package/src/ui/workspace.js +339 -0
package/src/server.js
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
// The local truemap server: one per repo, started on demand by the CLI, invisible to the user.
|
|
2
|
+
// Serves the workspace UI, the .truemap pages (with the SDK injected), a chat queue between
|
|
3
|
+
// the browser and the agent's CLI (listen/reply), and live updates over Server-Sent Events.
|
|
4
|
+
import { createServer } from 'node:http';
|
|
5
|
+
import { randomBytes } from 'node:crypto';
|
|
6
|
+
import { existsSync, lstatSync, readFileSync, realpathSync, rmSync, statSync, watch } from 'node:fs';
|
|
7
|
+
import { extname, join, resolve, sep } from 'node:path';
|
|
8
|
+
import { FOLDER, PKG_DIR, VERSION, appendPrivate, historyPath, serverStatePath, writePrivate } from './common.js';
|
|
9
|
+
import { checkAll, listPages } from './check.js';
|
|
10
|
+
|
|
11
|
+
const root = resolve(process.argv[2] || process.cwd());
|
|
12
|
+
const folder = join(root, FOLDER);
|
|
13
|
+
const token = randomBytes(18).toString('base64url');
|
|
14
|
+
const statePath = serverStatePath(root);
|
|
15
|
+
const IDLE_MS = Number(process.env.TRUEMAP_IDLE_MS || 30 * 60 * 1000);
|
|
16
|
+
const CLOSE_GRACE_MS = Number(process.env.TRUEMAP_CLOSE_GRACE_MS || 10_000);
|
|
17
|
+
const UI_DIR = join(PKG_DIR, 'src', 'ui');
|
|
18
|
+
|
|
19
|
+
const MIME = {
|
|
20
|
+
'.html': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8',
|
|
21
|
+
'.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8',
|
|
22
|
+
'.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
|
|
23
|
+
'.webp': 'image/webp', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.woff': 'font/woff', '.txt': 'text/plain; charset=utf-8',
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
// ---------- state ----------
|
|
27
|
+
const clients = new Set(); // SSE responses (browser tabs)
|
|
28
|
+
const queue = []; // messages waiting for the agent
|
|
29
|
+
let listener = null; // { res, timer } – the single active `listen`
|
|
30
|
+
let agentState = 'offline'; // listening | working | offline
|
|
31
|
+
let lastAgentActivity = 0;
|
|
32
|
+
let currentPage = null;
|
|
33
|
+
let closeTimer = null;
|
|
34
|
+
let idleTimer = null;
|
|
35
|
+
let seq = 0;
|
|
36
|
+
let lastCheck = { gitRepo: false, results: [] };
|
|
37
|
+
const history = loadHistory();
|
|
38
|
+
|
|
39
|
+
function loadHistory() {
|
|
40
|
+
try {
|
|
41
|
+
return readFileSync(historyPath(root), 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)).slice(-200);
|
|
42
|
+
} catch { return []; }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function remember(entry) {
|
|
46
|
+
history.push(entry);
|
|
47
|
+
if (history.length > 200) history.shift();
|
|
48
|
+
try { appendPrivate(historyPath(root), JSON.stringify(entry) + '\n'); } catch { /* ignore */ }
|
|
49
|
+
broadcast({ type: 'chat', entry });
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function broadcast(event) {
|
|
53
|
+
const data = `data: ${JSON.stringify(event)}\n\n`;
|
|
54
|
+
for (const res of clients) res.write(data);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function setAgentState(s) {
|
|
58
|
+
if (agentState === s) return;
|
|
59
|
+
agentState = s;
|
|
60
|
+
broadcast({ type: 'agent', state: s });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function touchIdle() {
|
|
64
|
+
clearTimeout(idleTimer);
|
|
65
|
+
idleTimer = setTimeout(() => {
|
|
66
|
+
if (clients.size === 0 && !listener && queue.length === 0) shutdown();
|
|
67
|
+
else touchIdle();
|
|
68
|
+
}, IDLE_MS);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function shutdown() {
|
|
72
|
+
try {
|
|
73
|
+
const s = JSON.parse(readFileSync(statePath, 'utf8'));
|
|
74
|
+
if (s.pid === process.pid) rmSync(statePath, { force: true });
|
|
75
|
+
} catch { /* ignore */ }
|
|
76
|
+
process.exit(0);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ---------- listen / reply ----------
|
|
80
|
+
function finishListen(body) {
|
|
81
|
+
if (!listener) return;
|
|
82
|
+
const { res, timer } = listener;
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
listener = null;
|
|
85
|
+
sendJson(res, 200, body);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function deliverQueue() {
|
|
89
|
+
if (listener && (listener.res.destroyed || listener.res.writableEnded)) { clearTimeout(listener.timer); listener = null; setAgentState('offline'); }
|
|
90
|
+
if (!listener || queue.length === 0) return;
|
|
91
|
+
const messages = queue.splice(0, queue.length);
|
|
92
|
+
setAgentState('working');
|
|
93
|
+
lastAgentActivity = Date.now();
|
|
94
|
+
broadcast({ type: 'delivered', ids: messages.map((m) => m.id) });
|
|
95
|
+
finishListen({ status: 'message', messages });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function scheduleCloseCheck() {
|
|
99
|
+
clearTimeout(closeTimer);
|
|
100
|
+
if (!listener || clients.size > 0) return;
|
|
101
|
+
closeTimer = setTimeout(() => {
|
|
102
|
+
if (listener && clients.size === 0 && queue.length === 0) {
|
|
103
|
+
finishListen({ status: 'browser_closed' });
|
|
104
|
+
setAgentState('offline');
|
|
105
|
+
}
|
|
106
|
+
}, CLOSE_GRACE_MS);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ---------- checks & file watching ----------
|
|
110
|
+
function runChecks() {
|
|
111
|
+
try { lastCheck = checkAll(root); } catch { lastCheck = { gitRepo: false, results: [] }; }
|
|
112
|
+
broadcast({ type: 'check', check: lastCheck });
|
|
113
|
+
return lastCheck;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Checks shell out to git, which can take a moment: never make a request wait for them.
|
|
117
|
+
let checkQueued = false;
|
|
118
|
+
function scheduleChecks() {
|
|
119
|
+
if (checkQueued) return;
|
|
120
|
+
checkQueued = true;
|
|
121
|
+
setTimeout(() => { checkQueued = false; runChecks(); }, 30);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
let watchTimer = null;
|
|
125
|
+
const changedPages = new Set();
|
|
126
|
+
function startWatching() {
|
|
127
|
+
const onChange = (file) => {
|
|
128
|
+
if (file) changedPages.add(String(file).split(sep).join('/'));
|
|
129
|
+
clearTimeout(watchTimer);
|
|
130
|
+
watchTimer = setTimeout(() => {
|
|
131
|
+
const files = [...changedPages];
|
|
132
|
+
changedPages.clear();
|
|
133
|
+
broadcast({ type: 'pages', pages: safePages() });
|
|
134
|
+
broadcast({ type: 'changed', files });
|
|
135
|
+
scheduleChecks();
|
|
136
|
+
}, 150);
|
|
137
|
+
};
|
|
138
|
+
try {
|
|
139
|
+
const w = watch(folder, { recursive: true }, (_e, f) => onChange(f));
|
|
140
|
+
w.on('error', () => { try { w.close(); } catch { /* ignore */ } setTimeout(startWatching, 2000); });
|
|
141
|
+
} catch { setTimeout(startWatching, 5000); }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function safePages() {
|
|
145
|
+
try { return listPages(root); } catch { return []; }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ---------- http helpers ----------
|
|
149
|
+
function sendJson(res, status, body) {
|
|
150
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
151
|
+
res.end(JSON.stringify(body));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function sendText(res, status, text) {
|
|
155
|
+
res.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
156
|
+
res.end(text);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function readBody(req, limit = 2 * 1024 * 1024) {
|
|
160
|
+
return new Promise((ok, fail) => {
|
|
161
|
+
let size = 0;
|
|
162
|
+
const chunks = [];
|
|
163
|
+
req.on('data', (c) => { size += c.length; if (size > limit) { fail(new Error('too large')); req.destroy(); } else chunks.push(c); });
|
|
164
|
+
req.on('end', () => {
|
|
165
|
+
try { ok(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); } catch (e) { fail(e); }
|
|
166
|
+
});
|
|
167
|
+
req.on('error', fail);
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
let port = 0; // workspace + API
|
|
172
|
+
let contentPort = 0; // pages only: a separate origin, so page scripts can never reach the API
|
|
173
|
+
function hostAllowed(req, p = port) {
|
|
174
|
+
const host = (req.headers.host || '').toLowerCase();
|
|
175
|
+
return [`127.0.0.1:${p}`, `localhost:${p}`, `[::1]:${p}`].includes(host);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function originAllowed(req) {
|
|
179
|
+
const origin = req.headers.origin;
|
|
180
|
+
if (!origin) return true; // CLI requests carry no Origin
|
|
181
|
+
return [`http://127.0.0.1:${port}`, `http://localhost:${port}`, `http://[::1]:${port}`].includes(origin.toLowerCase());
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function tokenOk(req, url) {
|
|
185
|
+
return req.headers['x-truemap-token'] === token || url.searchParams.get('t') === token;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Resolves a request path inside a base dir; refuses traversal and symlinks leading outside. */
|
|
189
|
+
function folderIsSafe() {
|
|
190
|
+
try { return !lstatSync(folder).isSymbolicLink(); } catch { return false; }
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function safeFile(base, relPath) {
|
|
194
|
+
let decoded;
|
|
195
|
+
try { decoded = decodeURIComponent(relPath); } catch { return null; }
|
|
196
|
+
if (decoded.includes('\0')) return null;
|
|
197
|
+
const full = resolve(base, '.' + sep + decoded.replace(/\//g, sep));
|
|
198
|
+
if (full !== base && !full.startsWith(base + sep)) return null;
|
|
199
|
+
if (!existsSync(full)) return null;
|
|
200
|
+
try {
|
|
201
|
+
const real = realpathSync(full);
|
|
202
|
+
const realBase = realpathSync(base);
|
|
203
|
+
if (real !== realBase && !real.startsWith(realBase + sep)) return null;
|
|
204
|
+
if (statSync(real).isDirectory()) return null;
|
|
205
|
+
return real;
|
|
206
|
+
} catch { return null; }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function servePage(res, file) {
|
|
210
|
+
const type = MIME[extname(file).toLowerCase()] || 'application/octet-stream';
|
|
211
|
+
let body = readFileSync(file);
|
|
212
|
+
if (type.startsWith('text/html')) {
|
|
213
|
+
const inject = `<script src="/__truemap/sdk.js"></script>`;
|
|
214
|
+
let html = body.toString('utf8');
|
|
215
|
+
html = /<\/body>/i.test(html) ? html.replace(/<\/body>(?![\s\S]*<\/body>)/i, `${inject}</body>`) : html + inject;
|
|
216
|
+
body = Buffer.from(html, 'utf8');
|
|
217
|
+
}
|
|
218
|
+
res.writeHead(200, {
|
|
219
|
+
'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',
|
|
220
|
+
// Only the truemap workspace may frame these pages.
|
|
221
|
+
'Content-Security-Policy': `frame-ancestors http://127.0.0.1:${port}`,
|
|
222
|
+
});
|
|
223
|
+
res.end(body);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function serveUi(res, name) {
|
|
227
|
+
const file = safeFile(UI_DIR, name);
|
|
228
|
+
if (!file) return sendText(res, 404, 'not found');
|
|
229
|
+
const type = MIME[extname(file).toLowerCase()] || 'application/octet-stream';
|
|
230
|
+
res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-store' });
|
|
231
|
+
res.end(readFileSync(file));
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// ---------- routes ----------
|
|
235
|
+
const server = createServer(async (req, res) => {
|
|
236
|
+
if (!hostAllowed(req)) return sendText(res, 403, 'forbidden host');
|
|
237
|
+
const url = new URL(req.url, `http://127.0.0.1:${port}`);
|
|
238
|
+
const p = url.pathname;
|
|
239
|
+
touchIdle();
|
|
240
|
+
|
|
241
|
+
try {
|
|
242
|
+
// Workspace shell (token required so other local pages can't embed a live session).
|
|
243
|
+
if (p === '/' && req.method === 'GET') {
|
|
244
|
+
if (!tokenOk(req, url)) return sendText(res, 403, 'missing token – open the link printed by `truemap`');
|
|
245
|
+
const html = readFileSync(join(UI_DIR, 'workspace.html'), 'utf8')
|
|
246
|
+
.replace('__TRUEMAP_TOKEN__', token)
|
|
247
|
+
.replace('__TRUEMAP_CONTENT__', `http://127.0.0.1:${contentPort}`);
|
|
248
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' });
|
|
249
|
+
return res.end(html);
|
|
250
|
+
}
|
|
251
|
+
if (p.startsWith('/__truemap/') && req.method === 'GET') return serveUi(res, p.slice('/__truemap/'.length));
|
|
252
|
+
if (!p.startsWith('/api/')) return sendText(res, 404, 'not found');
|
|
253
|
+
if (!originAllowed(req) || !tokenOk(req, url)) return sendText(res, 403, 'forbidden');
|
|
254
|
+
|
|
255
|
+
// ----- browser side -----
|
|
256
|
+
if (p === '/api/events' && req.method === 'GET') {
|
|
257
|
+
scheduleChecks();
|
|
258
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' });
|
|
259
|
+
res.write(`data: ${JSON.stringify({
|
|
260
|
+
type: 'hello', version: VERSION, root, agent: agentState, pages: safePages(), check: lastCheck,
|
|
261
|
+
history, current: currentPage, pending: queue.map((m) => m.id),
|
|
262
|
+
})}\n\n`);
|
|
263
|
+
clients.add(res);
|
|
264
|
+
clearTimeout(closeTimer);
|
|
265
|
+
const ping = setInterval(() => res.write(': ping\n\n'), 20_000);
|
|
266
|
+
req.on('close', () => { clearInterval(ping); clients.delete(res); scheduleCloseCheck(); touchIdle(); });
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
if (p === '/api/send' && req.method === 'POST') {
|
|
270
|
+
const b = await readBody(req);
|
|
271
|
+
const text = String(b.text ?? '').slice(0, 20_000);
|
|
272
|
+
const context = Array.isArray(b.context) ? b.context.slice(0, 12) : [];
|
|
273
|
+
const answer = b.kind === 'answer' && b.answer && typeof b.answer === 'object'
|
|
274
|
+
? { question: String(b.answer.question ?? '').slice(0, 500), choice: String(b.answer.choice ?? '').slice(0, 2000), note: String(b.answer.note ?? '').slice(0, 4000) }
|
|
275
|
+
: null;
|
|
276
|
+
if (!text.trim() && context.length === 0 && !answer) return sendJson(res, 400, { error: 'empty' });
|
|
277
|
+
const msg = {
|
|
278
|
+
id: `m${Date.now().toString(36)}${(seq++).toString(36)}`,
|
|
279
|
+
at: new Date().toISOString(),
|
|
280
|
+
kind: answer ? 'answer' : 'message',
|
|
281
|
+
from: b.from === 'page' ? 'page' : 'user',
|
|
282
|
+
page: typeof b.page === 'string' ? b.page : currentPage,
|
|
283
|
+
text,
|
|
284
|
+
context,
|
|
285
|
+
...(answer ? { answer } : {}),
|
|
286
|
+
};
|
|
287
|
+
queue.push(msg);
|
|
288
|
+
remember({ role: 'user', ...msg });
|
|
289
|
+
deliverQueue();
|
|
290
|
+
return sendJson(res, 200, { ok: true, id: msg.id, delivered: !queue.includes(msg) });
|
|
291
|
+
}
|
|
292
|
+
if (p === '/api/viewing' && req.method === 'POST') {
|
|
293
|
+
const b = await readBody(req);
|
|
294
|
+
currentPage = typeof b.page === 'string' ? b.page : currentPage;
|
|
295
|
+
scheduleChecks();
|
|
296
|
+
return sendJson(res, 200, { ok: true });
|
|
297
|
+
}
|
|
298
|
+
if (p === '/api/check' && req.method === 'POST') return sendJson(res, 200, runChecks());
|
|
299
|
+
|
|
300
|
+
// ----- agent (CLI) side -----
|
|
301
|
+
if (p === '/api/agent/status' && req.method === 'GET') {
|
|
302
|
+
return sendJson(res, 200, { version: VERSION, pid: process.pid, root, clients: clients.size, agent: agentState, queued: queue.length, current: currentPage });
|
|
303
|
+
}
|
|
304
|
+
if (p === '/api/agent/listen' && req.method === 'POST') {
|
|
305
|
+
const b = await readBody(req);
|
|
306
|
+
if (listener) finishListen({ status: 'replaced' });
|
|
307
|
+
lastAgentActivity = Date.now();
|
|
308
|
+
const timeoutMs = Number(b.timeoutMs) > 0 ? Number(b.timeoutMs) : 0;
|
|
309
|
+
const timer = timeoutMs ? setTimeout(() => { finishListen({ status: 'timeout' }); setAgentState('offline'); }, timeoutMs) : null;
|
|
310
|
+
listener = { res, timer };
|
|
311
|
+
// The request body is already consumed, so watch the response: it closes when the CLI goes away.
|
|
312
|
+
res.on('close', () => {
|
|
313
|
+
if (listener && listener.res === res) { clearTimeout(listener.timer); listener = null; setAgentState('offline'); }
|
|
314
|
+
});
|
|
315
|
+
if (queue.length) return deliverQueue();
|
|
316
|
+
setAgentState('listening');
|
|
317
|
+
if (clients.size === 0) scheduleCloseCheck();
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
if (p === '/api/agent/reply' && req.method === 'POST') {
|
|
321
|
+
const b = await readBody(req);
|
|
322
|
+
const text = String(b.text ?? '').slice(0, 100_000);
|
|
323
|
+
if (!text.trim()) return sendJson(res, 400, { error: 'empty reply' });
|
|
324
|
+
lastAgentActivity = Date.now();
|
|
325
|
+
remember({ role: 'agent', id: `a${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), text });
|
|
326
|
+
if (!listener) setAgentState(b.keepWorking ? 'working' : 'offline');
|
|
327
|
+
return sendJson(res, 200, { ok: true, browsers: clients.size });
|
|
328
|
+
}
|
|
329
|
+
if (p === '/api/agent/navigate' && req.method === 'POST') {
|
|
330
|
+
const b = await readBody(req);
|
|
331
|
+
const page = String(b.page ?? '');
|
|
332
|
+
broadcast({ type: 'navigate', page, pages: safePages() });
|
|
333
|
+
scheduleChecks();
|
|
334
|
+
return sendJson(res, 200, { ok: true, browsers: clients.size });
|
|
335
|
+
}
|
|
336
|
+
if (p === '/api/agent/progress' && req.method === 'POST') {
|
|
337
|
+
const b = await readBody(req);
|
|
338
|
+
broadcast({ type: 'progress', text: String(b.text ?? '').slice(0, 300) });
|
|
339
|
+
return sendJson(res, 200, { ok: true });
|
|
340
|
+
}
|
|
341
|
+
if (p === '/api/agent/shutdown' && req.method === 'POST') {
|
|
342
|
+
sendJson(res, 200, { ok: true });
|
|
343
|
+
setTimeout(shutdown, 50);
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
return sendText(res, 404, 'not found');
|
|
347
|
+
} catch (e) {
|
|
348
|
+
if (!res.headersSent) sendJson(res, 500, { error: String(e?.message || e) });
|
|
349
|
+
}
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
// Content origin: serves .truemap pages (with the SDK injected) and nothing else.
|
|
353
|
+
const content = createServer((req, res) => {
|
|
354
|
+
if (!hostAllowed(req, contentPort)) return sendText(res, 403, 'forbidden host');
|
|
355
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return sendText(res, 405, 'method not allowed');
|
|
356
|
+
const p = new URL(req.url, `http://127.0.0.1:${contentPort}`).pathname;
|
|
357
|
+
try {
|
|
358
|
+
if (p === '/__truemap/sdk.js') {
|
|
359
|
+
const js = readFileSync(join(UI_DIR, 'sdk.js'), 'utf8').replace('__TRUEMAP_PARENT__', `http://127.0.0.1:${port}`);
|
|
360
|
+
res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
361
|
+
return res.end(js);
|
|
362
|
+
}
|
|
363
|
+
if (p.startsWith('/pages/')) {
|
|
364
|
+
const file = folderIsSafe() ? safeFile(folder, p.slice('/pages/'.length)) : null;
|
|
365
|
+
if (!file) return sendText(res, 404, 'page not found');
|
|
366
|
+
return servePage(res, file);
|
|
367
|
+
}
|
|
368
|
+
return sendText(res, 404, 'not found');
|
|
369
|
+
} catch (e) {
|
|
370
|
+
if (!res.headersSent) sendText(res, 500, String(e?.message || e));
|
|
371
|
+
}
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
server.listen(Number(process.env.TRUEMAP_PORT || 0), '127.0.0.1', () => {
|
|
375
|
+
port = server.address().port;
|
|
376
|
+
content.listen(0, '127.0.0.1', () => {
|
|
377
|
+
contentPort = content.address().port;
|
|
378
|
+
writePrivate(statePath, JSON.stringify({ pid: process.pid, port, contentPort, token, version: VERSION, root, startedAt: new Date().toISOString() }));
|
|
379
|
+
startWatching();
|
|
380
|
+
scheduleChecks();
|
|
381
|
+
touchIdle();
|
|
382
|
+
});
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
// Code changes outside .truemap aren't watched (too noisy); re-check while someone is looking.
|
|
386
|
+
setInterval(() => { if (clients.size > 0) scheduleChecks(); }, 30_000).unref();
|
|
387
|
+
|
|
388
|
+
// Mark the agent offline if it hasn't listened or replied in a long while.
|
|
389
|
+
setInterval(() => {
|
|
390
|
+
if (!listener && agentState === 'working' && Date.now() - lastAgentActivity > 20 * 60 * 1000) setAgentState('offline');
|
|
391
|
+
}, 60_000).unref();
|
|
392
|
+
|
|
393
|
+
process.on('SIGTERM', shutdown);
|
|
394
|
+
process.on('SIGINT', shutdown);
|
package/src/ui/sdk.js
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Injected into every .truemap page by the local server (never saved into the page file).
|
|
2
|
+
// Runs inside a sandboxed iframe: click/select = context for the chat, decision forms = answers,
|
|
3
|
+
// and shows check marks on elements whose data-src no longer matches the code.
|
|
4
|
+
(() => {
|
|
5
|
+
if (window.__truemapSdk) return;
|
|
6
|
+
window.__truemapSdk = true;
|
|
7
|
+
const parentWin = window.parent;
|
|
8
|
+
if (!parentWin || parentWin === window) return;
|
|
9
|
+
const PARENT = '__TRUEMAP_PARENT__';
|
|
10
|
+
const post = (msg) => parentWin.postMessage({ __truemap: true, ...msg }, PARENT);
|
|
11
|
+
const T = { sent: 'Sent ✓', changed: 'Code changed after this page was written', broken: 'The code this points to is gone' };
|
|
12
|
+
|
|
13
|
+
const style = document.createElement('style');
|
|
14
|
+
style.textContent = `
|
|
15
|
+
[data-src] { cursor: pointer; }
|
|
16
|
+
[data-src]:hover { outline: 1.5px solid color-mix(in oklab, #2c5a8c 45%, transparent); outline-offset: 3px; }
|
|
17
|
+
[data-tm-selected] { outline: 2px solid #2c5a8c !important; outline-offset: 3px; border-radius: 4px; }
|
|
18
|
+
svg [data-tm-selected] { outline: none !important; filter: drop-shadow(0 0 3px #2c5a8c) drop-shadow(0 0 1px #2c5a8c); }
|
|
19
|
+
[data-tm-mark="changed"] { outline: 2px dashed #9c6c12 !important; outline-offset: 3px; }
|
|
20
|
+
[data-tm-mark="broken"] { outline: 2px dashed #a23b2c !important; outline-offset: 3px; }
|
|
21
|
+
svg [data-tm-mark="changed"] { outline: none !important; filter: drop-shadow(0 0 3px #9c6c12); }
|
|
22
|
+
svg [data-tm-mark="broken"] { outline: none !important; filter: drop-shadow(0 0 3px #a23b2c); }
|
|
23
|
+
@keyframes tm-flash { 0%,100% { outline-color: transparent } 30% { outline-color: #2c5a8c } }
|
|
24
|
+
[data-tm-flash] { outline: 3px solid #2c5a8c; outline-offset: 4px; animation: tm-flash 1.2s ease 2; }
|
|
25
|
+
`;
|
|
26
|
+
(document.head || document.documentElement).appendChild(style);
|
|
27
|
+
|
|
28
|
+
const pagePath = () => decodeURIComponent(location.pathname.replace(/^\/pages\//, ''));
|
|
29
|
+
const clean = (s, n) => String(s || '').replace(/\s+/g, ' ').trim().slice(0, n);
|
|
30
|
+
const INTERACTIVE = 'a[href],button,input,select,textarea,label,summary,[contenteditable],[role=button],[data-tm-action]';
|
|
31
|
+
|
|
32
|
+
function labelOf(el) {
|
|
33
|
+
return clean(el.getAttribute('data-label') || el.getAttribute('aria-label') || el.getAttribute('title')
|
|
34
|
+
|| el.querySelector?.('.tm-node-title,h1,h2,h3,h4,strong,b')?.textContent || el.textContent, 60) || el.tagName.toLowerCase();
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function pickTarget(t) {
|
|
38
|
+
const anchored = t.closest('[data-src]');
|
|
39
|
+
if (anchored) return anchored;
|
|
40
|
+
const block = t.closest('h1,h2,h3,h4,h5,h6,p,li,td,th,figure,pre,blockquote,.tm-card,.tm-node,.tm-step,.tm-callout,.tm-ask,section,article');
|
|
41
|
+
if (block && block !== document.body) return block;
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
let selected = [];
|
|
46
|
+
function setSelected(list) {
|
|
47
|
+
for (const el of selected) el.removeAttribute('data-tm-selected');
|
|
48
|
+
selected = list;
|
|
49
|
+
for (const el of selected) el.setAttribute('data-tm-selected', '');
|
|
50
|
+
post({
|
|
51
|
+
type: 'select',
|
|
52
|
+
page: pagePath(),
|
|
53
|
+
items: selected.map((el) => ({
|
|
54
|
+
kind: 'element', label: labelOf(el), src: el.closest('[data-src]')?.getAttribute('data-src') || '',
|
|
55
|
+
excerpt: clean(el.innerText || el.textContent, 400),
|
|
56
|
+
})),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
document.addEventListener('click', (e) => {
|
|
61
|
+
if (!e.isTrusted) return;
|
|
62
|
+
const t = e.target instanceof Element ? e.target : null;
|
|
63
|
+
if (!t || t.closest(INTERACTIVE)) return;
|
|
64
|
+
if (String(window.getSelection?.() || '').trim().length > 1) return; // text selection handled on mouseup
|
|
65
|
+
const el = pickTarget(t);
|
|
66
|
+
if (!el) { if (!e.ctrlKey && !e.metaKey) setSelected([]); return; }
|
|
67
|
+
if (e.ctrlKey || e.metaKey) {
|
|
68
|
+
setSelected(selected.includes(el) ? selected.filter((x) => x !== el) : [...selected, el]);
|
|
69
|
+
} else {
|
|
70
|
+
setSelected(selected.length === 1 && selected[0] === el ? [] : [el]);
|
|
71
|
+
}
|
|
72
|
+
}, true);
|
|
73
|
+
|
|
74
|
+
document.addEventListener('mouseup', (e) => {
|
|
75
|
+
if (!e.isTrusted) return;
|
|
76
|
+
setTimeout(() => {
|
|
77
|
+
const sel = window.getSelection?.();
|
|
78
|
+
const text = clean(sel?.toString(), 600);
|
|
79
|
+
if (!text || text.length < 2) return;
|
|
80
|
+
const node = sel.anchorNode?.nodeType === 1 ? sel.anchorNode : sel.anchorNode?.parentElement;
|
|
81
|
+
post({ type: 'select-text', page: pagePath(), item: { kind: 'text', label: clean(text, 60), src: node?.closest?.('[data-src]')?.getAttribute('data-src') || '', excerpt: text } });
|
|
82
|
+
}, 0);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
// Decision forms: <form class="tm-ask" data-tm-ask="question"> … <button type="submit">
|
|
86
|
+
document.addEventListener('submit', (e) => {
|
|
87
|
+
const form = e.target;
|
|
88
|
+
if (!(form instanceof HTMLFormElement) || !form.hasAttribute('data-tm-ask')) return;
|
|
89
|
+
e.preventDefault();
|
|
90
|
+
const fd = new FormData(form);
|
|
91
|
+
const values = {};
|
|
92
|
+
let note = '';
|
|
93
|
+
for (const [k, v] of fd.entries()) {
|
|
94
|
+
if (typeof v !== 'string') continue;
|
|
95
|
+
if (k === 'note') { note = v.trim(); continue; }
|
|
96
|
+
(values[k] ||= []).push(v);
|
|
97
|
+
}
|
|
98
|
+
const question = form.getAttribute('data-tm-ask') || clean(form.querySelector('h3,legend,h2,h4')?.textContent, 200);
|
|
99
|
+
const choice = Object.values(values).flat().join(', ');
|
|
100
|
+
if (!choice && !note) return;
|
|
101
|
+
form.setAttribute('data-tm-sent', '');
|
|
102
|
+
const btn = form.querySelector('button[type=submit],button:not([type])');
|
|
103
|
+
if (btn && !btn.dataset.tmLabel) { btn.dataset.tmLabel = btn.textContent; }
|
|
104
|
+
if (btn) btn.textContent = T.sent;
|
|
105
|
+
post({ type: 'answer', page: pagePath(), trusted: e.isTrusted, question, choice, note, src: form.closest('[data-src]')?.getAttribute('data-src') || '' });
|
|
106
|
+
}, true);
|
|
107
|
+
|
|
108
|
+
// Pages may also talk to the agent directly (marked as coming from the page, not the user).
|
|
109
|
+
window.truemap = { send: (text) => post({ type: 'page-send', page: pagePath(), text: clean(text, 4000) }) };
|
|
110
|
+
|
|
111
|
+
window.addEventListener('message', (e) => {
|
|
112
|
+
if (e.source !== parentWin || e.origin !== PARENT || !e.data || !e.data.__truemap) return;
|
|
113
|
+
const d = e.data;
|
|
114
|
+
if (d.type === 'marks') {
|
|
115
|
+
document.querySelectorAll('[data-tm-mark]').forEach((el) => { el.removeAttribute('data-tm-mark'); });
|
|
116
|
+
for (const m of d.items || []) {
|
|
117
|
+
document.querySelectorAll('[data-src]').forEach((el) => {
|
|
118
|
+
if (el.getAttribute('data-src') !== m.src) return;
|
|
119
|
+
el.setAttribute('data-tm-mark', m.state);
|
|
120
|
+
if (!el.hasAttribute('title')) el.setAttribute('title', m.state === 'broken' ? T.broken : T.changed);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
} else if (d.type === 'scroll') {
|
|
124
|
+
window.scrollTo(0, d.y || 0);
|
|
125
|
+
} else if (d.type === 'clear-selection') {
|
|
126
|
+
setSelected([]);
|
|
127
|
+
} else if (d.type === 'highlight') {
|
|
128
|
+
const el = [...document.querySelectorAll('[data-src]')].find((x) => x.getAttribute('data-src') === d.src);
|
|
129
|
+
if (el) { el.scrollIntoView({ block: 'center', behavior: 'smooth' }); el.setAttribute('data-tm-flash', ''); setTimeout(() => el.removeAttribute('data-tm-flash'), 2600); }
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
let scrollTimer = null;
|
|
134
|
+
window.addEventListener('scroll', () => {
|
|
135
|
+
clearTimeout(scrollTimer);
|
|
136
|
+
scrollTimer = setTimeout(() => post({ type: 'scroll', page: pagePath(), y: window.scrollY }), 120);
|
|
137
|
+
}, { passive: true });
|
|
138
|
+
|
|
139
|
+
const ready = () => post({ type: 'loaded', page: pagePath(), title: document.title || '' });
|
|
140
|
+
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', ready); else ready();
|
|
141
|
+
})();
|