sideby 0.19.1 → 0.20.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 +7 -4
- package/ai-tasks.json +28 -0
- package/dist/build.json +1 -1
- package/dist/src/cli/commands.d.ts +22 -1
- package/dist/src/cli/commands.js +815 -21
- package/dist/src/cli/format.d.ts +4 -0
- package/dist/src/cli/format.js +42 -4
- package/dist/src/cli/json-schemas.js +334 -4
- package/dist/src/cli/main.js +159 -13
- package/dist/src/core/accounts.d.ts +6 -0
- package/dist/src/core/accounts.js +12 -0
- package/dist/src/core/autostart.d.ts +11 -0
- package/dist/src/core/autostart.js +32 -5
- package/dist/src/core/browser-profiles.d.ts +23 -2
- package/dist/src/core/browser-profiles.js +148 -37
- package/dist/src/core/claude-settings-file.d.ts +18 -0
- package/dist/src/core/claude-settings-file.js +52 -3
- package/dist/src/core/config.d.ts +5 -0
- package/dist/src/core/config.js +12 -1
- package/dist/src/core/edit-settings.d.ts +7 -0
- package/dist/src/core/edit-settings.js +10 -5
- package/dist/src/core/history-group.d.ts +28 -0
- package/dist/src/core/history-group.js +47 -0
- package/dist/src/core/history-index.d.ts +145 -0
- package/dist/src/core/history-index.js +447 -0
- package/dist/src/core/history-project.d.ts +13 -0
- package/dist/src/core/history-project.js +87 -0
- package/dist/src/core/history.d.ts +210 -0
- package/dist/src/core/history.js +952 -0
- package/dist/src/core/inbound.d.ts +62 -0
- package/dist/src/core/inbound.js +215 -0
- package/dist/src/core/launch.d.ts +9 -1
- package/dist/src/core/launch.js +58 -24
- package/dist/src/core/live-sessions-copy.d.ts +5 -0
- package/dist/src/core/live-sessions-copy.js +46 -0
- package/dist/src/core/live-sessions-procs.d.ts +89 -0
- package/dist/src/core/live-sessions-procs.js +296 -0
- package/dist/src/core/live-sessions-title.d.ts +28 -0
- package/dist/src/core/live-sessions-title.js +80 -0
- package/dist/src/core/live-sessions.d.ts +68 -0
- package/dist/src/core/live-sessions.js +163 -0
- package/dist/src/core/login-check.d.ts +15 -0
- package/dist/src/core/login-check.js +32 -0
- package/dist/src/core/messages.d.ts +83 -0
- package/dist/src/core/messages.js +433 -0
- package/dist/src/core/project-categories.d.ts +14 -0
- package/dist/src/core/project-categories.js +48 -0
- package/dist/src/core/quota-fetch.d.ts +3 -3
- package/dist/src/core/quota-fetch.js +5 -5
- package/dist/src/core/quota-levels.d.ts +5 -0
- package/dist/src/core/quota-levels.js +5 -0
- package/dist/src/core/remote-control.d.ts +2 -0
- package/dist/src/core/remote-control.js +34 -59
- package/dist/src/core/run-link.d.ts +76 -0
- package/dist/src/core/run-link.js +245 -0
- package/dist/src/core/same-login.d.ts +4 -3
- package/dist/src/core/same-login.js +10 -7
- package/dist/src/core/session-select.d.ts +31 -0
- package/dist/src/core/session-select.js +44 -0
- package/dist/src/families/browser.d.ts +7 -18
- package/dist/src/families/browser.js +19 -8
- package/dist/src/families/claude/deliver.d.ts +2 -0
- package/dist/src/families/claude/deliver.js +43 -0
- package/dist/src/families/claude/history.d.ts +2 -0
- package/dist/src/families/claude/history.js +192 -0
- package/dist/src/families/claude/live-sessions.d.ts +13 -0
- package/dist/src/families/claude/live-sessions.js +117 -0
- package/dist/src/families/claude/messaging.d.ts +69 -0
- package/dist/src/families/claude/messaging.js +165 -0
- package/dist/src/families/claude/mod.d.ts +26 -0
- package/dist/src/families/claude/mod.js +105 -0
- package/dist/src/families/claude/session-files.d.ts +21 -0
- package/dist/src/families/claude/session-files.js +54 -0
- package/dist/src/families/codex/deliver.d.ts +5 -0
- package/dist/src/families/codex/deliver.js +76 -0
- package/dist/src/families/codex/history.d.ts +7 -0
- package/dist/src/families/codex/history.js +174 -0
- package/dist/src/families/codex/index.js +2 -0
- package/dist/src/families/codex/live-sessions.d.ts +12 -0
- package/dist/src/families/codex/live-sessions.js +193 -0
- package/dist/src/families/codex/quota.d.ts +3 -0
- package/dist/src/families/codex/quota.js +123 -0
- package/dist/src/families/codex/rate-limits.js +2 -0
- package/dist/src/families/codex/rollout.js +1 -1
- package/dist/src/families/grok/browser.d.ts +3 -0
- package/dist/src/families/grok/browser.js +5 -0
- package/dist/src/families/grok/history.d.ts +2 -0
- package/dist/src/families/grok/history.js +157 -0
- package/dist/src/families/grok/live-sessions.d.ts +4 -0
- package/dist/src/families/grok/live-sessions.js +80 -0
- package/dist/src/families/grok/login-key.d.ts +14 -0
- package/dist/src/families/grok/login-key.js +37 -0
- package/dist/src/families/history.d.ts +20 -0
- package/dist/src/families/history.js +81 -0
- package/dist/src/families/live-sessions.d.ts +26 -0
- package/dist/src/families/live-sessions.js +9 -0
- package/dist/src/families/login-keys.js +5 -1
- package/dist/src/families/messaging.d.ts +27 -0
- package/dist/src/families/messaging.js +6 -0
- package/dist/src/families/pi/history.d.ts +2 -0
- package/dist/src/families/pi/history.js +124 -0
- package/dist/src/families/pi/live-sessions.d.ts +2 -0
- package/dist/src/families/pi/live-sessions.js +70 -0
- package/dist/src/families/shared/history-text.d.ts +65 -0
- package/dist/src/families/shared/history-text.js +261 -0
- package/dist/src/menubar/hotkey.d.ts +86 -0
- package/dist/src/menubar/hotkey.js +159 -0
- package/dist/src/menubar/script.d.ts +2 -0
- package/dist/src/menubar/script.js +118 -22
- package/dist/src/menubar/snapshot.d.ts +8 -4
- package/dist/src/menubar/snapshot.js +45 -13
- package/dist/src/menubar/strings.d.ts +24 -6
- package/dist/src/menubar/strings.js +24 -6
- package/dist/src/panel/handler.d.ts +69 -0
- package/dist/src/panel/handler.js +686 -15
- package/dist/src/panel/i18n.d.ts +304 -3
- package/dist/src/panel/i18n.js +620 -18
- package/dist/src/panel/orca.d.ts +48 -0
- package/dist/src/panel/orca.js +153 -0
- package/dist/src/panel/page-logic.d.ts +255 -13
- package/dist/src/panel/page-logic.js +483 -1
- package/dist/src/panel/page-script.js +2260 -204
- package/dist/src/panel/page-styles.js +404 -32
- package/dist/src/panel/page.js +1 -0
- package/dist/src/plugins/check.js +16 -4
- package/dist/src/plugins/loader.d.ts +8 -1
- package/dist/src/plugins/loader.js +72 -7
- package/dist/src/runtime.d.ts +5 -0
- package/dist/src/runtime.js +27 -5
- package/dist/src/types.d.ts +116 -1
- package/dist/testing/index.d.ts +5 -0
- package/dist/testing/index.js +5 -0
- package/mods/claude/.claude-plugin/plugin.json +7 -0
- package/mods/claude/hooks/hooks.json +1 -0
- package/mods/claude/hooks/register.js +261 -0
- package/package.json +5 -2
- package/schemas/autostart.json +74 -1
- package/schemas/browser-set.json +110 -0
- package/schemas/browser.json +22 -2
- package/schemas/config.json +26 -1
- package/schemas/history-index.json +209 -0
- package/schemas/history-projects.json +133 -0
- package/schemas/history-show.json +275 -0
- package/schemas/history.json +410 -0
- package/schemas/menubar-hotkey.json +139 -0
- package/schemas/menubar-snapshot.json +36 -2
- package/schemas/menubar.json +74 -1
- package/schemas/messages-inbound.json +258 -0
- package/schemas/messages.json +164 -0
- package/schemas/send.json +165 -0
- package/schemas/sessions-copy.json +113 -0
- package/schemas/sessions-open-run.json +97 -0
- package/schemas/sessions.json +237 -0
- package/skills/sideby/SKILL.md +10 -5
- package/skills/sideby/references/accounts.md +11 -0
- package/skills/sideby/references/ai-tasks.md +17 -1
- package/skills/sideby/references/panel.md +6 -4
- package/skills/sideby/references/quota.md +2 -2
- package/skills/sideby/references/sessions.md +79 -0
|
@@ -0,0 +1,952 @@
|
|
|
1
|
+
// Session History (spec §3.33, ADR-0042): every Session of every Account, grouped by Project and searchable. The
|
|
2
|
+
// History Index keeps what the Family readers parse; this module keeps it in step with the Hosts' files and answers
|
|
3
|
+
// listings, searches, one Session's messages and the tool-output scan. Read-only towards every Host directory.
|
|
4
|
+
import { statSync } from 'node:fs';
|
|
5
|
+
import { realpath, stat } from 'node:fs/promises';
|
|
6
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
7
|
+
import { historyReader } from '../families/history.js';
|
|
8
|
+
import { cutText, SESSION_TEXT_MAX } from '../families/shared/history-text.js';
|
|
9
|
+
import { UserError } from './errors.js';
|
|
10
|
+
import { DAY_GROUPS, dayGroup, GROUP_BYS, orderGroups, } from './history-group.js';
|
|
11
|
+
import { HistoryIndex, } from './history-index.js';
|
|
12
|
+
import { ProjectResolver, projectNames } from './history-project.js';
|
|
13
|
+
import { accountLabels, hostResumeArgs, liveKey, referenceText } from './live-sessions.js';
|
|
14
|
+
const DAY = 86_400_000;
|
|
15
|
+
const HALF_LIFE = 7 * DAY;
|
|
16
|
+
const SYNC_EVERY_MS = 5_000;
|
|
17
|
+
const PARSE_AT_ONCE = 4;
|
|
18
|
+
const STATES = new Map();
|
|
19
|
+
/** Per index file: the last close or delete in flight. A new State opens nothing before it ends. */
|
|
20
|
+
const BARRIER = new Map();
|
|
21
|
+
/** Makes `work` the barrier of `key` until it ends. */
|
|
22
|
+
function fence(key, work) {
|
|
23
|
+
const done = work.then(() => { }, () => { });
|
|
24
|
+
BARRIER.set(key, done);
|
|
25
|
+
void done.then(() => {
|
|
26
|
+
if (BARRIER.get(key) === done)
|
|
27
|
+
BARRIER.delete(key);
|
|
28
|
+
});
|
|
29
|
+
return done;
|
|
30
|
+
}
|
|
31
|
+
/** What a Session id may look like: the Hosts use UUIDs and similar plain names. */
|
|
32
|
+
const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
33
|
+
export const historyIndexPath = (rt) => join(rt.paths.stateDir, 'history', 'index.sqlite');
|
|
34
|
+
const enabled = (rt) => rt.config.history?.index !== false;
|
|
35
|
+
/** `dev:ino` of the file at `path`, or '' when there is none. */
|
|
36
|
+
function fileIdOf(path) {
|
|
37
|
+
try {
|
|
38
|
+
const st = statSync(path);
|
|
39
|
+
return `${st.dev}:${st.ino}`;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return '';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function stateOf(rt) {
|
|
46
|
+
const key = historyIndexPath(rt);
|
|
47
|
+
let s = STATES.get(key);
|
|
48
|
+
// Another sideby process (the Panel, a second command) may have cleared or rebuilt the file: this one then closes
|
|
49
|
+
// its handle on the old file instead of writing into a deleted one, and opens the current file.
|
|
50
|
+
if (s && ((s.fileId && fileIdOf(key) !== s.fileId) || s.enabled !== enabled(rt))) {
|
|
51
|
+
retire(s);
|
|
52
|
+
s = undefined;
|
|
53
|
+
}
|
|
54
|
+
if (!s) {
|
|
55
|
+
const after = BARRIER.get(key);
|
|
56
|
+
s = {
|
|
57
|
+
key,
|
|
58
|
+
...(after ? { after } : {}),
|
|
59
|
+
reads: new Set(),
|
|
60
|
+
enabled: enabled(rt),
|
|
61
|
+
lastSync: 0,
|
|
62
|
+
built: false,
|
|
63
|
+
state: 'building',
|
|
64
|
+
done: 0,
|
|
65
|
+
total: 0,
|
|
66
|
+
notes: new Map(),
|
|
67
|
+
problems: [],
|
|
68
|
+
};
|
|
69
|
+
STATES.set(key, s);
|
|
70
|
+
}
|
|
71
|
+
return s;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Retires `s`: new calls get a new State, and its index closes once the open, sync and reads in flight on it end;
|
|
75
|
+
* `then` (deleting the file) runs after that, before any new State opens the file.
|
|
76
|
+
*/
|
|
77
|
+
function retire(s, then) {
|
|
78
|
+
s.retired = true;
|
|
79
|
+
if (STATES.get(s.key) === s)
|
|
80
|
+
STATES.delete(s.key);
|
|
81
|
+
return fence(s.key, (async () => {
|
|
82
|
+
await s.after;
|
|
83
|
+
while (s.opening || s.syncing || s.reads.size)
|
|
84
|
+
await Promise.allSettled([s.opening, s.syncing, ...s.reads]);
|
|
85
|
+
s.index?.close();
|
|
86
|
+
s.index = undefined;
|
|
87
|
+
await then?.();
|
|
88
|
+
})());
|
|
89
|
+
}
|
|
90
|
+
/** Runs `fn` on the current State, counted as a read so a retire waits for it before it closes the index. */
|
|
91
|
+
async function reading(rt, fn) {
|
|
92
|
+
const s = stateOf(rt);
|
|
93
|
+
const p = fn(s);
|
|
94
|
+
s.reads.add(p);
|
|
95
|
+
try {
|
|
96
|
+
return await p;
|
|
97
|
+
}
|
|
98
|
+
finally {
|
|
99
|
+
s.reads.delete(p);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
async function indexOf(_rt, s) {
|
|
103
|
+
if (s.index)
|
|
104
|
+
return s.index;
|
|
105
|
+
s.opening ??= (async () => {
|
|
106
|
+
await s.after;
|
|
107
|
+
// A retired State never opens (or deletes) the file again; it only finishes the call that is already waiting.
|
|
108
|
+
if (s.retired)
|
|
109
|
+
return HistoryIndex.open(':memory:', false);
|
|
110
|
+
if (!s.enabled) {
|
|
111
|
+
await HistoryIndex.remove(s.key).catch((err) => {
|
|
112
|
+
s.fallback = err.message;
|
|
113
|
+
});
|
|
114
|
+
return HistoryIndex.open(':memory:', false);
|
|
115
|
+
}
|
|
116
|
+
let why;
|
|
117
|
+
const idx = await HistoryIndex.open(s.key, true).catch((err) => {
|
|
118
|
+
why = err.message;
|
|
119
|
+
return undefined;
|
|
120
|
+
});
|
|
121
|
+
if (idx) {
|
|
122
|
+
s.fileId = fileIdOf(s.key) || undefined;
|
|
123
|
+
return idx;
|
|
124
|
+
}
|
|
125
|
+
s.fallback = why
|
|
126
|
+
? `${why}; searching only titles and folders this time`
|
|
127
|
+
: `could not open the History Index at ${s.key}; searching only titles and folders this time. Run \`sideby history index --clear\` to start it again`;
|
|
128
|
+
return HistoryIndex.open(':memory:', false);
|
|
129
|
+
})();
|
|
130
|
+
const idx = await s.opening;
|
|
131
|
+
s.opening = undefined;
|
|
132
|
+
if (!idx) {
|
|
133
|
+
s.state = 'unavailable';
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
s.index = idx;
|
|
137
|
+
return idx;
|
|
138
|
+
}
|
|
139
|
+
const UNAVAILABLE = `Session History needs Node ${'>='}22.18 with node:sqlite (this is Node ${process.versions.node}); update Node and run the command again`;
|
|
140
|
+
/** Closes the History Index of `rt` (tests), after the open, sync and reads in flight end. */
|
|
141
|
+
export function closeHistory(rt) {
|
|
142
|
+
const s = STATES.get(historyIndexPath(rt));
|
|
143
|
+
return s ? retire(s) : (BARRIER.get(historyIndexPath(rt)) ?? Promise.resolve());
|
|
144
|
+
}
|
|
145
|
+
/** Closes the History Index like closeHistory, then deletes its files before any new State opens them. */
|
|
146
|
+
async function clearHistory(rt) {
|
|
147
|
+
const key = historyIndexPath(rt);
|
|
148
|
+
let removed = false;
|
|
149
|
+
let failed;
|
|
150
|
+
const remove = async () => {
|
|
151
|
+
removed = await HistoryIndex.remove(key).catch((err) => {
|
|
152
|
+
failed = err;
|
|
153
|
+
return false;
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
const s = STATES.get(key);
|
|
157
|
+
await (s ? retire(s, remove) : fence(key, (BARRIER.get(key) ?? Promise.resolve()).then(remove)));
|
|
158
|
+
if (failed)
|
|
159
|
+
throw failed;
|
|
160
|
+
return removed;
|
|
161
|
+
}
|
|
162
|
+
async function mapLimit(items, n, fn) {
|
|
163
|
+
let next = 0;
|
|
164
|
+
await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
|
|
165
|
+
while (next < items.length)
|
|
166
|
+
await fn(items[next++]);
|
|
167
|
+
}));
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Brings the History Index in step with the Hosts' files: lists every Account's record files, forgets the ones that
|
|
171
|
+
* are gone, and reads the new or changed ones, newest first. One sync runs at a time; a call while one runs waits for
|
|
172
|
+
* it. An Account that cannot be listed keeps the Sessions already stored for it.
|
|
173
|
+
*/
|
|
174
|
+
export async function syncHistory(rt, opts = {}) {
|
|
175
|
+
const s = stateOf(rt);
|
|
176
|
+
if (s.syncing)
|
|
177
|
+
return s.syncing;
|
|
178
|
+
if (!opts.force && s.built && Date.now() - s.lastSync < SYNC_EVERY_MS)
|
|
179
|
+
return;
|
|
180
|
+
s.syncing = (async () => {
|
|
181
|
+
const idx = await indexOf(rt, s);
|
|
182
|
+
if (!idx)
|
|
183
|
+
return;
|
|
184
|
+
const accounts = (await rt.accounts()).filter((a) => historyReader(a.family, rt.families));
|
|
185
|
+
const labels = accountLabels(rt, accounts);
|
|
186
|
+
const notes = new Map();
|
|
187
|
+
const problems = [];
|
|
188
|
+
const listed = new Map();
|
|
189
|
+
await Promise.all(accounts.map(async (a) => {
|
|
190
|
+
try {
|
|
191
|
+
const files = await historyReader(a.family, rt.families).list(a, problems);
|
|
192
|
+
listed.set(a.ref, files);
|
|
193
|
+
if (!files.length)
|
|
194
|
+
notes.set(a.ref, 'no session records yet');
|
|
195
|
+
}
|
|
196
|
+
catch (err) {
|
|
197
|
+
const why = err.code ?? err.message;
|
|
198
|
+
notes.set(a.ref, `could not be read (${why})`);
|
|
199
|
+
problems.push(`${a.ref}: could not list its sessions (${why}); check that ${a.dir} is readable`);
|
|
200
|
+
}
|
|
201
|
+
}));
|
|
202
|
+
const known = idx.fileSigs();
|
|
203
|
+
const refs = new Set(accounts.map((a) => a.ref));
|
|
204
|
+
const seen = new Set();
|
|
205
|
+
const todo = [];
|
|
206
|
+
// Two Accounts whose record folders are links to one folder list the same files: each is kept once, for the
|
|
207
|
+
// first Account that lists it, so a Session is not listed twice nor needs --account to be opened.
|
|
208
|
+
const reals = new Map();
|
|
209
|
+
const realDir = (d) => {
|
|
210
|
+
let r = reals.get(d);
|
|
211
|
+
if (!r) {
|
|
212
|
+
r = realpath(d).catch(() => d);
|
|
213
|
+
reals.set(d, r);
|
|
214
|
+
}
|
|
215
|
+
return r;
|
|
216
|
+
};
|
|
217
|
+
const owners = new Set();
|
|
218
|
+
for (const a of accounts) {
|
|
219
|
+
for (const f of listed.get(a.ref) ?? []) {
|
|
220
|
+
const real = join(await realDir(dirname(f.path)), basename(f.path));
|
|
221
|
+
if (owners.has(real))
|
|
222
|
+
continue;
|
|
223
|
+
owners.add(real);
|
|
224
|
+
seen.add(f.path);
|
|
225
|
+
if (known.get(f.path)?.sig !== f.sig)
|
|
226
|
+
todo.push({ account: a, file: f });
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
// A file is forgotten when its Account was listed and no longer has it, or the Account is gone.
|
|
230
|
+
idx.remove([...known]
|
|
231
|
+
.filter(([path, k]) => !seen.has(path) && (!refs.has(k.account) || listed.has(k.account)))
|
|
232
|
+
.map(([path]) => path));
|
|
233
|
+
todo.sort((x, y) => y.file.mtimeMs - x.file.mtimeMs);
|
|
234
|
+
s.done = 0;
|
|
235
|
+
s.total = todo.length;
|
|
236
|
+
if (todo.length)
|
|
237
|
+
s.state = 'building';
|
|
238
|
+
const projects = new ProjectResolver();
|
|
239
|
+
let failed = 0;
|
|
240
|
+
let busy = 0;
|
|
241
|
+
let cut = 0;
|
|
242
|
+
await mapLimit(todo, PARSE_AT_ONCE, async ({ account, file }) => {
|
|
243
|
+
if (s.retired)
|
|
244
|
+
return;
|
|
245
|
+
const reader = historyReader(account.family, rt.families);
|
|
246
|
+
try {
|
|
247
|
+
const parsed = await reader.parse(file, account);
|
|
248
|
+
if (s.retired)
|
|
249
|
+
return;
|
|
250
|
+
let input;
|
|
251
|
+
// A Session id goes into a resume command the user may run, so only plain ids are kept.
|
|
252
|
+
if (parsed)
|
|
253
|
+
parsed.parent ??= file.parent;
|
|
254
|
+
if (parsed && SAFE_ID.test(parsed.sessionId) && (!parsed.parent || SAFE_ID.test(parsed.parent))) {
|
|
255
|
+
const p = await projects.resolve(parsed.cwd, parsed.gitRoot);
|
|
256
|
+
input = {
|
|
257
|
+
account: account.ref,
|
|
258
|
+
accountLabel: labels.get(account.ref) ?? account.ref,
|
|
259
|
+
family: account.family,
|
|
260
|
+
path: file.path,
|
|
261
|
+
sig: file.sig,
|
|
262
|
+
project: p.path,
|
|
263
|
+
cwdGone: p.gone,
|
|
264
|
+
session: parsed,
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
if (input && parsed?.cut)
|
|
268
|
+
cut++;
|
|
269
|
+
try {
|
|
270
|
+
idx.put(account.ref, file.path, file.sig, input);
|
|
271
|
+
}
|
|
272
|
+
catch {
|
|
273
|
+
// The index was busy or could not be written (another sideby writing it): the file is fine, so it is
|
|
274
|
+
// not marked unreadable and the next sync reads it again.
|
|
275
|
+
busy++;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
catch (err) {
|
|
279
|
+
// A file that vanished mid-read is picked up (or forgotten) by the next sync.
|
|
280
|
+
if (err.code !== 'ENOENT') {
|
|
281
|
+
failed++;
|
|
282
|
+
idx.putFailed(account.ref, file.path, file.sig);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
s.done++;
|
|
286
|
+
});
|
|
287
|
+
if (s.retired)
|
|
288
|
+
return;
|
|
289
|
+
// An Account given a new name or short command is found by it, also in Sessions read before.
|
|
290
|
+
idx.relabel(labels);
|
|
291
|
+
// A folder removed, or made a repository, after its Sessions were read moves them without reading them again.
|
|
292
|
+
for (const place of idx.places()) {
|
|
293
|
+
const p = await projects.resolve(place.cwd, place.gone ? place.project : undefined);
|
|
294
|
+
if (p.path && (p.path !== place.project || p.gone !== place.gone))
|
|
295
|
+
idx.moveProject(place.cwd, place.project, p.path, p.gone);
|
|
296
|
+
}
|
|
297
|
+
if (cut)
|
|
298
|
+
problems.push(`${cut} session${cut === 1 ? ' has' : 's have'} more than ${SESSION_TEXT_MAX / 1024 / 1024} MB of text; only the start of each is searchable`);
|
|
299
|
+
if (busy)
|
|
300
|
+
problems.push(`${busy} session${busy === 1 ? '' : 's'} could not be saved to the search index (another sideby may be updating it); they are added on the next refresh`);
|
|
301
|
+
if (failed)
|
|
302
|
+
problems.push(`${failed} session file${failed === 1 ? '' : 's'} could not be read; they are tried again once they change`);
|
|
303
|
+
for (const a of accounts) {
|
|
304
|
+
const reader = historyReader(a.family, rt.families);
|
|
305
|
+
if (!reader.titles || !listed.has(a.ref))
|
|
306
|
+
continue;
|
|
307
|
+
try {
|
|
308
|
+
idx.setHostTitles(a.ref, await reader.titles(a));
|
|
309
|
+
}
|
|
310
|
+
catch (err) {
|
|
311
|
+
problems.push(`${a.ref}: could not read its session titles (${err.code ?? err.message}); titles fall back to the first prompt`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (s.fallback)
|
|
315
|
+
problems.push(s.fallback);
|
|
316
|
+
s.notes = notes;
|
|
317
|
+
s.problems = [...new Set(problems)];
|
|
318
|
+
s.state = s.enabled && !s.fallback ? 'ready' : 'off';
|
|
319
|
+
s.built = true;
|
|
320
|
+
s.lastSync = Date.now();
|
|
321
|
+
})().finally(() => {
|
|
322
|
+
s.syncing = undefined;
|
|
323
|
+
});
|
|
324
|
+
return s.syncing;
|
|
325
|
+
}
|
|
326
|
+
/** How long a listing waits for a first build before it answers with what is built so far. */
|
|
327
|
+
export const FIRST_ANSWER_MS = 2_500;
|
|
328
|
+
/** Waits for `sync` with `wait`; else for at most FIRST_ANSWER_MS while nothing was built yet, then not at all. */
|
|
329
|
+
async function settle(s, sync, wait) {
|
|
330
|
+
if (wait)
|
|
331
|
+
return sync;
|
|
332
|
+
sync.catch(() => { });
|
|
333
|
+
if (s.built)
|
|
334
|
+
return;
|
|
335
|
+
let timer;
|
|
336
|
+
await Promise.race([
|
|
337
|
+
sync.catch(() => { }),
|
|
338
|
+
new Promise((r) => (timer = setTimeout(r, FIRST_ANSWER_MS))),
|
|
339
|
+
]);
|
|
340
|
+
clearTimeout(timer);
|
|
341
|
+
}
|
|
342
|
+
/** Starts a sync without waiting for it; what is already built answers at once. */
|
|
343
|
+
export function syncHistoryInBackground(rt) {
|
|
344
|
+
syncHistory(rt).catch(() => {
|
|
345
|
+
// reported by the next listing
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
function progressOf(s) {
|
|
349
|
+
return { state: s.state, progress: { done: s.done, total: s.total } };
|
|
350
|
+
}
|
|
351
|
+
/** True once a first build finished (the Panel then answers without waiting). */
|
|
352
|
+
export const historyBuilt = (rt) => stateOf(rt).built;
|
|
353
|
+
async function sourcesOf(rt, s, idx) {
|
|
354
|
+
const accounts = await rt.accounts();
|
|
355
|
+
const labels = accountLabels(rt, accounts);
|
|
356
|
+
const counts = idx.counts();
|
|
357
|
+
return accounts.map((a) => {
|
|
358
|
+
const c = counts.get(a.ref) ?? { files: 0, sessions: 0, failed: 0 };
|
|
359
|
+
const out = {
|
|
360
|
+
account: a.ref,
|
|
361
|
+
accountLabel: labels.get(a.ref) ?? a.ref,
|
|
362
|
+
family: a.family,
|
|
363
|
+
sessions: c.sessions,
|
|
364
|
+
files: c.files,
|
|
365
|
+
failed: c.failed,
|
|
366
|
+
};
|
|
367
|
+
const note = s.notes.get(a.ref);
|
|
368
|
+
if (!historyReader(a.family, rt.families)) {
|
|
369
|
+
out.note =
|
|
370
|
+
'sideby cannot read past sessions of this tool yet: its plugin gives no session reader (FamilyDef `history`, see docs/guide/plugins.md)';
|
|
371
|
+
out.reason = 'unsupported';
|
|
372
|
+
}
|
|
373
|
+
else if (note) {
|
|
374
|
+
out.note = note;
|
|
375
|
+
out.reason = note.startsWith('could not') ? 'unreadable' : 'empty';
|
|
376
|
+
}
|
|
377
|
+
else if (!c.sessions && c.files > c.failed) {
|
|
378
|
+
out.note = 'its records hold no conversation yet';
|
|
379
|
+
out.reason = 'no-conversation';
|
|
380
|
+
}
|
|
381
|
+
return out;
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
function sinceMs(since, now = Date.now()) {
|
|
385
|
+
if (!since || since === 'all')
|
|
386
|
+
return undefined;
|
|
387
|
+
if (since === 'today') {
|
|
388
|
+
const d = new Date(now);
|
|
389
|
+
d.setHours(0, 0, 0, 0);
|
|
390
|
+
return d.getTime();
|
|
391
|
+
}
|
|
392
|
+
return now - (since === '7d' ? 7 : 30) * DAY;
|
|
393
|
+
}
|
|
394
|
+
const SINCE = new Set(['today', '7d', '30d', 'all']);
|
|
395
|
+
/**
|
|
396
|
+
* The query with its time checked and a `~` project made a path, before anything is read, so a bad query fails the
|
|
397
|
+
* same way whether the index is there or not.
|
|
398
|
+
*/
|
|
399
|
+
function checkQuery(rt, q) {
|
|
400
|
+
if (q.since !== undefined && !SINCE.has(q.since))
|
|
401
|
+
throw new UserError(`unknown time "${q.since}"; use today, 7d, 30d or all`);
|
|
402
|
+
if (q.group !== undefined && !GROUP_BYS.includes(q.group))
|
|
403
|
+
throw new UserError(`unknown grouping "${q.group}"; use ${GROUP_BYS.join(', ')}`);
|
|
404
|
+
const p = q.project;
|
|
405
|
+
if (p === '~' || p?.startsWith('~/'))
|
|
406
|
+
return { ...q, project: rt.paths.home + p.slice(1) };
|
|
407
|
+
return q;
|
|
408
|
+
}
|
|
409
|
+
async function filtersOf(rt, idx, q, cats) {
|
|
410
|
+
const f = {};
|
|
411
|
+
if (q.category !== undefined) {
|
|
412
|
+
cats ??= await categoriesOf(rt, namesOf(idx), true);
|
|
413
|
+
if (!cats)
|
|
414
|
+
throw new UserError('no plugin sorts projects into categories; add one (see docs/guide/plugins.md) or filter with --project');
|
|
415
|
+
const name = q.category;
|
|
416
|
+
f.projects = [...cats.of].filter(([, c]) => c === name).map(([p]) => p);
|
|
417
|
+
if (!f.projects.length && !cats.problem)
|
|
418
|
+
throw new UserError(`no category named "${name}"; run \`sideby history projects\` to see them`);
|
|
419
|
+
}
|
|
420
|
+
if (q.family) {
|
|
421
|
+
if (!rt.families.has(q.family))
|
|
422
|
+
throw new UserError(`unknown AI "${q.family}"; use one of ${[...rt.families.keys()].join(', ')}`);
|
|
423
|
+
f.family = q.family;
|
|
424
|
+
}
|
|
425
|
+
if (q.account)
|
|
426
|
+
f.account = (await rt.resolve(q.account)).ref;
|
|
427
|
+
if (q.project !== undefined)
|
|
428
|
+
f.project = await resolveProject(idx, q.project, rt.paths.home);
|
|
429
|
+
const since = sinceMs(q.since);
|
|
430
|
+
if (since)
|
|
431
|
+
f.since = since;
|
|
432
|
+
if (q.scripts)
|
|
433
|
+
f.scripts = true;
|
|
434
|
+
return f;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* A Project path from a path or a name; an unknown name throws with the names that exist. A path (absolute, or
|
|
438
|
+
* starting with `.` or `~`) is resolved from the current folder and moved up to the Project it is in, so a subfolder,
|
|
439
|
+
* `.` or a worktree finds its repository's Sessions.
|
|
440
|
+
*/
|
|
441
|
+
async function resolveProject(idx, p, home) {
|
|
442
|
+
if (p === '')
|
|
443
|
+
return p;
|
|
444
|
+
const names = namesOf(idx);
|
|
445
|
+
if (isAbsolute(p) || p === '.' || p === '..' || /^\.{1,2}\//.test(p) || p === '~' || p.startsWith('~/')) {
|
|
446
|
+
const abs = resolve(p === '~' || p.startsWith('~/') ? join(home, p.slice(1)) : p);
|
|
447
|
+
if (names.has(abs))
|
|
448
|
+
return abs;
|
|
449
|
+
const found = (await new ProjectResolver().resolve(abs)).path;
|
|
450
|
+
if (names.has(found))
|
|
451
|
+
return found;
|
|
452
|
+
for (let dir = abs; dirname(dir) !== dir; dir = dirname(dir))
|
|
453
|
+
if (names.has(dir))
|
|
454
|
+
return dir;
|
|
455
|
+
return abs;
|
|
456
|
+
}
|
|
457
|
+
const hit = projectsNamed(names, p);
|
|
458
|
+
if (hit.length === 1)
|
|
459
|
+
return hit[0];
|
|
460
|
+
if (hit.length > 1)
|
|
461
|
+
throw new UserError(`"${p}" names ${hit.length} projects (${hit.join(', ')}); give the full path`);
|
|
462
|
+
throw new UserError(`no project named "${p}"; run \`sideby history projects\` to see them`);
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* The Projects a name given to `--project` may mean: the one whose shown name it is, else every Project whose path
|
|
466
|
+
* ends with it. A shown name is unique, so it wins over a path tail it shares with a longer path (`a/app` for
|
|
467
|
+
* `/a/app` beside `/x/a/app`).
|
|
468
|
+
*/
|
|
469
|
+
export function projectsNamed(names, p) {
|
|
470
|
+
const all = [...names.keys()];
|
|
471
|
+
const named = all.filter((x) => names.get(x) === p);
|
|
472
|
+
if (named.length === 1)
|
|
473
|
+
return named;
|
|
474
|
+
return all.filter((x) => names.get(x) === p || x.endsWith(`/${p}`));
|
|
475
|
+
}
|
|
476
|
+
const SAFE = /^[\w@%+=:,./-]+$/;
|
|
477
|
+
const shq = (v) => (SAFE.test(v) ? v : `'${v.replaceAll("'", "'\\''")}'`);
|
|
478
|
+
/** A snippet of `text` around the first of `words` it contains, about 40 characters each side. */
|
|
479
|
+
export function snippetOf(text, words) {
|
|
480
|
+
if (!text || !words.length)
|
|
481
|
+
return undefined;
|
|
482
|
+
let at = -1;
|
|
483
|
+
let len = 0;
|
|
484
|
+
for (const w of words) {
|
|
485
|
+
// Matched in the text itself: lowercasing can change its length and move every position after it.
|
|
486
|
+
const m = new RegExp(w.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'iu').exec(text);
|
|
487
|
+
if (m && (at < 0 || m.index < at)) {
|
|
488
|
+
at = m.index;
|
|
489
|
+
len = m[0].length;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
if (at < 0)
|
|
493
|
+
return undefined;
|
|
494
|
+
let start = Math.max(0, at - 40);
|
|
495
|
+
if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start]))
|
|
496
|
+
start--;
|
|
497
|
+
const end = start + cutText(text.slice(start), at - start + len + 40).length;
|
|
498
|
+
const body = text.slice(start, end).replace(/\s+/g, ' ').trim();
|
|
499
|
+
return `${start > 0 ? '…' : ''}${body}${end < text.length ? '…' : ''}`;
|
|
500
|
+
}
|
|
501
|
+
const NAMES = new WeakMap();
|
|
502
|
+
/** Project names, worked out again only after the index changed. */
|
|
503
|
+
function namesOf(idx) {
|
|
504
|
+
const kept = NAMES.get(idx);
|
|
505
|
+
if (kept?.version === idx.version)
|
|
506
|
+
return kept.names;
|
|
507
|
+
const names = projectNames(idx.projects({ scripts: true }).map((p) => p.project));
|
|
508
|
+
NAMES.set(idx, { version: idx.version, names });
|
|
509
|
+
return names;
|
|
510
|
+
}
|
|
511
|
+
/** The command that resumes Session `id` in `account` itself. */
|
|
512
|
+
function accountResumeCommand(rt, family, account, id) {
|
|
513
|
+
const custom = historyReader(family, rt.families)?.resumeArgs?.(id);
|
|
514
|
+
const args = custom ? custom.map(shq).join(' ') : hostResumeArgs(family, id);
|
|
515
|
+
return `sideby run ${shq(account)} -- ${args}`;
|
|
516
|
+
}
|
|
517
|
+
const iso = (ms) => (ms ? new Date(ms).toISOString() : '');
|
|
518
|
+
function toSession(rt, r, labels, names, extra) {
|
|
519
|
+
const accountLabel = labels.get(r.account) ?? r.accountLabel;
|
|
520
|
+
// The Account of this row, not Resume Routing's pick: the same Session may be kept by another Account too.
|
|
521
|
+
const resumeCommand = SAFE_ID.test(r.sessionId)
|
|
522
|
+
? accountResumeCommand(rt, r.family, r.account, r.sessionId)
|
|
523
|
+
: '';
|
|
524
|
+
const continueCommand = resumeCommand && r.cwd && !r.cwdGone ? `cd ${shq(r.cwd)} && ${resumeCommand}` : resumeCommand;
|
|
525
|
+
const out = {
|
|
526
|
+
account: r.account,
|
|
527
|
+
accountLabel,
|
|
528
|
+
family: r.family,
|
|
529
|
+
sessionId: r.sessionId,
|
|
530
|
+
title: r.title,
|
|
531
|
+
titleFrom: r.titleFrom,
|
|
532
|
+
project: r.project,
|
|
533
|
+
projectName: r.project ? (names.get(r.project) ?? r.project) : '',
|
|
534
|
+
cwd: r.cwd,
|
|
535
|
+
startedAt: iso(r.startedAt),
|
|
536
|
+
updatedAt: iso(r.updatedAt),
|
|
537
|
+
messages: r.messages,
|
|
538
|
+
script: r.script,
|
|
539
|
+
children: extra.children ?? 0,
|
|
540
|
+
live: extra.live ?? false,
|
|
541
|
+
transcript: r.path,
|
|
542
|
+
resumeCommand,
|
|
543
|
+
continueCommand,
|
|
544
|
+
reference: referenceText({
|
|
545
|
+
accountLabel,
|
|
546
|
+
sessionId: r.sessionId,
|
|
547
|
+
title: r.title,
|
|
548
|
+
cwd: r.cwd,
|
|
549
|
+
transcript: r.path,
|
|
550
|
+
guessed: false,
|
|
551
|
+
resumeCommand,
|
|
552
|
+
}, 'en'),
|
|
553
|
+
};
|
|
554
|
+
if (r.cwdGone)
|
|
555
|
+
out.cwdGone = true;
|
|
556
|
+
if (r.branch)
|
|
557
|
+
out.branch = r.branch;
|
|
558
|
+
if (r.model)
|
|
559
|
+
out.model = r.model;
|
|
560
|
+
if (r.parent)
|
|
561
|
+
out.parent = r.parent;
|
|
562
|
+
const first = r.firstPrompt.replace(/\s+/g, ' ').trim();
|
|
563
|
+
if (first && first !== r.title && !(r.titleFrom === 'prompt' && first.length <= r.title.length))
|
|
564
|
+
out.preview = first.length > 240 ? `${cutText(first, 239)}…` : first;
|
|
565
|
+
if (extra.snippet)
|
|
566
|
+
out.snippet = extra.snippet;
|
|
567
|
+
return out;
|
|
568
|
+
}
|
|
569
|
+
/** The words of a search; `"two words"` in double quotes is one phrase, matched as written. */
|
|
570
|
+
export const splitWords = (q) => [...(q ?? '').matchAll(/"([^"]*)"?|(\S+)/g)].map((m) => (m[1] ?? m[2] ?? '').trim()).filter(Boolean);
|
|
571
|
+
/**
|
|
572
|
+
* Sessions matching `q`, best first (relevance times a recency boost that halves every 7 days), or newest first
|
|
573
|
+
* without words. Answers from what is built; `wait` waits for the current sync first (the CLI's first run).
|
|
574
|
+
* `live` names Sessions running now, as `<account>\0<sessionId>`.
|
|
575
|
+
*/
|
|
576
|
+
export async function searchHistory(rt, q, opts = {}) {
|
|
577
|
+
const checked = checkQuery(rt, q);
|
|
578
|
+
return reading(rt, (s) => search(rt, s, checked, opts));
|
|
579
|
+
}
|
|
580
|
+
async function search(rt, s, q, opts) {
|
|
581
|
+
await settle(s, syncHistory(rt), opts.wait);
|
|
582
|
+
const idx = await indexOf(rt, s);
|
|
583
|
+
if (!idx)
|
|
584
|
+
return {
|
|
585
|
+
sessions: [],
|
|
586
|
+
total: 0,
|
|
587
|
+
sources: [],
|
|
588
|
+
problems: [UNAVAILABLE],
|
|
589
|
+
state: 'unavailable',
|
|
590
|
+
progress: { done: 0, total: 0 },
|
|
591
|
+
};
|
|
592
|
+
const group = q.group ?? 'none';
|
|
593
|
+
const names = namesOf(idx);
|
|
594
|
+
const cats = await categoriesOf(rt, names, q.category !== undefined || group === 'category');
|
|
595
|
+
const f = await filtersOf(rt, idx, q, cats);
|
|
596
|
+
const words = splitWords(q.q);
|
|
597
|
+
const limit = Math.max(1, Math.min(q.limit ?? 50, 500));
|
|
598
|
+
const offset = Math.max(0, q.offset ?? 0);
|
|
599
|
+
const accounts = await rt.accounts();
|
|
600
|
+
const labels = accountLabels(rt, accounts);
|
|
601
|
+
let rows;
|
|
602
|
+
let total;
|
|
603
|
+
let groups;
|
|
604
|
+
const groupOf = new Map();
|
|
605
|
+
const pageOf = (ids) => {
|
|
606
|
+
const byId = new Map(idx.rows(ids).map((r) => [r.id, r]));
|
|
607
|
+
return ids.map((id) => byId.get(id)).filter(Boolean);
|
|
608
|
+
};
|
|
609
|
+
if (words.length || group !== 'none') {
|
|
610
|
+
let items;
|
|
611
|
+
if (words.length) {
|
|
612
|
+
const now = Date.now();
|
|
613
|
+
const hits = idx.match(words, f);
|
|
614
|
+
const outline = idx.outlineOf(hits.map((h) => h.id));
|
|
615
|
+
items = hits.flatMap((h) => {
|
|
616
|
+
const o = outline.get(h.id);
|
|
617
|
+
return o ? [{ ...o, score: h.relevance * 0.5 ** (Math.max(0, now - o.updatedAt) / HALF_LIFE) }] : [];
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
else
|
|
621
|
+
items = idx.outline(f).map((o) => ({ ...o, score: o.updatedAt }));
|
|
622
|
+
if (group === 'none') {
|
|
623
|
+
items.sort((a, b) => b.score - a.score || b.id - a.id);
|
|
624
|
+
total = items.length;
|
|
625
|
+
rows = pageOf(items.slice(offset, offset + limit).map((h) => h.id));
|
|
626
|
+
}
|
|
627
|
+
else {
|
|
628
|
+
const collapsed = new Set(q.collapsed ?? []);
|
|
629
|
+
const now = new Date();
|
|
630
|
+
const keyOf = (o) => group === 'project'
|
|
631
|
+
? o.project
|
|
632
|
+
: group === 'category'
|
|
633
|
+
? (cats?.of.get(o.project) ?? '')
|
|
634
|
+
: group === 'account'
|
|
635
|
+
? o.account
|
|
636
|
+
: group === 'family'
|
|
637
|
+
? o.family
|
|
638
|
+
: dayGroup(o.updatedAt, now);
|
|
639
|
+
const ordered = orderGroups(items, keyOf, collapsed, group === 'day' ? DAY_GROUPS : undefined);
|
|
640
|
+
total = ordered.items.length;
|
|
641
|
+
const page = ordered.items.slice(offset, offset + limit);
|
|
642
|
+
for (const it of page)
|
|
643
|
+
groupOf.set(it.id, it.group);
|
|
644
|
+
rows = pageOf(page.map((it) => it.id));
|
|
645
|
+
groups = ordered.groups.map((g) => {
|
|
646
|
+
const out = {
|
|
647
|
+
key: g.key,
|
|
648
|
+
label: groupLabel(rt, group, g.key, names, labels),
|
|
649
|
+
sessions: g.sessions,
|
|
650
|
+
updatedAt: iso(g.updatedAt),
|
|
651
|
+
};
|
|
652
|
+
if (collapsed.has(g.key))
|
|
653
|
+
out.collapsed = true;
|
|
654
|
+
return out;
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
else {
|
|
659
|
+
;
|
|
660
|
+
({ rows, total } = idx.recent(f, limit, offset));
|
|
661
|
+
}
|
|
662
|
+
const children = idx.children(rows);
|
|
663
|
+
const sessions = rows.map((r) => {
|
|
664
|
+
let snippet;
|
|
665
|
+
if (words.length && idx.keepText) {
|
|
666
|
+
const t = idx.text(r.id);
|
|
667
|
+
snippet = snippetOf(t.prompts, words) ?? snippetOf(t.replies, words);
|
|
668
|
+
}
|
|
669
|
+
const out = toSession(rt, r, labels, names, {
|
|
670
|
+
children: children.get(r.id) ?? 0,
|
|
671
|
+
...(snippet ? { snippet } : {}),
|
|
672
|
+
live: opts.live?.has(liveKey(r.account, r.sessionId)) ?? false,
|
|
673
|
+
});
|
|
674
|
+
const g = groupOf.get(r.id);
|
|
675
|
+
if (g !== undefined)
|
|
676
|
+
out.group = g;
|
|
677
|
+
return out;
|
|
678
|
+
});
|
|
679
|
+
const result = {
|
|
680
|
+
sessions,
|
|
681
|
+
total,
|
|
682
|
+
sources: await sourcesOf(rt, s, idx),
|
|
683
|
+
problems: cats?.problem ? [...s.problems, cats.problem] : s.problems,
|
|
684
|
+
...progressOf(s),
|
|
685
|
+
};
|
|
686
|
+
if (groups)
|
|
687
|
+
result.groups = groups;
|
|
688
|
+
if (rt.projectCategoriesFrom)
|
|
689
|
+
result.categories = { label: cats?.label ?? '', from: rt.projectCategoriesFrom };
|
|
690
|
+
return result;
|
|
691
|
+
}
|
|
692
|
+
/** The Project Categories of every Project in the index, asked of the Plugin only when `need` is set. */
|
|
693
|
+
async function categoriesOf(rt, names, need) {
|
|
694
|
+
if (!need || !rt.projectCategoriesFrom)
|
|
695
|
+
return undefined;
|
|
696
|
+
return rt.projectCategories([...names.keys()].filter(Boolean));
|
|
697
|
+
}
|
|
698
|
+
const DAY_LABELS = {
|
|
699
|
+
today: 'Today',
|
|
700
|
+
yesterday: 'Yesterday',
|
|
701
|
+
week: 'Last 7 days',
|
|
702
|
+
month: 'Last 30 days',
|
|
703
|
+
older: 'Older',
|
|
704
|
+
};
|
|
705
|
+
/** The English label of a group; the Panel shows its own words for days and for the group without a key. */
|
|
706
|
+
function groupLabel(rt, group, key, names, labels) {
|
|
707
|
+
if (group === 'day')
|
|
708
|
+
return DAY_LABELS[key] ?? key;
|
|
709
|
+
if (key === '')
|
|
710
|
+
return group === 'category' ? 'No category' : group === 'project' ? 'No project' : 'Other';
|
|
711
|
+
if (group === 'project')
|
|
712
|
+
return names.get(key) ?? key;
|
|
713
|
+
if (group === 'account')
|
|
714
|
+
return labels.get(key) ?? key;
|
|
715
|
+
if (group === 'family')
|
|
716
|
+
return rt.families.get(key)?.title ?? key;
|
|
717
|
+
return key;
|
|
718
|
+
}
|
|
719
|
+
/** Every Project with its number of Sessions, most recent first. */
|
|
720
|
+
export async function historyProjects(rt, q = {}, opts = {}) {
|
|
721
|
+
q = checkQuery(rt, q);
|
|
722
|
+
return reading(rt, async (s) => {
|
|
723
|
+
await settle(s, syncHistory(rt), opts.wait);
|
|
724
|
+
const idx = await indexOf(rt, s);
|
|
725
|
+
if (!idx)
|
|
726
|
+
throw new UserError(UNAVAILABLE, { code: 'history-unavailable' });
|
|
727
|
+
const f = await filtersOf(rt, idx, q);
|
|
728
|
+
const list = idx.projects(f);
|
|
729
|
+
const names = namesOf(idx);
|
|
730
|
+
const cats = await categoriesOf(rt, names, true);
|
|
731
|
+
return {
|
|
732
|
+
...(cats ? { categories: { label: cats.label, from: cats.owner } } : {}),
|
|
733
|
+
...(cats?.problem ? { problems: [cats.problem] } : {}),
|
|
734
|
+
projects: list.map((p) => {
|
|
735
|
+
const e = {
|
|
736
|
+
project: p.project,
|
|
737
|
+
name: p.project ? (names.get(p.project) ?? p.project) : '',
|
|
738
|
+
sessions: p.sessions,
|
|
739
|
+
updatedAt: iso(p.updatedAt),
|
|
740
|
+
};
|
|
741
|
+
if (p.gone)
|
|
742
|
+
e.gone = true;
|
|
743
|
+
const c = cats?.of.get(p.project);
|
|
744
|
+
if (c)
|
|
745
|
+
e.category = c;
|
|
746
|
+
return e;
|
|
747
|
+
}),
|
|
748
|
+
...progressOf(s),
|
|
749
|
+
};
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* One Session's messages, oldest first: the newest `limit` (default 200) before message `before`. `id` is the
|
|
754
|
+
* Session id or its first eight characters or more.
|
|
755
|
+
*/
|
|
756
|
+
export async function historyShow(rt, id, opts = {}) {
|
|
757
|
+
return reading(rt, (s) => show(rt, s, id, opts));
|
|
758
|
+
}
|
|
759
|
+
async function show(rt, s, id, opts) {
|
|
760
|
+
const idx = await indexOf(rt, s);
|
|
761
|
+
if (!idx)
|
|
762
|
+
throw new UserError(UNAVAILABLE, { code: 'history-unavailable' });
|
|
763
|
+
const account = opts.account ? (await rt.resolve(opts.account)).ref : undefined;
|
|
764
|
+
const lookup = () => idx.find(id).filter((r) => !account || r.account === account);
|
|
765
|
+
let found = lookup();
|
|
766
|
+
if (!found.length) {
|
|
767
|
+
await syncHistory(rt, { force: true });
|
|
768
|
+
found = lookup();
|
|
769
|
+
}
|
|
770
|
+
if (!found.length)
|
|
771
|
+
throw new UserError(`no session "${id}"${account ? ` in ${account}` : ''}; run \`sideby history\` to find its id`);
|
|
772
|
+
const ids = new Set(found.map((r) => `${r.account} ${r.sessionId}`));
|
|
773
|
+
if (ids.size > 1) {
|
|
774
|
+
const accounts = new Set(found.map((r) => r.account));
|
|
775
|
+
throw new UserError(`"${id}" matches ${ids.size} sessions (${[...ids].slice(0, 5).join(', ')}); ${accounts.size > 1 && new Set(found.map((r) => r.sessionId)).size === 1 ? 'add --account <account> to pick one' : 'give more of the id'}`);
|
|
776
|
+
}
|
|
777
|
+
// The same Session kept by two Accounts (a shared folder) reads the same file; take the newest.
|
|
778
|
+
const r = found.sort((a, b) => b.updatedAt - a.updatedAt)[0];
|
|
779
|
+
const reader = historyReader(r.family, rt.families);
|
|
780
|
+
if (!reader)
|
|
781
|
+
throw new UserError(`sideby cannot read ${r.family} sessions: its plugin gives no session reader (FamilyDef \`history\`, see docs/guide/plugins.md)`);
|
|
782
|
+
const limit = Math.max(1, Math.min(opts.limit ?? 200, 2000));
|
|
783
|
+
const window = [];
|
|
784
|
+
let n = 0;
|
|
785
|
+
try {
|
|
786
|
+
for await (const m of reader.messages(r.path)) {
|
|
787
|
+
n++;
|
|
788
|
+
if (opts.before !== undefined && n >= opts.before)
|
|
789
|
+
break;
|
|
790
|
+
window.push({ n, ...m });
|
|
791
|
+
if (window.length > limit)
|
|
792
|
+
window.shift();
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
catch (err) {
|
|
796
|
+
const code = err.code;
|
|
797
|
+
// Forget the gone file now, so the list refreshed after this error no longer shows it.
|
|
798
|
+
if (code === 'ENOENT') {
|
|
799
|
+
try {
|
|
800
|
+
idx.remove([r.path]);
|
|
801
|
+
}
|
|
802
|
+
catch { }
|
|
803
|
+
}
|
|
804
|
+
throw new UserError(`could not read ${r.path} (${code ?? err.message}); the Host may have removed it, run \`sideby history\` again`, code === 'ENOENT' ? { code: 'session-gone' } : {});
|
|
805
|
+
}
|
|
806
|
+
const labels = accountLabels(rt, await rt.accounts());
|
|
807
|
+
const names = namesOf(idx);
|
|
808
|
+
const out = {
|
|
809
|
+
session: toSession(rt, r, labels, names, { children: idx.children([r]).get(r.id) ?? 0 }),
|
|
810
|
+
messages: window,
|
|
811
|
+
};
|
|
812
|
+
if (window[0] && window[0].n > 1)
|
|
813
|
+
out.before = window[0].n;
|
|
814
|
+
return out;
|
|
815
|
+
}
|
|
816
|
+
async function sizeOf(path) {
|
|
817
|
+
let n = 0;
|
|
818
|
+
for (const p of [path, `${path}-wal`])
|
|
819
|
+
n += await stat(p).then((st) => st.size, () => 0);
|
|
820
|
+
return n;
|
|
821
|
+
}
|
|
822
|
+
/** The History Index's state; with `clear` it is deleted first (and rebuilt by the next listing when on). */
|
|
823
|
+
export async function historyIndexInfo(rt, opts = {}) {
|
|
824
|
+
const cleared = opts.clear ? await clearHistory(rt) : undefined;
|
|
825
|
+
// Cleared without a rebuild (the CLI): nothing is opened again, so the command ends and the file stays deleted
|
|
826
|
+
// until the next listing builds it.
|
|
827
|
+
if (opts.clear && opts.rebuild === false)
|
|
828
|
+
return {
|
|
829
|
+
enabled: enabled(rt),
|
|
830
|
+
path: historyIndexPath(rt),
|
|
831
|
+
state: enabled(rt) ? 'building' : 'off',
|
|
832
|
+
progress: { done: 0, total: 0 },
|
|
833
|
+
files: 0,
|
|
834
|
+
sessions: 0,
|
|
835
|
+
bytes: 0,
|
|
836
|
+
sources: [],
|
|
837
|
+
cleared: cleared ?? false,
|
|
838
|
+
};
|
|
839
|
+
return reading(rt, async (s) => {
|
|
840
|
+
const sync = syncHistory(rt);
|
|
841
|
+
if (opts.wait)
|
|
842
|
+
await sync;
|
|
843
|
+
else
|
|
844
|
+
sync.catch(() => { });
|
|
845
|
+
const idx = await indexOf(rt, s);
|
|
846
|
+
const sources = idx ? await sourcesOf(rt, s, idx) : [];
|
|
847
|
+
const out = {
|
|
848
|
+
enabled: s.enabled,
|
|
849
|
+
path: historyIndexPath(rt),
|
|
850
|
+
...progressOf(s),
|
|
851
|
+
files: sources.reduce((n, x) => n + x.files, 0),
|
|
852
|
+
sessions: sources.reduce((n, x) => n + x.sessions, 0),
|
|
853
|
+
bytes: s.enabled ? await sizeOf(historyIndexPath(rt)) : 0,
|
|
854
|
+
sources,
|
|
855
|
+
};
|
|
856
|
+
if (cleared !== undefined)
|
|
857
|
+
out.cleared = cleared;
|
|
858
|
+
return out;
|
|
859
|
+
});
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* A snippet when every word appears, case-insensitively, in the Session's tool calls and tool results, else
|
|
863
|
+
* undefined. Only the reader's tool text is searched, never the record's other fields; nothing read is kept.
|
|
864
|
+
*/
|
|
865
|
+
async function findWords(reader, path, words, signal) {
|
|
866
|
+
const missing = new Set(words.map((w) => w.toLowerCase()));
|
|
867
|
+
let snippet;
|
|
868
|
+
try {
|
|
869
|
+
for await (const text of reader.toolText(path)) {
|
|
870
|
+
if (signal?.aborted)
|
|
871
|
+
return undefined;
|
|
872
|
+
if (!text)
|
|
873
|
+
continue;
|
|
874
|
+
const low = text.toLowerCase();
|
|
875
|
+
for (const w of missing) {
|
|
876
|
+
if (!low.includes(w))
|
|
877
|
+
continue;
|
|
878
|
+
missing.delete(w);
|
|
879
|
+
snippet ??= snippetOf(text, [w]) ?? w;
|
|
880
|
+
}
|
|
881
|
+
if (!missing.size)
|
|
882
|
+
return snippet ?? '';
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
catch {
|
|
886
|
+
// A file that went away or cannot be read is skipped.
|
|
887
|
+
}
|
|
888
|
+
return undefined;
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Reads the record files of the Sessions in scope, newest first, for `words` anywhere in them (tool output included),
|
|
892
|
+
* and yields each Session in which every word appears. Nothing read is kept. Stops when `signal` aborts.
|
|
893
|
+
*/
|
|
894
|
+
export async function* scanToolOutput(rt, q, opts = {}) {
|
|
895
|
+
q = checkQuery(rt, q);
|
|
896
|
+
const words = splitWords(q.q);
|
|
897
|
+
if (!words.length)
|
|
898
|
+
return;
|
|
899
|
+
const s = stateOf(rt);
|
|
900
|
+
// Counted as a read for as long as the scan runs, so the index stays open under it.
|
|
901
|
+
let end;
|
|
902
|
+
const running = new Promise((r) => (end = r));
|
|
903
|
+
s.reads.add(running);
|
|
904
|
+
try {
|
|
905
|
+
yield* scan(rt, s, q, words, opts);
|
|
906
|
+
}
|
|
907
|
+
finally {
|
|
908
|
+
s.reads.delete(running);
|
|
909
|
+
end();
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
async function* scan(rt, s, q, words, opts) {
|
|
913
|
+
if (!s.built)
|
|
914
|
+
await syncHistory(rt);
|
|
915
|
+
const idx = await indexOf(rt, s);
|
|
916
|
+
if (!idx)
|
|
917
|
+
throw new UserError(UNAVAILABLE, { code: 'history-unavailable' });
|
|
918
|
+
const f = await filtersOf(rt, idx, q);
|
|
919
|
+
const files = idx.paths({ ...f, scripts: true });
|
|
920
|
+
const labels = accountLabels(rt, await rt.accounts());
|
|
921
|
+
const names = namesOf(idx);
|
|
922
|
+
// Sessions are known by Account and id: a row is written again (with a new number) when its file changes mid-scan.
|
|
923
|
+
const yielded = new Set();
|
|
924
|
+
let done = 0;
|
|
925
|
+
for (const file of files) {
|
|
926
|
+
if (opts.signal?.aborted)
|
|
927
|
+
return;
|
|
928
|
+
if (yielded.has(liveKey(file.account, file.parent || file.sessionId))) {
|
|
929
|
+
opts.onProgress?.(++done, files.length);
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
const reader = historyReader(file.family, rt.families);
|
|
933
|
+
const found = reader ? await findWords(reader, file.path, words, opts.signal) : undefined;
|
|
934
|
+
if (opts.signal?.aborted)
|
|
935
|
+
return;
|
|
936
|
+
await opts.onProgress?.(++done, files.length);
|
|
937
|
+
if (found === undefined)
|
|
938
|
+
continue;
|
|
939
|
+
const target = (file.parent && idx.parentOf(file.account, file.parent)) || idx.idOf(file.path);
|
|
940
|
+
const row = target === undefined ? undefined : idx.rows([target])[0];
|
|
941
|
+
if (!row || (row.script && !q.scripts))
|
|
942
|
+
continue;
|
|
943
|
+
const key = liveKey(row.account, row.sessionId);
|
|
944
|
+
if (opts.skip?.has(key))
|
|
945
|
+
continue;
|
|
946
|
+
yielded.add(key);
|
|
947
|
+
yield {
|
|
948
|
+
session: toSession(rt, row, labels, names, { snippet: found, live: opts.live?.has(key) ?? false }),
|
|
949
|
+
snippet: found,
|
|
950
|
+
};
|
|
951
|
+
}
|
|
952
|
+
}
|