officepals 0.0.0-stage → 0.3.1

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/src/stats.mjs ADDED
@@ -0,0 +1,72 @@
1
+ // Daily stats, kept on disk (~/.officepals/stats.json) so they survive a
2
+ // reload and a restart: how often and how long your agents waited on you, and
3
+ // how many turns they finished. Counts only; nothing about what was done.
4
+ import * as fs from 'node:fs';
5
+ import * as path from 'node:path';
6
+
7
+ /** Days kept on disk. */
8
+ export const KEEP_DAYS = 60;
9
+
10
+ const pad = (n) => String(n).padStart(2, '0');
11
+
12
+ /** The local calendar day of a time, "2026-11-30". */
13
+ export function dayKey(ts) {
14
+ const d = new Date(ts);
15
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
16
+ }
17
+
18
+ const emptyDay = () => ({ waits: 0, waitMs: 0, longestWaitMs: 0, turns: 0, workMs: 0 });
19
+
20
+ export function createStats(days = {}) {
21
+ return { days };
22
+ }
23
+
24
+ /** Add a fact from the session state: a wait that ended, or a turn that did. */
25
+ export function record(stats, fact, ts) {
26
+ const key = dayKey(ts);
27
+ const d = (stats.days[key] ??= emptyDay());
28
+ const ms = Math.max(0, Math.round(Number(fact.ms) || 0));
29
+ if (fact.type === 'wait') {
30
+ d.waits++;
31
+ d.waitMs += ms;
32
+ d.longestWaitMs = Math.max(d.longestWaitMs, ms);
33
+ } else if (fact.type === 'turn') {
34
+ d.turns++;
35
+ d.workMs += ms;
36
+ } else {
37
+ return false;
38
+ }
39
+ const keys = Object.keys(stats.days).sort();
40
+ for (const old of keys.slice(0, Math.max(0, keys.length - KEEP_DAYS))) delete stats.days[old];
41
+ return true;
42
+ }
43
+
44
+ /** Today's numbers (zeros on a fresh day), with the day they're for. */
45
+ export function today(stats, ts) {
46
+ const key = dayKey(ts);
47
+ return { day: key, ...(stats.days[key] ?? emptyDay()) };
48
+ }
49
+
50
+ /** Read the stats file; anything missing or odd starts afresh. */
51
+ export function loadStats(file) {
52
+ try {
53
+ const data = JSON.parse(fs.readFileSync(file, 'utf-8'));
54
+ const days = {};
55
+ for (const [key, d] of Object.entries(data?.days ?? {})) {
56
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(key) || !d || typeof d !== 'object') continue;
57
+ const day = emptyDay();
58
+ for (const k of Object.keys(day)) if (Number.isFinite(d[k]) && d[k] >= 0) day[k] = d[k];
59
+ days[key] = day;
60
+ }
61
+ return createStats(days);
62
+ } catch {
63
+ return createStats();
64
+ }
65
+ }
66
+
67
+ export function saveStats(file, stats) {
68
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
69
+ const tmp = `${file}.tmp`;
70
+ fs.writeFileSync(tmp, JSON.stringify({ version: 1, days: stats.days }, null, 2) + '\n', { mode: 0o600 });
71
+ fs.renameSync(tmp, file);
72
+ }
package/src/title.mjs ADDED
@@ -0,0 +1,100 @@
1
+ // The title Claude Code shows for a session, read from its transcript (JSONL).
2
+ //
3
+ // Claude Code appends title records as a conversation goes on:
4
+ // {"type":"custom-title","customTitle":"…"} — the user's /rename, which wins
5
+ // {"type":"ai-title","aiTitle":"…"} — the one it generates
6
+ // The newest is near the end, so only the file's tail is read (then its head,
7
+ // for a session whose tail is one long tool result). Prompts are never read.
8
+ import * as fs from 'node:fs';
9
+ import * as os from 'node:os';
10
+ import * as path from 'node:path';
11
+
12
+ import { codexIndexPath } from './paths.mjs';
13
+
14
+ const SCAN_BYTES = 128 * 1024;
15
+ const MAX_TITLE = 40;
16
+
17
+ /** Only transcripts under ~/.claude/projects are read (override for tests).
18
+ * Windows paths compare without regard to case or slash direction. */
19
+ export function transcriptAllowed(file, root = process.env.OFFICEPALS_TRANSCRIPTS || path.join(os.homedir(), '.claude', 'projects'), p = path) {
20
+ if (typeof file !== 'string' || !file.toLowerCase().endsWith('.jsonl')) return false;
21
+ const fold = p.sep === '\\' ? (s) => s.toLowerCase() : (s) => s;
22
+ return fold(p.resolve(file)).startsWith(fold(p.resolve(root) + p.sep));
23
+ }
24
+
25
+ function titlesIn(chunk) {
26
+ const found = {};
27
+ for (const line of chunk.split('\n')) {
28
+ if (!line.includes('itle"')) continue;
29
+ let rec;
30
+ try {
31
+ rec = JSON.parse(line);
32
+ } catch {
33
+ continue; // a line cut by the read window
34
+ }
35
+ if (rec?.type === 'custom-title' && typeof rec.customTitle === 'string' && rec.customTitle.trim()) found.custom = rec.customTitle;
36
+ if (rec?.type === 'ai-title' && typeof rec.aiTitle === 'string' && rec.aiTitle.trim()) found.ai = rec.aiTitle;
37
+ }
38
+ return found;
39
+ }
40
+
41
+ async function readRange(fh, start, end) {
42
+ const length = Math.max(0, end - start);
43
+ const buf = Buffer.alloc(length);
44
+ await fh.read(buf, 0, length, start);
45
+ return buf.toString('utf-8');
46
+ }
47
+
48
+ /** One line, at most MAX_TITLE characters; null when empty. */
49
+ function clipTitle(raw) {
50
+ const title = String(raw).replace(/\s+/g, ' ').trim();
51
+ if (!title) return null;
52
+ return title.length > MAX_TITLE ? title.slice(0, MAX_TITLE - 1) + '…' : title;
53
+ }
54
+
55
+ /** The session's title, or null. Never throws. */
56
+ export async function readTitle(file) {
57
+ if (!transcriptAllowed(file)) return null;
58
+ let fh;
59
+ try {
60
+ fh = await fs.promises.open(file, 'r');
61
+ const { size } = await fh.stat();
62
+ const late = titlesIn(await readRange(fh, Math.max(0, size - SCAN_BYTES), size));
63
+ const early = !late.custom && size > SCAN_BYTES ? titlesIn(await readRange(fh, 0, SCAN_BYTES)) : {};
64
+ return clipTitle(late.custom ?? early.custom ?? late.ai ?? early.ai ?? '');
65
+ } catch {
66
+ return null;
67
+ } finally {
68
+ await fh?.close();
69
+ }
70
+ }
71
+
72
+ /**
73
+ * A Codex session's title: the newest "thread_name" for its id in Codex's
74
+ * session index (~/.codex/session_index.jsonl), read from the end. Null when
75
+ * there's none.
76
+ */
77
+ export async function readCodexTitle(sessionId, file = codexIndexPath()) {
78
+ if (typeof sessionId !== 'string' || !sessionId) return null;
79
+ let fh;
80
+ try {
81
+ fh = await fs.promises.open(file, 'r');
82
+ const { size } = await fh.stat();
83
+ const chunk = await readRange(fh, Math.max(0, size - SCAN_BYTES), size);
84
+ let title = null;
85
+ for (const line of chunk.split('\n')) {
86
+ if (!line.includes(sessionId)) continue;
87
+ try {
88
+ const rec = JSON.parse(line);
89
+ if (rec?.id === sessionId && typeof rec.thread_name === 'string' && rec.thread_name.trim()) title = rec.thread_name;
90
+ } catch {
91
+ // a line cut by the read window
92
+ }
93
+ }
94
+ return title ? clipTitle(title) : null;
95
+ } catch {
96
+ return null;
97
+ } finally {
98
+ await fh?.close();
99
+ }
100
+ }