@zaferyalcin/agent-office 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/src/util.js ADDED
@@ -0,0 +1,139 @@
1
+ 'use strict';
2
+ // Small shared helpers. Everything here is synchronous, read-only and dependency free.
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ const SEC = 1e3, MIN = 60e3, HOUR = 3600e3, DAY = 24 * HOUR;
7
+
8
+ const oneLine = (s) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim();
9
+ const cut = (s, n) => { s = String(s == null ? '' : s); return s.length > n ? s.slice(0, n - 1) + '…' : s; };
10
+ const short = (s, n) => cut(oneLine(s), n);
11
+ const stripBom = (s) => (s.charCodeAt(0) === 0xfeff ? s.slice(1) : s);
12
+ function tryJSON(s) { try { return JSON.parse(s); } catch (e) { return undefined; } }
13
+ function statOrNull(f) { try { return fs.statSync(f); } catch (e) { return null; } }
14
+ function listDir(d) { try { return fs.readdirSync(d, { withFileTypes: true }); } catch (e) { return null; } }
15
+ function readText(f, max) {
16
+ try {
17
+ if (!max) return stripBom(fs.readFileSync(f, 'utf8'));
18
+ const fd = fs.openSync(f, 'r');
19
+ try { const b = Buffer.alloc(max); const n = fs.readSync(fd, b, 0, max, 0); return stripBom(b.slice(0, n).toString('utf8')); }
20
+ finally { fs.closeSync(fd); }
21
+ } catch (e) { return null; }
22
+ }
23
+ function readJSONFile(f) { const t = readText(f); return t == null ? null : tryJSON(t.trim()) || null; }
24
+ function tailText(f, bytes) {
25
+ const st = statOrNull(f); if (!st) return null;
26
+ try {
27
+ const fd = fs.openSync(f, 'r');
28
+ try {
29
+ const n = Math.min(bytes, st.size), b = Buffer.alloc(n);
30
+ fs.readSync(fd, b, 0, n, st.size - n);
31
+ let s = b.toString('utf8'); if (n < st.size) s = s.slice(s.indexOf('\n') + 1);
32
+ return stripBom(s);
33
+ } finally { fs.closeSync(fd); }
34
+ } catch (e) { return null; }
35
+ }
36
+ function firstLine(s) {
37
+ const lines = String(s || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
38
+ return lines[0] || '';
39
+ }
40
+
41
+ // Incremental JSONL reader: each update() reads only the bytes appended since the last call and
42
+ // hands every complete line to onLine(text, offset, length). A half-written last line is kept for next time.
43
+ // `filter` (optional) is a cheap substring test run before the caller parses the line.
44
+ class JsonlTail {
45
+ constructor(file, opts) {
46
+ this.file = file; this.size = 0; this.mtimeMs = 0; this.offset = 0; this.rest = null;
47
+ this.maxFirst = (opts && opts.maxFirst) || 0; // first read: only the last N bytes of a larger file
48
+ this.partial = false; this.error = null;
49
+ // optional: a regex tested against the first 64 bytes of each line; matching lines are skipped unread
50
+ this.skipHead = (opts && opts.skipHead) || null;
51
+ // optional: lines longer than maxLine go to onBig(buffer, start, end) instead of being decoded
52
+ this.maxLine = (opts && opts.maxLine) || 0; this.onBig = (opts && opts.onBig) || null;
53
+ }
54
+ // returns false when nothing changed, 'reset' when the file was rewritten (caller must clear its state), true otherwise
55
+ update(onLine) {
56
+ const st = statOrNull(this.file);
57
+ if (!st) { this.error = 'missing'; return false; }
58
+ this.error = null;
59
+ if (st.size === this.size && st.mtimeMs === this.mtimeMs) return false;
60
+ let result = true;
61
+ if (st.size < this.offset) { this.offset = 0; this.rest = null; this.partial = false; result = 'reset'; }
62
+ let fd;
63
+ try { fd = fs.openSync(this.file, 'r'); } catch (e) { this.error = e.code; return false; }
64
+ try {
65
+ let start = this.offset, skipFirst = false;
66
+ if (start === 0 && this.maxFirst && st.size > this.maxFirst) { start = st.size - this.maxFirst; this.partial = true; skipFirst = true; }
67
+ // read in 1 MB chunks so a large file never needs one large buffer
68
+ const CHUNK = 1 << 20, buf = Buffer.alloc(Math.min(CHUNK, Math.max(1, st.size - start)));
69
+ let carry = skipFirst ? null : this.rest, carryBase = skipFirst ? start : start - (this.rest ? this.rest.length : 0);
70
+ let pos = start;
71
+ while (pos < st.size) {
72
+ const n = fs.readSync(fd, buf, 0, Math.min(buf.length, st.size - pos), pos);
73
+ if (!n) break;
74
+ let data = carry ? Buffer.concat([carry, buf.subarray(0, n)]) : buf.subarray(0, n);
75
+ let p = 0;
76
+ if (skipFirst) { const nl = data.indexOf(10); if (nl < 0) { carry = null; carryBase = pos + n; pos += n; continue; } p = nl + 1; skipFirst = false; }
77
+ for (;;) {
78
+ const nl = data.indexOf(10, p); if (nl < 0) break;
79
+ let end = nl; if (end > p && data[end - 1] === 13) end--;
80
+ if (end > p && !(this.skipHead && this.skipHead.test(data.toString('latin1', p, Math.min(end, p + 64))))) {
81
+ if (this.onBig && end - p > this.maxLine) this.onBig(data, p, end);
82
+ else onLine(data.toString('utf8', p, end), carryBase + p, end - p);
83
+ }
84
+ p = nl + 1;
85
+ }
86
+ carry = p < data.length ? Buffer.from(data.subarray(p)) : null;
87
+ carryBase += p;
88
+ pos += n;
89
+ }
90
+ if (carry && tryJSON(carry.toString('utf8'))) { onLine(carry.toString('utf8'), carryBase, carry.length); carry = null; carryBase = st.size; }
91
+ this.rest = carry;
92
+ this.offset = st.size;
93
+ } catch (e) { this.error = e.code || String(e); }
94
+ finally { fs.closeSync(fd); }
95
+ this.size = st.size; this.mtimeMs = st.mtimeMs;
96
+ return result;
97
+ }
98
+ readAt(off, len) {
99
+ try {
100
+ const fd = fs.openSync(this.file, 'r');
101
+ try { const b = Buffer.alloc(len); fs.readSync(fd, b, 0, len, off); return b.toString('utf8'); } finally { fs.closeSync(fd); }
102
+ } catch (e) { return null; }
103
+ }
104
+ }
105
+
106
+ // Model name -> vendor. Unknown names land in "other" and still get their own row in the UI.
107
+ function vendorOf(model) {
108
+ const m = String(model || '').toLowerCase();
109
+ if (!m) return 'other';
110
+ if (m.includes('claude') || /^(opus|sonnet|haiku|fable)/.test(m)) return 'anthropic';
111
+ if (/^(gpt|o\d|codex|chatgpt|davinci)/.test(m) || m.includes('gpt-')) return 'openai';
112
+ if (m.includes('gemini') || m.includes('gemma') || /neon|carbon|hydrogen/.test(m)) return 'google';
113
+ if (m.includes('grok')) return 'xai';
114
+ if (m.includes('mistral') || m.includes('codestral') || m.includes('devstral')) return 'mistral';
115
+ if (m.includes('deepseek')) return 'deepseek';
116
+ if (m.includes('qwen')) return 'qwen';
117
+ if (m.includes('llama')) return 'meta';
118
+ return 'other';
119
+ }
120
+
121
+ // Rolling token samples kept per session: [ts, model, total, in, cache, out]. Only the last `keepMs` are kept.
122
+ class Samples {
123
+ constructor() { this.list = []; }
124
+ add(ts, model, tin, tcache, tout) {
125
+ if (!ts) return;
126
+ this.list.push([ts, model || 'unknown', tin + tcache + tout, tin, tcache, tout]);
127
+ }
128
+ prune(from) {
129
+ if (!this.list.length || this.list[0][0] >= from) return;
130
+ this.list.sort((a, b) => a[0] - b[0]);
131
+ let k = 0; while (k < this.list.length && this.list[k][0] < from) k++;
132
+ this.list.splice(0, k);
133
+ }
134
+ }
135
+
136
+ module.exports = {
137
+ SEC, MIN, HOUR, DAY, oneLine, cut, short, stripBom, tryJSON, statOrNull, listDir, readText, readJSONFile,
138
+ tailText, firstLine, JsonlTail, vendorOf, Samples, path,
139
+ };
@@ -0,0 +1,112 @@
1
+ 'use strict';
2
+ // Turns a working directory into a workspace: the git repository it belongs to (worktrees of one repository
3
+ // share a workspace), the branch checked out there, and a display name. Results are cached for a short while.
4
+ const path = require('path');
5
+ const { readText, statOrNull } = require('./util');
6
+
7
+ const cache = new Map(); // dir -> { at, info }
8
+ const TTL = 15e3;
9
+
10
+ function norm(p) {
11
+ if (!p) return '';
12
+ let s = path.resolve(String(p));
13
+ if (process.platform === 'win32') s = s.replace(/\//g, '\\');
14
+ return s.replace(/[\\/]+$/, '') || s;
15
+ }
16
+ const key = (p) => (process.platform === 'win32' ? p.toLowerCase() : p);
17
+
18
+ function readHead(gitDir) {
19
+ const head = readText(path.join(gitDir, 'HEAD'), 512);
20
+ if (!head) return '';
21
+ const m = /^ref:\s*refs\/heads\/(.+)$/m.exec(head.trim());
22
+ return m ? m[1].trim() : head.trim().slice(0, 8); // detached: short sha
23
+ }
24
+
25
+ // Walks up from `dir` looking for .git (a folder, or a file pointing at a worktree's git dir).
26
+ function gitInfo(dir) {
27
+ let cur = dir;
28
+ for (let i = 0; i < 40 && cur; i++) {
29
+ const g = path.join(cur, '.git');
30
+ const st = statOrNull(g);
31
+ if (st && st.isDirectory()) return { top: cur, common: cur, branch: readHead(g) };
32
+ if (st && st.isFile()) {
33
+ const t = readText(g, 1024) || '';
34
+ const m = /gitdir:\s*(.+)/.exec(t);
35
+ if (m) {
36
+ const gd = path.resolve(cur, m[1].trim());
37
+ // <repo>/.git/worktrees/<name> -> <repo>
38
+ const wm = /^(.*)[\\/]\.git[\\/]worktrees[\\/][^\\/]+$/.exec(gd);
39
+ const commonDirFile = readText(path.join(gd, 'commondir'), 512);
40
+ let common = wm ? wm[1] : cur;
41
+ if (!wm && commonDirFile) common = path.dirname(path.resolve(gd, commonDirFile.trim()));
42
+ return { top: cur, common, branch: readHead(gd) };
43
+ }
44
+ }
45
+ const up = path.dirname(cur);
46
+ if (up === cur) break;
47
+ cur = up;
48
+ }
49
+ return null;
50
+ }
51
+
52
+ // { id, name, path, branch, top }
53
+ function resolveWorkspace(dir) {
54
+ const d = norm(dir);
55
+ if (!d || d.length < 3) return null;
56
+ const k = key(d);
57
+ const c = cache.get(k);
58
+ if (c && Date.now() - c.at < TTL) return c.info;
59
+ let info;
60
+ const st = statOrNull(d);
61
+ const probe = st && st.isDirectory() ? d : path.dirname(d);
62
+ const g = gitInfo(probe);
63
+ if (g) info = { id: key(norm(g.common)), name: path.basename(g.common), path: norm(g.common), top: norm(g.top), branch: g.branch, git: true };
64
+ else info = { id: k, name: path.basename(d) || d, path: d, top: d, branch: '' };
65
+ cache.set(k, { at: Date.now(), info });
66
+ if (cache.size > 2000) cache.clear();
67
+ return info;
68
+ }
69
+
70
+ // Folders that belong to the agent tools themselves, never to the work.
71
+ const os = require('os');
72
+ const INTERNAL_DIRS = ['.gemini', '.claude', '.codex', '.cursor', 'AppData'];
73
+ function internalPrefixes() {
74
+ const home = os.homedir();
75
+ return INTERNAL_DIRS.map((d) => path.join(home, d).toLowerCase());
76
+ }
77
+
78
+ // Picks the most likely working folder from a list of absolute paths a session touched.
79
+ // Paths may carry trailing text (they come from free-form tool arguments), so each is shortened to the
80
+ // longest prefix that exists. Folders inside a git repository count five times as much as loose folders.
81
+ function guessDir(paths) {
82
+ const internal = internalPrefixes();
83
+ const isInternal = (p) => {
84
+ const lp = (process.platform === 'win32' ? p.replace(/\//g, '\\') : p).toLowerCase();
85
+ return internal.some((d) => lp.startsWith(d));
86
+ };
87
+ const counts = new Map(), done = new Map();
88
+ for (let p of paths) {
89
+ if (!p || !/^([a-zA-Z]:[\\/]|\/)/.test(p)) continue;
90
+ p = p.replace(/[\s.,;:)\]}'"`]+$/, '');
91
+ if (p.length < 4 || isInternal(p)) continue;
92
+ let top = done.get(p);
93
+ if (top === undefined) {
94
+ let q = p, st = statOrNull(q);
95
+ for (let i = 0; !st && i < 12 && q.length > 3; i++) { q = path.dirname(q); st = statOrNull(q); }
96
+ top = null;
97
+ if (st && q.length > 3) {
98
+ const w = resolveWorkspace(st.isDirectory() ? q : path.dirname(q));
99
+ if (w && w.top.length > 3) top = w;
100
+ }
101
+ done.set(p, top);
102
+ }
103
+ if (!top) continue;
104
+ const c = counts.get(top.top) || { n: 0, top: top.top };
105
+ c.n += top.git ? 1 : 0.2; counts.set(top.top, c);
106
+ }
107
+ let best = null;
108
+ for (const c of counts.values()) if (!best || c.n > best.n) best = c;
109
+ return best ? best.top : '';
110
+ }
111
+
112
+ module.exports = { resolveWorkspace, guessDir, norm };