Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
3503 lines (3172 loc) · 145 KB
/
Copy pathserver.js
File metadata and controls
3503 lines (3172 loc) · 145 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
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
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
332
333
334
335
336
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// The bin is also the CLI, which agents run per card: it skips the server's requires.
if (require('./cli').runCli(process.argv)) return;
// #region SETUP
const express = require('express');
const path = require('node:path');
const fs = require('node:fs').promises;
const { existsSync, readdirSync, readFileSync, writeFileSync, statSync, unlinkSync, rmSync, mkdirSync, renameSync, realpathSync } = require('node:fs');
const _readline = require('node:readline');
const chokidar = require('chokidar');
const os = require('node:os');
const crypto = require('node:crypto');
const { spawn } = require('node:child_process');
const { assertOpenTarget, whichSync, exeBehindShim } = require('./lib/open-editor');
const { createNetGuard } = require('./lib/net-guard');
const { isContained, realpathDeepest } = require('./lib/contain');
const { resolveScratchSubdir, listScratchDir } = require('./lib/scratch-files');
const { fileUrlToPath } = require('./lib/file-url');
const { httpError: previewError } = require('./lib/http-error');
const { MODEL_WINDOWS_FILE, contextOf } = require('./lib/model-windows');
const { readSettings } = require('./lib/claude-settings');
const { companionStatus, installPlan, refreshLatest } = require('./lib/companions');
const { createCompanionHost } = require('./lib/companion-host');
const {
readRecentMessages: _readRecentMessagesUncached,
readMessagesPage: _readMessagesPageUncached,
readSessionInfoFromJsonl,
transcriptActivityMs,
modelDisplayName,
buildSessionDigest,
readArtifactLinks,
readScratchpadCreations,
extractPromptFromTranscript,
extractModelFromTranscript,
extractAgentResultFromTranscript,
readFullToolResult,
readUserImage,
readToolResultImage,
readCachedImage,
readLines
} = require('./lib/parsers');
const { inlineHtmlAssets, MIME_BY_EXT } = require('./lib/inline-assets');
const { resolvePiAgentDir, boardDir, getArgValue,storageNamespace } = require('./lib/board-dir');
const { readTerminalConfig } = require('./lib/terminal');
const { THINKING_LEVELS } = require('./lib/pi-agents');
const { createTerminalClient } = require('./lib/terminal-client');
const { createShowStore, mountShowRoutes, showBodyParser, SESSION_SHOW_PATH } = require('./lib/show');
const { createAskStore, mountAskRoutes, terminalAskRoutes, askBodyParser, ASK_PATH, SESSION_ASK_PATH, SESSION_ASK_ROUTES } = require('./lib/ask');
const { readLiveSessions, isPidAlive, isSessionLive, noteReplacedSessions } = require('./lib/live-sessions');
const { createProcStats } = require('./lib/proc-stats');
const { createUserGroupStore } = require('./lib/user-groups');
const { createSessionPinStore } = require('./lib/session-pins');
const { stampedJsonFile } = require('./lib/stamped-json-file');
const { parseReviewSource, parseActionBody, formatActionMarkdown } = require('./lib/preview-action');
const { createDispatchedStore, pruneSessionDirs, pruneTaskMaps, retentionMs } = require('./lib/retention');
const { createDispatchReports, parseReport } = require('./lib/dispatch-reports');
const { createModelCache, listPiModels } = require('./lib/pi-models');
const { createWorktreeStore } = require('./lib/worktrees');
const { createScratchpadDirResolver, defaultScratchpadRoot } = require('./lib/scratchpad-dir');
const { readGitBranch } = require('./lib/git-branch');
const { createLinkedDocStore, linkUrl } = require('./lib/linked-docs');
const { createPaneStore, isOwnOrigin } = require('./lib/panes');
const { probeFraming, parseOrigin } = require('./lib/frame-policy');
const { pickFolder } = require('./lib/folder-dialog');
const { loadSessionCache, saveSessionCache } = require('./lib/session-cache');
const { countTaskDir } = require('./lib/task-counts');
const { readTaskDir } = require('./lib/task-dir');
const { foldAgentLines } = require('./lib/agent-log');
const { claudeWaiting } = require('./lib/pi-transcript');
const { projectMatcher, normalizeProjectPath, sessionProjectKey } = require('./public/project-match');
const { sessionRoots, listSessionFiles, readSessionHeader, describeSessionFile, decodeProjectDir, scanSessionIds } = require('./lib/pi-sessions');
startServer();
// Not indented: the formatter is off for this file, and a reindent would rewrite every line.
function startServer() {
const app = express();
const PORT = parseInt(getArgValue('port') || process.env.PORT || '3460', 10);
// Mounted before express.json() so a rejected request never buffers a body, and
// before the /api catch-all so no route escapes the check.
// The board frames the terminal from its other loopback name, so Chrome runs it in its own process.
const net = createNetGuard({ appName: 'pi-kanban', selfFramedPaths: ['/terminal.html'] });
app.use(net.hostGuard);
app.use(net.frameGuard);
app.use(net.originGuard);
const PI_AGENT_DIR = resolvePiAgentDir();
const PK_DIR = boardDir(PI_AGENT_DIR);
const TASKS_DIR = path.join(PK_DIR, 'tasks');
const SESSION_DIR_FLAG = getArgValue('session-dir');
// A pi started with its own --session-dir reports that dir in the live registry. The board keeps
// it, so those sessions stay listed after that pi exits and after a board restart.
const SESSION_DIRS_FILE = path.join(PK_DIR, 'session-dirs.json');
const savedSessionDirs = readJsonOrNull(SESSION_DIRS_FILE);
const reportedSessionDirs = new Set(Array.isArray(savedSessionDirs) ? savedSessionDirs : []);
const rootsFor = (cwds) => sessionRoots({ agentDir: PI_AGENT_DIR, sessionDir: SESSION_DIR_FLAG, cwds, sessionDirs: [...reportedSessionDirs] });
const SESSION_OPTS = { roots: rootsFor() };
const SESSIONS_DIR = path.join(PK_DIR, 'live');
const AGENT_ACTIVITY_DIR = path.join(PK_DIR, 'agent-activity');
const MODEL_WINDOWS_PATH = path.join(PK_DIR, MODEL_WINDOWS_FILE);
const ATTACHMENTS_DIR = path.join(PK_DIR, 'attachments');
const PINS_FILE = path.join(PK_DIR, 'pins.json');
const USER_GROUPS_FILE = path.join(PK_DIR, 'groups.json');
const DISPATCHED_FILE = path.join(PK_DIR, 'dispatched.json');
const WORKTREES_FILE = path.join(PK_DIR, 'worktrees.json');
const LINKED_DOCS_FILE = path.join(PK_DIR, 'linked-docs.json');
const PANES_FILE = path.join(PK_DIR, 'panes.json');
const SERVER_INFO_FILE = path.join(PK_DIR, 'server.json');
const TERMINAL_TOKENS_DIR = path.join(PK_DIR, 'terminal-tokens');
const TERMINAL_SECRET_FILE = path.join(PK_DIR, 'terminal-secret.json');
const SESSION_CACHE_FILE = path.join(PK_DIR, 'session-cache.json');
// Every board on a config dir rewrites the whole file, so a test board points this elsewhere.
const TERMINALS_FILE = process.env.PK_TERMINALS_FILE ? path.resolve(process.env.PK_TERMINALS_FILE) : path.join(PK_DIR, 'terminals.json');
// os.tmpdir() can be an 8.3 short path on Windows; transcripts record the long form.
const TEMP_ROOT = (() => {
try { return realpathSync.native(os.tmpdir()); } catch { return os.tmpdir(); }
})();
// The kanban extension makes the per-session pad under this root and records it in the session.
// Used only for a session that does not record its scratchpad dir.
// The root may not exist yet, so its deepest existing parent gives the long form.
const SCRATCHPAD_ROOT = realpathDeepest(defaultScratchpadRoot());
// #endregion
// #region SERVER_STATE
function writeJsonAtomic(file, obj, mode) {
mkdirSync(path.dirname(file), { recursive: true });
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
try {
writeFileSync(tmp, JSON.stringify(obj, null, 2), { encoding: 'utf8', mode });
renameSync(tmp, file);
} catch (e) {
rmSync(tmp, { force: true });
throw e;
}
}
// The pi extension reads task files while the board writes them, so it must never see half a file.
// On Windows a rename over a file another handle has open fails with EPERM or EBUSY until it closes.
let taskWriteSeq = 0;
async function writeTaskFile(file, task) {
const tmp = `${file}.${process.pid}.${++taskWriteSeq}.tmp`;
try {
await fs.writeFile(tmp, JSON.stringify(task, null, 2));
for (let attempt = 1; ; attempt++) {
try {
await fs.rename(tmp, file);
break;
} catch (e) {
if (attempt >= 10 || (e.code !== 'EPERM' && e.code !== 'EBUSY')) throw e;
await new Promise((r) => setTimeout(r, attempt * 10));
}
}
} catch (e) {
await fs.rm(tmp, { force: true });
throw e;
}
}
// For state that is also held in memory: a failed save is logged and the server goes on.
function writeJsonAtomicOrLog(file, obj, mode) {
try {
writeJsonAtomic(file, obj, mode);
} catch (e) {
console.error(`Failed to write ${path.basename(file)}:`, e.message);
}
}
function readJsonOrNull(file) {
try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; }
}
const jsonFile = (file) => ({
load: () => readJsonOrNull(file),
save: (data) => writeJsonAtomicOrLog(file, data),
});
const sessionPins = createSessionPinStore(stampedJsonFile(PINS_FILE, writeJsonAtomic));
// Port discovery for out-of-process helpers (the plugin's doorbell mod, the CLI).
// The pid rides along so a reader can tell a live server from a file left behind by
// a crashed one.
function writeServerInfo(port) {
writeJsonAtomicOrLog(SERVER_INFO_FILE, { port, pid: process.pid });
}
// For `dispatch start`: a local process as the same user can already run pi itself,
// so handing it the token adds little. A browser still cannot read the file.
// One file per port: two boards on one config dir each keep a token, so the CLI can
// reach the board PK_URL names even when the other one owns server.json.
// The sweep also drops terminal-token.json, the single file that older versions wrote.
let terminalTokenFile = null;
function writeTerminalToken(port) {
if (terminal.unavailableReason()) return;
let stale = [path.join(PK_DIR, 'terminal-token.json')];
try { stale = stale.concat(readdirSync(TERMINAL_TOKENS_DIR).map(name => path.join(TERMINAL_TOKENS_DIR, name))); } catch (_) { /* no dir yet */ }
for (const file of stale) {
const pid = ownerPid(file);
if (pid !== null && !isPidAlive(pid)) try { unlinkSync(file); } catch (_) { /* already gone */ }
}
terminalTokenFile = path.join(TERMINAL_TOKENS_DIR, `${port}.json`);
writeJsonAtomicOrLog(terminalTokenFile,{ pid: process.pid, token: terminal.token }, 0o600);
}
// The token outlives the server, so a restart does not cut off the terminal in open board tabs.
// --new-token replaces it.
function persistentTerminalToken() {
if (process.env.PK_TERMINAL_TOKEN) return process.env.PK_TERMINAL_TOKEN;
if (process.argv.includes('--no-terminal')) return undefined;
const saved = !process.argv.includes('--new-token') && readJsonOrNull(TERMINAL_SECRET_FILE)?.token;
if (typeof saved === 'string' && /^[0-9a-f]{64}$/.test(saved)) return saved;
const token = crypto.randomBytes(32).toString('hex');
writeJsonAtomicOrLog(TERMINAL_SECRET_FILE, { token }, 0o600);
return token;
}
function ownerPid(file) {
try { return JSON.parse(readFileSync(file, 'utf8')).pid ?? null; } catch (_) { return null; }
}
// A beacon that outlives its server sends the doorbell mod and the CLI to a closed
// port. The next server can take another port, so a stale beacon never comes back on its own — drop ours on
// the way out. Only when the file is still ours: a newer server on the same config
// dir has already claimed it. The terminal token file goes the same way.
function removeServerInfo() {
for (const file of [SERVER_INFO_FILE, terminalTokenFile]) {
if (file && ownerPid(file) === process.pid) try { unlinkSync(file); } catch (_) { /* already gone */ }
}
}
// A second server on the same config dir (a test run, say) takes the beacon and removes it on
// exit, which leaves this live server undiscoverable. A newer live owner keeps it.
function reclaimServerInfo(port) {
const pid = ownerPid(SERVER_INFO_FILE);
if (pid !== null && isPidAlive(pid)) return;
writeServerInfo(port);
}
process.on('exit', removeServerInfo);
for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
process.on(sig, () => {
removeServerInfo();
process.exit(0);
});
}
// #endregion
// #region TIMINGS
const PERMISSION_TTL_MS = 30 * 60 * 1000;
const AGENT_TTL_MS = 60 * 60 * 1000;
const AGENT_STALE_MS = 30 * 60 * 1000; // safety net for crashed sessions
const SESSION_STALE_MS = 5 * 60 * 1000;
// Keep an idle session in the active list this long after its last log write, so it
// doesn't vanish the instant a turn ends. Ungated by registry-idle — visibility only,
// never the "active" status (which stays accurate via hasRecentLog).
const SESSION_GRACE_MS = 2 * 60 * 1000;
const WAITING_RESOLVE_GRACE_MS = 15 * 1000;
const CLEANUP_MAX_AGE_MS = 2 * 24 * 60 * 60 * 1000;
const CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
const RETENTION_FIRST_RUN_MS = 5 * 60 * 1000;
// #endregion
// #region AGENT_ACTIVITY
function readAgentJsonl(filePath) {
return foldAgentLines(readFileSync(filePath, 'utf8'));
}
// Agent-activity record files in a session dir, excluding the `_`-prefixed sidecars
// (_waiting.json, _stop.json, _name-*). Returns [] if the dir is missing/unreadable.
function listAgentFiles(agentDir) {
try {
return readdirSync(agentDir).filter((f) => f.endsWith('.jsonl') && !f.startsWith('_'));
} catch (_) {
return [];
}
}
function persistAgent(dir, agent) {
const file = path.join(dir, `${agent.agentId}.jsonl`);
fs.appendFile(file, `${JSON.stringify({ ...agent, event: 'server-update' })}\n`, 'utf8').catch(() => {});
}
// <PK_DIR>/config.json — pi-kanban's own settings, per pi agent dir.
const PK_CONFIG_FILE = path.join(PK_DIR, 'config.json');
const pkConfigCache = new Map();
const readCckConfig = () => JSON.parse(readFileSync(PK_CONFIG_FILE, 'utf8'));
function pkConfigSection(name) {
try {
return readCckConfig()?.[name] ?? null;
} catch {
return null;
}
}
function boardEventsEnabled() {
return cachedByMtime(pkConfigCache, 'boardEvents', PK_CONFIG_FILE,
() => boardEventsOn(readCckConfig()), boardEventsOn(null));
}
function checkWaitingForUser(agentDir, logMtime) {
const data = readJsonOrNull(path.join(agentDir, '_waiting.json'));
if (data?.status !== 'waiting' || !data.timestamp) return null;
const waitTime = new Date(data.timestamp).getTime();
if (Date.now() - waitTime >= PERMISSION_TTL_MS) return null;
// After grace period, check if session resumed activity (user already responded)
if (movedOnSince(waitTime, logMtime)) return null;
return data;
}
function agentDisplayName(agent) {
return agent.type || agent.name;
}
function isGhostAgent(agent) {
if (agent.startedAt !== agent.updatedAt || agent.lastMessage) return false;
return (Date.now() - new Date(agent.startedAt).getTime()) >= AGENT_STALE_MS;
}
function getContextFields(meta) {
const reply = meta?.lastReply;
return {
context: contextOf(reply, readSettings(MODEL_WINDOWS_PATH) || {}),
cache: reply ? { ...reply, modelName: modelDisplayName(reply.model) } : null,
totals: meta?.totals || null,
};
}
function isAgentFresh(agent) {
if (isGhostAgent(agent)) return false;
const ts = agent.updatedAt || agent.startedAt;
if (!ts) return true;
return (Date.now() - new Date(ts).getTime()) < AGENT_TTL_MS;
}
function isAgentLive(agent) {
return agent.status === 'active' || agent.status === 'idle';
}
// A pi session records no git branch. Resolve it on demand from the session cwd. Cached per-cwd
// with a short TTL so a list refresh across N sessions sharing one cwd reads HEAD at most once per
// TTL window.
const gitBranchCache = new Map();
const GIT_BRANCH_TTL_MS = 30000;
const GIT_BRANCH_CACHE_MAX = 500;
function getGitBranch(cwd) {
if (!cwd) return null;
const now = Date.now();
const cached = gitBranchCache.get(cwd);
if (cached && now - cached.ts < GIT_BRANCH_TTL_MS) return cached.branch;
const branch = readGitBranch(cwd);
gitBranchCache.set(cwd, { branch, ts: now });
if (gitBranchCache.size > GIT_BRANCH_CACHE_MAX) {
const firstKey = gitBranchCache.keys().next().value;
gitBranchCache.delete(firstKey);
}
return branch;
}
const worktrees = createWorktreeStore(jsonFile(WORKTREES_FILE));
function getSessionLogStat(meta) {
if (!meta.jsonlPath) return { mtime: null, hasMessages: false };
try {
const st = statSync(meta.jsonlPath);
return { mtime: transcriptActivityMs(meta.jsonlPath, st), hasMessages: st.size > 1000 };
} catch { return { mtime: null, hasMessages: false }; }
}
// A transcript write past the grace window after a marker means the session went on.
function movedOnSince(markerMs, logMtime) {
return !!logMtime && logMtime > markerMs + WAITING_RESOLVE_GRACE_MS;
}
// The mod cannot delete _stop.json when the session works again.
function resumedSince(markerPath, logMtime) {
if (!logMtime) return false;
try { return movedOnSince(statSync(markerPath).mtimeMs, logMtime); }
catch { return true; }
}
function checkAgentStatus(agentDir, stale, logMtime) {
const result = { hasActive: false, hasRunning: false, waitingForUser: null, unread: false };
let names;
try { names = readdirSync(agentDir); } catch { return result; }
if (names.includes('_waiting.json')) result.waitingForUser = checkWaitingForUser(agentDir, logMtime);
if (result.waitingForUser) result.hasActive = true;
const stopped = names.includes('_stop.json') && !resumedSince(path.join(agentDir, '_stop.json'), logMtime);
if (stale) {
result.unread = stopped;
return result;
}
try {
for (const file of names.filter(f => f.endsWith('.jsonl') && !f.startsWith('_'))) {
try {
const agent = readAgentJsonl(path.join(agentDir, file));
// Idle agents never mark a session active.
if (agent.status === 'active' && isAgentFresh(agent)) {
result.hasActive = true;
result.hasRunning = true;
}
if (result.hasRunning) break;
} catch { /* skip invalid */ }
}
} catch { /* ignore */ }
result.unread = stopped && !result.hasRunning;
return result;
}
// #endregion
// #region LIVE_SESSIONS
function sessionMetaFor(sessionId) {
return loadSessionMetadata()[sessionId];
}
let liveSessionsCache = null;
let lastLiveSessionsScan = 0;
const LIVE_SESSIONS_TTL = 5000;
const replacedSessions = new Map();
function loadLiveSessions() {
const now = Date.now();
if (liveSessionsCache && now - lastLiveSessionsScan < LIVE_SESSIONS_TTL) return liveSessionsCache;
const prev = liveSessionsCache;
liveSessionsCache = readLiveSessions(SESSIONS_DIR);
lastLiveSessionsScan = now;
noteReplacedSessions(prev, liveSessionsCache, replacedSessions, now, SESSION_STALE_MS);
return liveSessionsCache;
}
// An open-but-idle interactive session keeps touching its JSONL (metadata-line
// rewrites), so mtime alone reads as activity for as long as the terminal stays
// open. The live-session registry the pi extension writes knows the real state — trust its
// 'idle' over the mtime. No registry entry (or any other status) falls back to
// the mtime rule.
function isRegistryIdle(sessionId) {
const live = loadLiveSessions().find(s => s.sessionId === sessionId);
return live?.status === 'idle';
}
function hasRecentLogActivity(sessionId, logAge) {
return logAge <= SESSION_STALE_MS && !isRegistryIdle(sessionId) && !replacedSessions.has(sessionId);
}
// Visibility-only recency: hasRecentLogActivity widened by the post-turn grace
// window (ungated by registry-idle). Drives whether a session appears in the
// active list — never the "active" status badges, which stay on hasRecentLog.
function hasVisibleLogActivity(sessionId, logAge) {
if (replacedSessions.has(sessionId)) return false;
return logAge <= SESSION_GRACE_MS || hasRecentLogActivity(sessionId, logAge);
}
// #endregion
// #region SHARED_STATE
// SSE clients for live updates
const clients = new Set();
// Cache for session metadata (refreshed periodically)
let sessionMetadataCache = {};
let lastMetadataRefresh = 0;
const METADATA_CACHE_TTL = 10000; // 10 seconds
// Watcher-driven invalidation. `change` events (append to existing jsonl) only
// dirty the one path so we can do a targeted refresh; `add` / `unlink` events
// are structural and force a full rescan.
const dirtyMetadataPaths = new Set();
let metadataNeedsFullScan = true;
// #endregion
// #region REQUEST_GUARDS
const SAFE_ID_RE = /^[a-zA-Z0-9_-]+$/;
function isSafeId(id) {
return typeof id === 'string' && id.length > 0 && id.length <= 128 && SAFE_ID_RE.test(id);
}
app.param('sessionId', (_req, res, next, val) => {
if (!isSafeId(val)) return res.status(400).json({ error: 'Invalid session ID' });
next();
});
app.param('taskId', (_req, res, next, val) => {
if (!isSafeId(val)) return res.status(400).json({ error: 'Invalid task ID' });
next();
});
app.use(SESSION_SHOW_PATH, showBodyParser());
app.use(ASK_PATH, askBodyParser());
app.use(SESSION_ASK_PATH, askBodyParser());
// Parse JSON bodies. A review of 50 comments at the field caps is about 450 kB.
app.use(express.json({ limit: '1mb' }));
// #endregion
// #region STATIC
// app.js reads localStorage synchronously at startup, before any fetch could deliver the
// namespace, so it is injected into the page instead of served from an endpoint.
const STORAGE_NS = storageNamespace(PI_AGENT_DIR);
const NS_DECL = 'window.__STORAGE_NS__ = null;';
const RAW_INDEX = readFileSync(path.join(__dirname, 'public', 'index.html'), 'utf8');
if (!RAW_INDEX.includes(NS_DECL)) throw new Error(`public/index.html is missing "${NS_DECL}"`);
const INDEX_HTML = RAW_INDEX.replace(NS_DECL, `window.__STORAGE_NS__ = ${JSON.stringify(STORAGE_NS)};`);
app.get(['/', '/index.html'], (_req, res) => {
res.setHeader('Cache-Control', 'no-cache');
res.type('html').send(INDEX_HTML);
});
// Serve static files
app.get('/sw.js', (_req, res) => {
res.setHeader('Cache-Control', 'no-cache');
res.sendFile(path.join(__dirname, 'public', 'sw.js'));
});
app.use(express.static(path.join(__dirname, 'public')));
// #endregion
// #region SESSION_LIST
const messageCache = new Map();
const MESSAGE_CACHE_TTL = 5000;
const MAX_CACHE_ENTRIES = 200;
const taskCountsCache = new Map();
const TASK_MAPS_DIR = path.join(AGENT_ACTIVITY_DIR, '_task-maps');
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function isUUID(s) { return UUID_RE.test(s); }
function evictStaleCache(cache) {
if (cache.size <= MAX_CACHE_ENTRIES) return;
const oldest = cache.keys().next().value;
if (oldest !== undefined) cache.delete(oldest);
}
let sessionToTaskListCache = null;
let lastTaskMapScan = 0;
const TASK_MAP_SCAN_TTL = 5000;
function loadAllTaskMaps() {
const now = Date.now();
if (sessionToTaskListCache && now - lastTaskMapScan < TASK_MAP_SCAN_TTL) return sessionToTaskListCache;
const sessionToList = {};
const listToSessions = {};
if (!existsSync(TASK_MAPS_DIR)) {
sessionToTaskListCache = { sessionToList, listToSessions };
lastTaskMapScan = now;
return sessionToTaskListCache;
}
try {
for (const file of readdirSync(TASK_MAPS_DIR).filter(f => f.endsWith('.json'))) {
const taskListName = file.replace(/\.json$/, '');
const mapPath = path.join(TASK_MAPS_DIR, file);
try {
const map = JSON.parse(readFileSync(mapPath, 'utf8'));
listToSessions[taskListName] = map;
for (const sessionId of Object.keys(map)) {
sessionToList[sessionId] = taskListName;
}
} catch { /* skip invalid */ }
}
} catch { /* ignore */ }
sessionToTaskListCache = { sessionToList, listToSessions };
lastTaskMapScan = now;
return sessionToTaskListCache;
}
function getCustomTaskDir(sessionId) {
const { sessionToList } = loadAllTaskMaps();
const taskListName = sessionToList[sessionId];
if (taskListName) {
const dir = path.join(TASKS_DIR, taskListName);
if (existsSync(dir)) return dir;
}
return null;
}
// Where a session's task files live. The custom-list and team lookups can both miss, and
// the fallback is the plain per-session dir -- every route that touches a task file needs
// that same resolution, so it lives in one place.
function taskDirFor(sessionId) {
return getCustomTaskDir(sessionId) || path.join(TASKS_DIR, sessionId);
}
function getTaskCounts(sessionPath) {
const cached = taskCountsCache.get(sessionPath);
if (cached) return cached;
const { completed, inProgress, pending, newestTaskMtime } = countTaskDir(sessionPath);
// Directory mtime bumps when task files are added/removed, so it dates an emptied dir
// (task list closed) that has no files left to date.
let dirMtime = 0;
try { dirMtime = statSync(sessionPath).mtimeMs; } catch (_) {}
const taskCount = completed + inProgress + pending;
const result = { taskCount, completed, inProgress, pending, newestTaskMtime, dirMtime };
taskCountsCache.set(sessionPath, result);
return result;
}
// A promise from loadFn is cached as is, so concurrent callers share one read, and a newer
// mtime starts no second read while it is pending: full-transcript scans stream for seconds.
function cachedByMtime(cache, cacheKey, filePath, loadFn, fallback) {
try {
const cached = cache.get(cacheKey);
if (cached && (cached.pending || Date.now() - cached.ts < MESSAGE_CACHE_TTL)) return cached.data;
const st = statSync(filePath);
if (cached && cached.mtime === st.mtimeMs) {
cached.ts = Date.now();
return cached.data;
}
const entry = { data: loadFn(), mtime: st.mtimeMs, ts: Date.now() };
if (typeof entry.data?.then === 'function') {
entry.pending = true;
entry.data = entry.data.catch(() => {
if (cache.get(cacheKey) === entry) cache.delete(cacheKey);
return fallback;
}).finally(() => {
entry.pending = false;
entry.ts = Date.now();
});
}
cache.set(cacheKey, entry);
evictStaleCache(cache);
return entry.data;
} catch (_) { return fallback; }
}
// Express 4 does not pass a rejected handler promise to next(), and Node 24 exits on it.
function asyncRoute(fn) {
return (req, res, next) => fn(req, res, next).catch(next);
}
const sessionDigestCache = new Map();
function getSessionDigest(jsonlPath) {
return cachedByMtime(sessionDigestCache, jsonlPath, jsonlPath, () => buildSessionDigest(jsonlPath), { progressMap: {}, terminated: new Map() });
}
async function getProgressMap(jsonlPath) {
return (await getSessionDigest(jsonlPath)).progressMap;
}
function readRecentMessages(jsonlPath, limit = 10) {
return cachedByMtime(messageCache, `${jsonlPath}:${limit}`, jsonlPath, () => _readRecentMessagesUncached(jsonlPath, limit), []);
}
/**
* Scan all project directories to find session JSONL files and extract slugs
*/
// Returns false when sessionId is unknown — caller must promote to full scan.
function refreshSessionMetadataPath(jsonlPath) {
const entry = sessionMetadataOf(jsonlPath);
if (!entry || !sessionMetadataCache[entry.sessionId]) return false;
sessionMetadataCache[entry.sessionId] = entry.meta;
return true;
}
// Null for a file that is not a pi session or has an unsafe id.
function sessionMetadataOf(jsonlPath) {
let info;
try {
info = readSessionInfoFromJsonl(jsonlPath);
} catch (_) {
return null;
}
if (!info.sessionId || !isSafeId(info.sessionId)) return null;
return {
sessionId: info.sessionId,
meta: {
project: info.projectPath || decodeProjectDir(path.basename(path.dirname(jsonlPath))),
cwd: info.cwd,
customTitle: info.customTitle,
jsonlPath,
lastReply: info.lastReply,
totals: info.totals,
scratchpadDir: info.scratchpadDir,
firstPrompt: info.firstPrompt,
title: info.title,
parentSessionPath: info.parentSessionPath,
created: info.createdAt,
},
};
}
function loadSessionMetadata() {
const now = Date.now();
if (!metadataNeedsFullScan && now - lastMetadataRefresh < METADATA_CACHE_TTL) {
if (dirtyMetadataPaths.size > 0) {
for (const p of dirtyMetadataPaths) {
if (!refreshSessionMetadataPath(p)) {
// Unknown sessionId — structural change snuck in. Promote to full.
metadataNeedsFullScan = true;
break;
}
}
dirtyMetadataPaths.clear();
if (!metadataNeedsFullScan) return sessionMetadataCache;
} else {
return sessionMetadataCache;
}
}
const metadata = {};
const scanInto = (opts) => {
for (const file of listSessionFiles(opts)) {
const entry = sessionMetadataOf(file);
if (entry) metadata[entry.sessionId] = entry.meta;
}
};
try {
scanInto(SESSION_OPTS);
// A project .pi/settings.json can move a cwd's sessions to a dir of its own; the cwds come
// from the headers just read and from the live registry, so a new root needs one more pass.
const live = loadLiveSessions();
const cwds = new Set([...Object.values(metadata), ...live].map((m) => m.cwd).filter(Boolean));
const known = reportedSessionDirs.size;
for (const s of live) if (s.sessionDir) reportedSessionDirs.add(s.sessionDir);
if (reportedSessionDirs.size !== known) writeJsonAtomicOrLog(SESSION_DIRS_FILE, [...reportedSessionDirs]);
const added = syncSessionRoots(cwds);
if (added.length) {
scanInto({ roots: added });
broadcast({ type: 'metadata-update' });
}
} catch (e) {
console.error('Error loading session metadata:', e);
}
sessionMetadataCache = metadata;
lastMetadataRefresh = now;
metadataNeedsFullScan = false;
dirtyMetadataPaths.clear();
return metadata;
}
function getSessionDisplayName(meta) {
return meta?.customTitle || meta?.title || null;
}
const getScratchpadDir = createScratchpadDirResolver({
root: SCRATCHPAD_ROOT,
// Transcripts record the 8.3 short form on Windows; path checks and the watcher need the long one.
toLong: realpathDeepest,
});
function buildSessionObject(id, meta, overrides = {}) {
const logStat = overrides._logStat || getSessionLogStat(meta);
const logMtime = logStat.mtime;
const logAge = logMtime ? Date.now() - logMtime : Infinity;
const worktree = worktrees.resolve(meta.project);
return {
id,
name: getSessionDisplayName(meta),
project: meta.project || null,
cwd: meta.cwd || null,
description: meta.description || null,
gitBranch: getGitBranch(meta.cwd || meta.project),
worktree,
customTitle: meta.customTitle || null,
firstPrompt: meta.firstPrompt || null,
taskCount: 0,
completed: 0,
inProgress: 0,
pending: 0,
createdAt: meta.created || null,
modifiedAt: overrides.modifiedAt || new Date(0).toISOString(),
hasMessages: logStat.hasMessages,
hasActiveAgents: false,
hasRunningAgents: false,
hasWaitingForUser: false,
unread: false,
hasRecentLog: hasRecentLogActivity(id, logAge),
hasRecentActivity: hasVisibleLogActivity(id, logAge),
jsonlPath: meta.jsonlPath || null,
tasksDir: null,
scratchpadDir: getScratchpadDir(id, meta),
...getContextFields(meta),
...overrides,
// Remove internal-only field
_logStat: undefined,
};
}
// #endregion
// #region SESSION_ROUTES
// API: List all sessions
app.get('/api/sessions', async (req, res) => {
// Prevent browser caching
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, private');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
try {
// Parse limit parameter (default: 20, "all" for unlimited)
const limitParam = req.query.limit || '20';
const limit = limitParam === 'all' ? null : parseInt(limitParam, 10);
// `pinned=` from a board page loaded before the server kept pins is ignored.
const includeIds = req.query.include ? new Set(req.query.include.split(',').filter(Boolean)) : new Set();
const pins = req.query.pins === 'off' ? {} : sessionPins.state().pins;
const pinnedIds = new Set(Object.keys(pins));
for (const id of includeIds) pinnedIds.add(id);
const activeFilter = req.query.filter === 'active';
const terminalIds = new Set(terminal.ids());
const metadata = loadSessionMetadata();
const sessionsMap = new Map();
// First, add sessions that have tasks directories
if (existsSync(TASKS_DIR)) {
const entries = readdirSync(TASKS_DIR, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory() && isUUID(entry.name)) {
const sessionPath = path.join(TASKS_DIR, entry.name);
const { taskCount, completed, inProgress, pending, newestTaskMtime, dirMtime } = getTaskCounts(sessionPath);
// Get metadata for this session
const meta = metadata[entry.name] || {};
const logStat = getSessionLogStat(meta);
const logMtime = logStat.mtime;
const logAge = logMtime ? Date.now() - logMtime : Infinity;
const stale = logAge > AGENT_STALE_MS;
const agentStatus = checkAgentStatus(path.join(AGENT_ACTIVITY_DIR, entry.name), stale, logMtime);
// Cheap-probe: when filter=active, skip expensive enrichment for inactive non-pinned sessions.
// Mirrors the post-filter predicate using only signals already computed above.
if (activeFilter && !pinnedIds.has(entry.name) && !terminalIds.has(entry.name)) {
const cheaplyActive = logStat.hasMessages && (
hasVisibleLogActivity(entry.name, logAge)
|| agentStatus.hasActive
|| !!agentStatus.waitingForUser
|| (pending > 0 || inProgress > 0)
);
if (!cheaplyActive) continue;
}
// Use newest of: task file mtime, JSONL mtime, directory mtime
let modifiedAt = (newestTaskMtime || new Date(dirMtime)).toISOString();
if (logMtime) {
const jsonlMtime = new Date(logMtime).toISOString();
if (jsonlMtime > modifiedAt) modifiedAt = jsonlMtime;
}
sessionsMap.set(entry.name, buildSessionObject(entry.name, meta, {
_logStat: logStat,
taskCount,
completed,
inProgress,
pending,
modifiedAt,
hasActiveAgents: agentStatus.hasActive,
hasRunningAgents: agentStatus.hasRunning,
hasWaitingForUser: !!agentStatus.waitingForUser,
unread: agentStatus.unread,
tasksDir: sessionPath,
}));
}
}
// Process custom task lists (non-UUID directories mapped via _task-maps)
const { listToSessions } = loadAllTaskMaps();
for (const [taskListName, map] of Object.entries(listToSessions)) {
const customTaskDir = path.join(TASKS_DIR, taskListName);
if (!existsSync(customTaskDir)) continue;
const counts = getTaskCounts(customTaskDir);
for (const [sessionId, info] of Object.entries(map)) {
const existing = sessionsMap.get(sessionId);
if (existing) {
Object.assign(existing, {
taskCount: counts.taskCount,
completed: counts.completed,
inProgress: counts.inProgress,
pending: counts.pending,
tasksDir: customTaskDir,
sharedTaskList: taskListName,
});
} else {
const meta = { ...(metadata[sessionId] || {}) };
if (!meta.project && info.project) meta.project = info.project;
const logStat = getSessionLogStat(meta);
const logMtime = logStat.mtime;
const logAge = logMtime ? Date.now() - logMtime : Infinity;
const stale = logAge > AGENT_STALE_MS;
const agentDir = path.join(AGENT_ACTIVITY_DIR, sessionId);
const agentStatus = checkAgentStatus(agentDir, stale, logMtime);
let modifiedAt = info.updatedAt || new Date(0).toISOString();
if (logMtime) {
const jsonlMtime = new Date(logMtime).toISOString();
if (jsonlMtime > modifiedAt) modifiedAt = jsonlMtime;
}
sessionsMap.set(sessionId, buildSessionObject(sessionId, meta, {
_logStat: logStat,
taskCount: counts.taskCount,
completed: counts.completed,
inProgress: counts.inProgress,
pending: counts.pending,
modifiedAt,
hasActiveAgents: agentStatus.hasActive,
hasRunningAgents: agentStatus.hasRunning,
hasWaitingForUser: !!agentStatus.waitingForUser,
unread: agentStatus.unread,
tasksDir: customTaskDir,
sharedTaskList: taskListName,
}));
}
}
}
}
// Add sessions from metadata that don't have task directories
for (const [sessionId, meta] of Object.entries(metadata)) {
if (!sessionsMap.has(sessionId)) {
const logStat = getSessionLogStat(meta);
const logMtime = logStat.mtime;
const logAge = logMtime ? Date.now() - logMtime : Infinity;
const stale = logAge > AGENT_STALE_MS;
const metaAgentDir = path.join(AGENT_ACTIVITY_DIR, sessionId);
const metaAgentStatus = checkAgentStatus(metaAgentDir, stale, logMtime);
// Cheap-probe: no tasks here (metadata-only), so active = recent log OR live agent.
if (activeFilter && !pinnedIds.has(sessionId) && !terminalIds.has(sessionId)) {
const cheaplyActive = logStat.hasMessages && (
hasVisibleLogActivity(sessionId, logAge) || metaAgentStatus.hasActive || !!metaAgentStatus.waitingForUser
);
if (!cheaplyActive) continue;
}
let modifiedAt = meta.created || null;
if (logMtime) {
const jsonlMtime = new Date(logMtime).toISOString();
if (!modifiedAt || jsonlMtime > modifiedAt) modifiedAt = jsonlMtime;
}
sessionsMap.set(sessionId, buildSessionObject(sessionId, meta, {
_logStat: logStat,
modifiedAt: modifiedAt || new Date(0).toISOString(),
hasActiveAgents: metaAgentStatus.hasActive,
hasRunningAgents: metaAgentStatus.hasRunning,
hasWaitingForUser: !!metaAgentStatus.waitingForUser,
unread: metaAgentStatus.unread,
}));
}
}
// Add sessions from agent-activity that have _waiting.json but no tasks/metadata
if (existsSync(AGENT_ACTIVITY_DIR)) {
try {
for (const dir of readdirSync(AGENT_ACTIVITY_DIR, { withFileTypes: true })) {
if (!dir.isDirectory() || sessionsMap.has(dir.name)) continue;
const agentDir = path.join(AGENT_ACTIVITY_DIR, dir.name);
if (!existsSync(path.join(agentDir, '_waiting.json'))) continue;
const meta = metadata[dir.name] || {};
const logStat = getSessionLogStat(meta);
const waiting = checkWaitingForUser(agentDir, logStat.mtime);
if (!waiting) continue;
sessionsMap.set(dir.name, buildSessionObject(dir.name, meta, {
_logStat: logStat,
modifiedAt: waiting.timestamp || new Date().toISOString(),
hasActiveAgents: true,
hasWaitingForUser: true,
}));
}
} catch { /* ignore */ }
}
// Ensure pinned sessions are in the map even if they weren't discovered
for (const pid of pinnedIds) {
if (sessionsMap.has(pid)) continue;
const meta = metadata[pid];
if (!meta) continue;
const pinnedLogStat = getSessionLogStat(meta);
const pinnedLogMtime = pinnedLogStat.mtime;
let modifiedAt = meta.created || null;
if (pinnedLogMtime) {
const jsonlMtime = new Date(pinnedLogMtime).toISOString();
if (!modifiedAt || jsonlMtime > modifiedAt) modifiedAt = jsonlMtime;
}
sessionsMap.set(pid, buildSessionObject(pid, meta, {
_logStat: pinnedLogStat,
modifiedAt: modifiedAt || new Date(0).toISOString(),
}));
}
// The sidebar's Active rule (getFilteredSessions in public/app.js); the CLI reads `active`
// instead of keeping its own copy. Pinned IDs bypass the filter.
for (const [id, s] of sessionsMap) {
s.active = terminalIds.has(id) || !!(s.hasMessages && (
(!s.sharedTaskList && (s.pending > 0 || s.inProgress > 0))
|| s.hasActiveAgents
|| s.hasWaitingForUser
|| s.hasRecentActivity
));
if (activeFilter && !s.active && !pinnedIds.has(id)) sessionsMap.delete(id);