truemap-cli 0.1.0 → 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/README.md +31 -27
- package/bin/truemap.js +3 -0
- package/kit/fonts/OFL.txt +93 -0
- package/kit/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
- package/kit/fonts/ibm-plex-mono-latin-500-normal.woff2 +0 -0
- package/kit/fonts/ibm-plex-sans-latin-400-normal.woff2 +0 -0
- package/kit/fonts/ibm-plex-sans-latin-500-normal.woff2 +0 -0
- package/kit/fonts/ibm-plex-sans-latin-600-normal.woff2 +0 -0
- package/kit/truemap.css +248 -186
- package/package.json +1 -1
- package/skills/truemap/SKILL.md +4 -3
- package/src/check.js +32 -1
- package/src/cli.js +75 -20
- package/src/export.js +62 -0
- package/src/guide.md +67 -32
- package/src/outline.js +71 -0
- package/src/server.js +453 -394
- package/src/ui/sdk.js +350 -58
- package/src/ui/wires.js +237 -0
- package/src/ui/workspace.css +194 -128
- package/src/ui/workspace.html +59 -45
- package/src/ui/workspace.js +277 -104
package/src/server.js
CHANGED
|
@@ -1,394 +1,453 @@
|
|
|
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
|
-
|
|
12
|
-
const
|
|
13
|
-
const
|
|
14
|
-
const
|
|
15
|
-
const
|
|
16
|
-
const
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
let
|
|
34
|
-
let
|
|
35
|
-
let
|
|
36
|
-
let
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
try {
|
|
49
|
-
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
function
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
if (
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
//
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
const
|
|
332
|
-
|
|
333
|
-
scheduleChecks();
|
|
334
|
-
return sendJson(res, 200, { ok: true
|
|
335
|
-
}
|
|
336
|
-
if (p === '/api/
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
}
|
|
351
|
-
|
|
352
|
-
//
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
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
|
+
import { exportPage, kitCss } from './export.js';
|
|
11
|
+
|
|
12
|
+
const root = resolve(process.argv[2] || process.cwd());
|
|
13
|
+
const folder = join(root, FOLDER);
|
|
14
|
+
const token = randomBytes(18).toString('base64url');
|
|
15
|
+
const statePath = serverStatePath(root);
|
|
16
|
+
const IDLE_MS = Number(process.env.TRUEMAP_IDLE_MS || 30 * 60 * 1000);
|
|
17
|
+
const CLOSE_GRACE_MS = Number(process.env.TRUEMAP_CLOSE_GRACE_MS || 10_000);
|
|
18
|
+
const UI_DIR = join(PKG_DIR, 'src', 'ui');
|
|
19
|
+
const KIT_DIR = join(PKG_DIR, 'kit');
|
|
20
|
+
const FONT_DIR = join(KIT_DIR, 'fonts');
|
|
21
|
+
const CMD = process.env.TRUEMAP_CMD || 'npx -y truemap-cli';
|
|
22
|
+
|
|
23
|
+
const MIME = {
|
|
24
|
+
'.html': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8',
|
|
25
|
+
'.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8',
|
|
26
|
+
'.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif',
|
|
27
|
+
'.webp': 'image/webp', '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.woff': 'font/woff', '.txt': 'text/plain; charset=utf-8',
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// ---------- state ----------
|
|
31
|
+
const clients = new Set(); // SSE responses (browser tabs)
|
|
32
|
+
const queue = []; // messages waiting for the agent
|
|
33
|
+
let listener = null; // { res, timer } – the single active `listen`
|
|
34
|
+
let agentState = 'offline'; // offline (never seen) | listening | working | idle (back in the terminal)
|
|
35
|
+
let agentName = ''; // claude-code | codex | ''
|
|
36
|
+
let agentSince = 0; // when the current state began
|
|
37
|
+
let endRequested = false; // the user pressed End conversation while the agent wasn't listening
|
|
38
|
+
let annotateWish; // set by `truemap <page> --annotate` before a tab is open
|
|
39
|
+
let lastAgentActivity = 0;
|
|
40
|
+
let currentPage = null;
|
|
41
|
+
let closeTimer = null;
|
|
42
|
+
let idleTimer = null;
|
|
43
|
+
let seq = 0;
|
|
44
|
+
let lastCheck = { gitRepo: false, results: [] };
|
|
45
|
+
const history = loadHistory();
|
|
46
|
+
|
|
47
|
+
function loadHistory() {
|
|
48
|
+
try {
|
|
49
|
+
return readFileSync(historyPath(root), 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)).slice(-200);
|
|
50
|
+
} catch { return []; }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function remember(entry) {
|
|
54
|
+
history.push(entry);
|
|
55
|
+
if (history.length > 200) history.shift();
|
|
56
|
+
try { appendPrivate(historyPath(root), JSON.stringify(entry) + '\n'); } catch { /* ignore */ }
|
|
57
|
+
broadcast({ type: 'chat', entry });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function broadcast(event) {
|
|
61
|
+
const data = `data: ${JSON.stringify(event)}\n\n`;
|
|
62
|
+
for (const res of clients) res.write(data);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const agentInfo = () => ({ state: agentState, name: agentName, since: agentSince });
|
|
66
|
+
function setAgentState(s) {
|
|
67
|
+
if (agentState === s) return;
|
|
68
|
+
agentState = s;
|
|
69
|
+
agentSince = Date.now();
|
|
70
|
+
broadcast({ type: 'agent', agent: agentInfo() });
|
|
71
|
+
}
|
|
72
|
+
function noteAgent(name) {
|
|
73
|
+
if (typeof name === 'string' && name && name !== agentName) { agentName = name.slice(0, 40); broadcast({ type: 'agent', agent: agentInfo() }); }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function touchIdle() {
|
|
77
|
+
clearTimeout(idleTimer);
|
|
78
|
+
idleTimer = setTimeout(() => {
|
|
79
|
+
if (clients.size === 0 && !listener && queue.length === 0) shutdown();
|
|
80
|
+
else touchIdle();
|
|
81
|
+
}, IDLE_MS);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function shutdown() {
|
|
85
|
+
broadcast({ type: 'closing' });
|
|
86
|
+
try {
|
|
87
|
+
const s = JSON.parse(readFileSync(statePath, 'utf8'));
|
|
88
|
+
if (s.pid === process.pid) rmSync(statePath, { force: true });
|
|
89
|
+
} catch { /* ignore */ }
|
|
90
|
+
setTimeout(() => process.exit(0), 150); // let the browsers hear 'closing'
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ---------- listen / reply ----------
|
|
94
|
+
function finishListen(body) {
|
|
95
|
+
if (!listener) return;
|
|
96
|
+
const { res, timer } = listener;
|
|
97
|
+
clearTimeout(timer);
|
|
98
|
+
listener = null;
|
|
99
|
+
sendJson(res, 200, body);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function deliverQueue() {
|
|
103
|
+
if (listener && (listener.res.destroyed || listener.res.writableEnded)) { clearTimeout(listener.timer); listener = null; setAgentState('idle'); }
|
|
104
|
+
if (!listener || queue.length === 0) return;
|
|
105
|
+
const messages = queue.splice(0, queue.length);
|
|
106
|
+
setAgentState('working');
|
|
107
|
+
lastAgentActivity = Date.now();
|
|
108
|
+
broadcast({ type: 'delivered', ids: messages.map((m) => m.id) });
|
|
109
|
+
finishListen({ status: 'message', messages });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function scheduleCloseCheck() {
|
|
113
|
+
clearTimeout(closeTimer);
|
|
114
|
+
if (!listener || clients.size > 0) return;
|
|
115
|
+
closeTimer = setTimeout(() => {
|
|
116
|
+
if (listener && clients.size === 0 && queue.length === 0) {
|
|
117
|
+
finishListen({ status: 'browser_closed' });
|
|
118
|
+
setAgentState('idle');
|
|
119
|
+
}
|
|
120
|
+
}, CLOSE_GRACE_MS);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ---------- checks & file watching ----------
|
|
124
|
+
function runChecks() {
|
|
125
|
+
try { lastCheck = checkAll(root); } catch { lastCheck = { gitRepo: false, results: [] }; }
|
|
126
|
+
broadcast({ type: 'check', check: lastCheck });
|
|
127
|
+
return lastCheck;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Checks shell out to git, which can take a moment: never make a request wait for them.
|
|
131
|
+
let checkQueued = false;
|
|
132
|
+
function scheduleChecks() {
|
|
133
|
+
if (checkQueued) return;
|
|
134
|
+
checkQueued = true;
|
|
135
|
+
setTimeout(() => { checkQueued = false; runChecks(); }, 30);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
let watchTimer = null;
|
|
139
|
+
const changedPages = new Set();
|
|
140
|
+
function startWatching() {
|
|
141
|
+
const onChange = (file) => {
|
|
142
|
+
if (file) changedPages.add(String(file).split(sep).join('/'));
|
|
143
|
+
clearTimeout(watchTimer);
|
|
144
|
+
watchTimer = setTimeout(() => {
|
|
145
|
+
const files = [...changedPages];
|
|
146
|
+
changedPages.clear();
|
|
147
|
+
broadcast({ type: 'pages', pages: safePages() });
|
|
148
|
+
broadcast({ type: 'changed', files });
|
|
149
|
+
scheduleChecks();
|
|
150
|
+
}, 150);
|
|
151
|
+
};
|
|
152
|
+
try {
|
|
153
|
+
const w = watch(folder, { recursive: true }, (_e, f) => onChange(f));
|
|
154
|
+
w.on('error', () => { try { w.close(); } catch { /* ignore */ } setTimeout(startWatching, 2000); });
|
|
155
|
+
} catch { setTimeout(startWatching, 5000); }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function safePages() {
|
|
159
|
+
try { return listPages(root); } catch { return []; }
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// ---------- http helpers ----------
|
|
163
|
+
function sendJson(res, status, body) {
|
|
164
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
165
|
+
res.end(JSON.stringify(body));
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function sendText(res, status, text) {
|
|
169
|
+
res.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
170
|
+
res.end(text);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function readBody(req, limit = 2 * 1024 * 1024) {
|
|
174
|
+
return new Promise((ok, fail) => {
|
|
175
|
+
let size = 0;
|
|
176
|
+
const chunks = [];
|
|
177
|
+
req.on('data', (c) => { size += c.length; if (size > limit) { fail(new Error('too large')); req.destroy(); } else chunks.push(c); });
|
|
178
|
+
req.on('end', () => {
|
|
179
|
+
try { ok(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); } catch (e) { fail(e); }
|
|
180
|
+
});
|
|
181
|
+
req.on('error', fail);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
let port = 0; // workspace + API
|
|
186
|
+
let contentPort = 0; // pages only: a separate origin, so page scripts can never reach the API
|
|
187
|
+
function hostAllowed(req, p = port) {
|
|
188
|
+
const host = (req.headers.host || '').toLowerCase();
|
|
189
|
+
return [`127.0.0.1:${p}`, `localhost:${p}`, `[::1]:${p}`].includes(host);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function originAllowed(req) {
|
|
193
|
+
const origin = req.headers.origin;
|
|
194
|
+
if (!origin) return true; // CLI requests carry no Origin
|
|
195
|
+
return [`http://127.0.0.1:${port}`, `http://localhost:${port}`, `http://[::1]:${port}`].includes(origin.toLowerCase());
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function tokenOk(req, url) {
|
|
199
|
+
return req.headers['x-truemap-token'] === token || url.searchParams.get('t') === token;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Resolves a request path inside a base dir; refuses traversal and symlinks leading outside. */
|
|
203
|
+
function folderIsSafe() {
|
|
204
|
+
try { return !lstatSync(folder).isSymbolicLink(); } catch { return false; }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function safeFile(base, relPath) {
|
|
208
|
+
let decoded;
|
|
209
|
+
try { decoded = decodeURIComponent(relPath); } catch { return null; }
|
|
210
|
+
if (decoded.includes('\0')) return null;
|
|
211
|
+
const full = resolve(base, '.' + sep + decoded.replace(/\//g, sep));
|
|
212
|
+
if (full !== base && !full.startsWith(base + sep)) return null;
|
|
213
|
+
if (!existsSync(full)) return null;
|
|
214
|
+
try {
|
|
215
|
+
const real = realpathSync(full);
|
|
216
|
+
const realBase = realpathSync(base);
|
|
217
|
+
if (real !== realBase && !real.startsWith(realBase + sep)) return null;
|
|
218
|
+
if (statSync(real).isDirectory()) return null;
|
|
219
|
+
return real;
|
|
220
|
+
} catch { return null; }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function servePage(res, file) {
|
|
224
|
+
const type = MIME[extname(file).toLowerCase()] || 'application/octet-stream';
|
|
225
|
+
let body = readFileSync(file);
|
|
226
|
+
if (type.startsWith('text/html')) {
|
|
227
|
+
const inject = `<script src="/__truemap/sdk.js"></script>`;
|
|
228
|
+
let html = body.toString('utf8');
|
|
229
|
+
html = /<\/body>/i.test(html) ? html.replace(/<\/body>(?![\s\S]*<\/body>)/i, `${inject}</body>`) : html + inject;
|
|
230
|
+
body = Buffer.from(html, 'utf8');
|
|
231
|
+
}
|
|
232
|
+
res.writeHead(200, {
|
|
233
|
+
'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',
|
|
234
|
+
// Only the truemap workspace may frame these pages.
|
|
235
|
+
'Content-Security-Policy': `frame-ancestors http://127.0.0.1:${port}`,
|
|
236
|
+
});
|
|
237
|
+
res.end(body);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function serveStatic(res, dir, name, cache = 'no-store') {
|
|
241
|
+
const file = safeFile(dir, name);
|
|
242
|
+
if (!file) return sendText(res, 404, 'not found');
|
|
243
|
+
res.writeHead(200, { 'Content-Type': MIME[extname(file).toLowerCase()] || 'application/octet-stream', 'Cache-Control': cache });
|
|
244
|
+
res.end(readFileSync(file));
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// The page kit comes from truemap itself, so every repo gets kit updates. A repo may still keep its own
|
|
248
|
+
// assets/truemap.css (older setups, or a hand-tuned copy): that copy wins. assets/theme.css is appended.
|
|
249
|
+
function serveKit(res) {
|
|
250
|
+
const css = kitCss(root);
|
|
251
|
+
res.writeHead(200, { 'Content-Type': 'text/css; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
252
|
+
res.end(css);
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function serveUi(res, name) {
|
|
256
|
+
const file = safeFile(UI_DIR, name);
|
|
257
|
+
if (!file) return sendText(res, 404, 'not found');
|
|
258
|
+
const type = MIME[extname(file).toLowerCase()] || 'application/octet-stream';
|
|
259
|
+
res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-store' });
|
|
260
|
+
res.end(readFileSync(file));
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ---------- routes ----------
|
|
264
|
+
const server = createServer(async (req, res) => {
|
|
265
|
+
if (!hostAllowed(req)) return sendText(res, 403, 'forbidden host');
|
|
266
|
+
const url = new URL(req.url, `http://127.0.0.1:${port}`);
|
|
267
|
+
const p = url.pathname;
|
|
268
|
+
touchIdle();
|
|
269
|
+
|
|
270
|
+
try {
|
|
271
|
+
// Workspace shell (token required so other local pages can't embed a live session).
|
|
272
|
+
if (p === '/' && req.method === 'GET') {
|
|
273
|
+
if (!tokenOk(req, url)) return sendText(res, 403, 'missing token – open the link printed by `truemap`');
|
|
274
|
+
const html = readFileSync(join(UI_DIR, 'workspace.html'), 'utf8')
|
|
275
|
+
.replace('__TRUEMAP_TOKEN__', token)
|
|
276
|
+
.replace('__TRUEMAP_CONTENT__', `http://127.0.0.1:${contentPort}`);
|
|
277
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer' });
|
|
278
|
+
return res.end(html);
|
|
279
|
+
}
|
|
280
|
+
if (p.startsWith('/__truemap/fonts/') && req.method === 'GET') return serveStatic(res, FONT_DIR, p.slice('/__truemap/fonts/'.length), 'max-age=86400');
|
|
281
|
+
if (p.startsWith('/__truemap/') && req.method === 'GET') return serveUi(res, p.slice('/__truemap/'.length));
|
|
282
|
+
if (!p.startsWith('/api/')) return sendText(res, 404, 'not found');
|
|
283
|
+
if (!originAllowed(req) || !tokenOk(req, url)) return sendText(res, 403, 'forbidden');
|
|
284
|
+
|
|
285
|
+
// ----- browser side -----
|
|
286
|
+
if (p === '/api/events' && req.method === 'GET') {
|
|
287
|
+
scheduleChecks();
|
|
288
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-store', Connection: 'keep-alive' });
|
|
289
|
+
res.write(`data: ${JSON.stringify({
|
|
290
|
+
type: 'hello', version: VERSION, root, cmd: CMD, agent: agentInfo(), pages: safePages(), check: lastCheck,
|
|
291
|
+
history, current: currentPage, pending: queue.map((m) => m.id), ...(annotateWish !== undefined ? { annotate: annotateWish } : {}),
|
|
292
|
+
})}\n\n`);
|
|
293
|
+
annotateWish = undefined;
|
|
294
|
+
clients.add(res);
|
|
295
|
+
clearTimeout(closeTimer);
|
|
296
|
+
const ping = setInterval(() => res.write(': ping\n\n'), 20_000);
|
|
297
|
+
req.on('close', () => { clearInterval(ping); clients.delete(res); scheduleCloseCheck(); touchIdle(); });
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
if (p === '/api/send' && req.method === 'POST') {
|
|
301
|
+
const b = await readBody(req);
|
|
302
|
+
const text = String(b.text ?? '').slice(0, 20_000);
|
|
303
|
+
const str = (v, n) => String(v ?? '').slice(0, n);
|
|
304
|
+
const context = (Array.isArray(b.context) ? b.context.slice(0, 20) : [])
|
|
305
|
+
.filter((c) => c && typeof c === 'object')
|
|
306
|
+
.map((c) => ({
|
|
307
|
+
kind: c.kind === 'text' ? 'text' : 'element', label: str(c.label, 120), src: str(c.src, 300), excerpt: str(c.excerpt, 600),
|
|
308
|
+
...(c.comment ? { comment: str(c.comment, 4000) } : {}), ...(c.page ? { page: str(c.page, 200) } : {}),
|
|
309
|
+
}));
|
|
310
|
+
const answer = b.kind === 'answer' && b.answer && typeof b.answer === 'object'
|
|
311
|
+
? { question: String(b.answer.question ?? '').slice(0, 500), choice: String(b.answer.choice ?? '').slice(0, 2000), note: String(b.answer.note ?? '').slice(0, 4000) }
|
|
312
|
+
: null;
|
|
313
|
+
if (!text.trim() && context.length === 0 && !answer) return sendJson(res, 400, { error: 'empty' });
|
|
314
|
+
const msg = {
|
|
315
|
+
id: `m${Date.now().toString(36)}${(seq++).toString(36)}`,
|
|
316
|
+
at: new Date().toISOString(),
|
|
317
|
+
kind: answer ? 'answer' : 'message',
|
|
318
|
+
from: b.from === 'page' ? 'page' : 'user',
|
|
319
|
+
page: typeof b.page === 'string' ? b.page : currentPage,
|
|
320
|
+
text,
|
|
321
|
+
context,
|
|
322
|
+
...(answer ? { answer } : {}),
|
|
323
|
+
};
|
|
324
|
+
queue.push(msg);
|
|
325
|
+
endRequested = false; // a new message means the conversation goes on
|
|
326
|
+
remember({ role: 'user', ...msg });
|
|
327
|
+
deliverQueue();
|
|
328
|
+
return sendJson(res, 200, { ok: true, id: msg.id, delivered: !queue.includes(msg) });
|
|
329
|
+
}
|
|
330
|
+
if (p === '/api/viewing' && req.method === 'POST') {
|
|
331
|
+
const b = await readBody(req);
|
|
332
|
+
currentPage = typeof b.page === 'string' ? b.page : currentPage;
|
|
333
|
+
scheduleChecks();
|
|
334
|
+
return sendJson(res, 200, { ok: true });
|
|
335
|
+
}
|
|
336
|
+
if (p === '/api/check' && req.method === 'POST') return sendJson(res, 200, runChecks());
|
|
337
|
+
if (p === '/api/export' && req.method === 'GET') {
|
|
338
|
+
const page = url.searchParams.get('page') || '';
|
|
339
|
+
let html;
|
|
340
|
+
try { html = exportPage(root, page); } catch (e) { return sendText(res, 404, String(e.message || e)); }
|
|
341
|
+
const name = page.split('/').pop().replace(/\.html?$/i, '') || 'page';
|
|
342
|
+
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'Content-Disposition': `attachment; filename="${name.replace(/[^\w.-]/g, '_')}-truemap.html"` });
|
|
343
|
+
return res.end(html);
|
|
344
|
+
}
|
|
345
|
+
if (p === '/api/end' && req.method === 'POST') {
|
|
346
|
+
// The user is done talking on the page: free the agent to go back to the terminal.
|
|
347
|
+
if (listener) finishListen({ status: 'ended' }); else if (agentState === 'working' || agentState === 'listening') endRequested = true;
|
|
348
|
+
setAgentState('idle');
|
|
349
|
+
return sendJson(res, 200, { ok: true });
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// ----- agent (CLI) side -----
|
|
353
|
+
if (p === '/api/agent/status' && req.method === 'GET') {
|
|
354
|
+
return sendJson(res, 200, { version: VERSION, pid: process.pid, root, clients: clients.size, agent: agentState, queued: queue.length, current: currentPage });
|
|
355
|
+
}
|
|
356
|
+
if (p === '/api/agent/listen' && req.method === 'POST') {
|
|
357
|
+
const b = await readBody(req);
|
|
358
|
+
if (listener) finishListen({ status: 'replaced' });
|
|
359
|
+
lastAgentActivity = Date.now();
|
|
360
|
+
noteAgent(b.agent);
|
|
361
|
+
const timeoutMs = Number(b.timeoutMs) > 0 ? Number(b.timeoutMs) : 0;
|
|
362
|
+
const timer = timeoutMs ? setTimeout(() => { finishListen({ status: 'timeout' }); setAgentState('idle'); }, timeoutMs) : null;
|
|
363
|
+
listener = { res, timer };
|
|
364
|
+
// The request body is already consumed, so watch the response: it closes when the CLI goes away.
|
|
365
|
+
res.on('close', () => {
|
|
366
|
+
if (listener && listener.res === res) { clearTimeout(listener.timer); listener = null; setAgentState('idle'); }
|
|
367
|
+
});
|
|
368
|
+
if (queue.length) return deliverQueue();
|
|
369
|
+
if (endRequested) { endRequested = false; finishListen({ status: 'ended' }); setAgentState('idle'); return; }
|
|
370
|
+
setAgentState('listening');
|
|
371
|
+
if (clients.size === 0) scheduleCloseCheck();
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
if (p === '/api/agent/reply' && req.method === 'POST') {
|
|
375
|
+
const b = await readBody(req);
|
|
376
|
+
const text = String(b.text ?? '').slice(0, 100_000);
|
|
377
|
+
if (!text.trim()) return sendJson(res, 400, { error: 'empty reply' });
|
|
378
|
+
lastAgentActivity = Date.now();
|
|
379
|
+
noteAgent(b.agent);
|
|
380
|
+
remember({ role: 'agent', id: `a${Date.now().toString(36)}${(seq++).toString(36)}`, at: new Date().toISOString(), agent: agentName, text });
|
|
381
|
+
if (!listener) setAgentState(b.keepWorking || b.willListen ? 'working' : 'idle');
|
|
382
|
+
return sendJson(res, 200, { ok: true, browsers: clients.size });
|
|
383
|
+
}
|
|
384
|
+
if (p === '/api/agent/navigate' && req.method === 'POST') {
|
|
385
|
+
const b = await readBody(req);
|
|
386
|
+
const page = String(b.page ?? '');
|
|
387
|
+
noteAgent(b.agent);
|
|
388
|
+
if (typeof b.annotate === 'boolean' && clients.size === 0) annotateWish = b.annotate;
|
|
389
|
+
broadcast({ type: 'navigate', page, pages: safePages(), ...(typeof b.annotate === 'boolean' ? { annotate: b.annotate } : {}) });
|
|
390
|
+
scheduleChecks();
|
|
391
|
+
return sendJson(res, 200, { ok: true, browsers: clients.size });
|
|
392
|
+
}
|
|
393
|
+
if (p === '/api/agent/progress' && req.method === 'POST') {
|
|
394
|
+
const b = await readBody(req);
|
|
395
|
+
broadcast({ type: 'progress', text: String(b.text ?? '').slice(0, 300) });
|
|
396
|
+
return sendJson(res, 200, { ok: true });
|
|
397
|
+
}
|
|
398
|
+
if (p === '/api/agent/shutdown' && req.method === 'POST') {
|
|
399
|
+
sendJson(res, 200, { ok: true });
|
|
400
|
+
setTimeout(shutdown, 50);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
return sendText(res, 404, 'not found');
|
|
404
|
+
} catch (e) {
|
|
405
|
+
if (!res.headersSent) sendJson(res, 500, { error: String(e?.message || e) });
|
|
406
|
+
}
|
|
407
|
+
});
|
|
408
|
+
|
|
409
|
+
// Content origin: serves .truemap pages (with the SDK injected) and nothing else.
|
|
410
|
+
const content = createServer((req, res) => {
|
|
411
|
+
if (!hostAllowed(req, contentPort)) return sendText(res, 403, 'forbidden host');
|
|
412
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return sendText(res, 405, 'method not allowed');
|
|
413
|
+
const p = new URL(req.url, `http://127.0.0.1:${contentPort}`).pathname;
|
|
414
|
+
try {
|
|
415
|
+
if (p === '/__truemap/sdk.js') {
|
|
416
|
+
const js = readFileSync(join(UI_DIR, 'wires.js'), 'utf8') + '\n' + readFileSync(join(UI_DIR, 'sdk.js'), 'utf8').replace('__TRUEMAP_PARENT__', `http://127.0.0.1:${port}`);
|
|
417
|
+
res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
418
|
+
return res.end(js);
|
|
419
|
+
}
|
|
420
|
+
if (p.startsWith('/__truemap/fonts/')) return serveStatic(res, FONT_DIR, p.slice('/__truemap/fonts/'.length), 'max-age=86400');
|
|
421
|
+
if (p === '/pages/assets/truemap.css') return serveKit(res);
|
|
422
|
+
if (p.startsWith('/pages/')) {
|
|
423
|
+
const file = folderIsSafe() ? safeFile(folder, p.slice('/pages/'.length)) : null;
|
|
424
|
+
if (!file) return sendText(res, 404, 'page not found');
|
|
425
|
+
return servePage(res, file);
|
|
426
|
+
}
|
|
427
|
+
return sendText(res, 404, 'not found');
|
|
428
|
+
} catch (e) {
|
|
429
|
+
if (!res.headersSent) sendText(res, 500, String(e?.message || e));
|
|
430
|
+
}
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
server.listen(Number(process.env.TRUEMAP_PORT || 0), '127.0.0.1', () => {
|
|
434
|
+
port = server.address().port;
|
|
435
|
+
content.listen(0, '127.0.0.1', () => {
|
|
436
|
+
contentPort = content.address().port;
|
|
437
|
+
writePrivate(statePath, JSON.stringify({ pid: process.pid, port, contentPort, token, version: VERSION, root, startedAt: new Date().toISOString() }));
|
|
438
|
+
startWatching();
|
|
439
|
+
scheduleChecks();
|
|
440
|
+
touchIdle();
|
|
441
|
+
});
|
|
442
|
+
});
|
|
443
|
+
|
|
444
|
+
// Code changes outside .truemap aren't watched (too noisy); re-check while someone is looking.
|
|
445
|
+
setInterval(() => { if (clients.size > 0) scheduleChecks(); }, 30_000).unref();
|
|
446
|
+
|
|
447
|
+
// Mark the agent offline if it hasn't listened or replied in a long while.
|
|
448
|
+
setInterval(() => {
|
|
449
|
+
if (!listener && (agentState === 'working' || agentState === 'idle') && Date.now() - lastAgentActivity > 20 * 60 * 1000) setAgentState('offline');
|
|
450
|
+
}, 60_000).unref();
|
|
451
|
+
|
|
452
|
+
process.on('SIGTERM', shutdown);
|
|
453
|
+
process.on('SIGINT', shutdown);
|