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.
Files changed (159) hide show
  1. package/README.md +7 -4
  2. package/ai-tasks.json +28 -0
  3. package/dist/build.json +1 -1
  4. package/dist/src/cli/commands.d.ts +22 -1
  5. package/dist/src/cli/commands.js +815 -21
  6. package/dist/src/cli/format.d.ts +4 -0
  7. package/dist/src/cli/format.js +42 -4
  8. package/dist/src/cli/json-schemas.js +334 -4
  9. package/dist/src/cli/main.js +159 -13
  10. package/dist/src/core/accounts.d.ts +6 -0
  11. package/dist/src/core/accounts.js +12 -0
  12. package/dist/src/core/autostart.d.ts +11 -0
  13. package/dist/src/core/autostart.js +32 -5
  14. package/dist/src/core/browser-profiles.d.ts +23 -2
  15. package/dist/src/core/browser-profiles.js +148 -37
  16. package/dist/src/core/claude-settings-file.d.ts +18 -0
  17. package/dist/src/core/claude-settings-file.js +52 -3
  18. package/dist/src/core/config.d.ts +5 -0
  19. package/dist/src/core/config.js +12 -1
  20. package/dist/src/core/edit-settings.d.ts +7 -0
  21. package/dist/src/core/edit-settings.js +10 -5
  22. package/dist/src/core/history-group.d.ts +28 -0
  23. package/dist/src/core/history-group.js +47 -0
  24. package/dist/src/core/history-index.d.ts +145 -0
  25. package/dist/src/core/history-index.js +447 -0
  26. package/dist/src/core/history-project.d.ts +13 -0
  27. package/dist/src/core/history-project.js +87 -0
  28. package/dist/src/core/history.d.ts +210 -0
  29. package/dist/src/core/history.js +952 -0
  30. package/dist/src/core/inbound.d.ts +62 -0
  31. package/dist/src/core/inbound.js +215 -0
  32. package/dist/src/core/launch.d.ts +9 -1
  33. package/dist/src/core/launch.js +58 -24
  34. package/dist/src/core/live-sessions-copy.d.ts +5 -0
  35. package/dist/src/core/live-sessions-copy.js +46 -0
  36. package/dist/src/core/live-sessions-procs.d.ts +89 -0
  37. package/dist/src/core/live-sessions-procs.js +296 -0
  38. package/dist/src/core/live-sessions-title.d.ts +28 -0
  39. package/dist/src/core/live-sessions-title.js +80 -0
  40. package/dist/src/core/live-sessions.d.ts +68 -0
  41. package/dist/src/core/live-sessions.js +163 -0
  42. package/dist/src/core/login-check.d.ts +15 -0
  43. package/dist/src/core/login-check.js +32 -0
  44. package/dist/src/core/messages.d.ts +83 -0
  45. package/dist/src/core/messages.js +433 -0
  46. package/dist/src/core/project-categories.d.ts +14 -0
  47. package/dist/src/core/project-categories.js +48 -0
  48. package/dist/src/core/quota-fetch.d.ts +3 -3
  49. package/dist/src/core/quota-fetch.js +5 -5
  50. package/dist/src/core/quota-levels.d.ts +5 -0
  51. package/dist/src/core/quota-levels.js +5 -0
  52. package/dist/src/core/remote-control.d.ts +2 -0
  53. package/dist/src/core/remote-control.js +34 -59
  54. package/dist/src/core/run-link.d.ts +76 -0
  55. package/dist/src/core/run-link.js +245 -0
  56. package/dist/src/core/same-login.d.ts +4 -3
  57. package/dist/src/core/same-login.js +10 -7
  58. package/dist/src/core/session-select.d.ts +31 -0
  59. package/dist/src/core/session-select.js +44 -0
  60. package/dist/src/families/browser.d.ts +7 -18
  61. package/dist/src/families/browser.js +19 -8
  62. package/dist/src/families/claude/deliver.d.ts +2 -0
  63. package/dist/src/families/claude/deliver.js +43 -0
  64. package/dist/src/families/claude/history.d.ts +2 -0
  65. package/dist/src/families/claude/history.js +192 -0
  66. package/dist/src/families/claude/live-sessions.d.ts +13 -0
  67. package/dist/src/families/claude/live-sessions.js +117 -0
  68. package/dist/src/families/claude/messaging.d.ts +69 -0
  69. package/dist/src/families/claude/messaging.js +165 -0
  70. package/dist/src/families/claude/mod.d.ts +26 -0
  71. package/dist/src/families/claude/mod.js +105 -0
  72. package/dist/src/families/claude/session-files.d.ts +21 -0
  73. package/dist/src/families/claude/session-files.js +54 -0
  74. package/dist/src/families/codex/deliver.d.ts +5 -0
  75. package/dist/src/families/codex/deliver.js +76 -0
  76. package/dist/src/families/codex/history.d.ts +7 -0
  77. package/dist/src/families/codex/history.js +174 -0
  78. package/dist/src/families/codex/index.js +2 -0
  79. package/dist/src/families/codex/live-sessions.d.ts +12 -0
  80. package/dist/src/families/codex/live-sessions.js +193 -0
  81. package/dist/src/families/codex/quota.d.ts +3 -0
  82. package/dist/src/families/codex/quota.js +123 -0
  83. package/dist/src/families/codex/rate-limits.js +2 -0
  84. package/dist/src/families/codex/rollout.js +1 -1
  85. package/dist/src/families/grok/browser.d.ts +3 -0
  86. package/dist/src/families/grok/browser.js +5 -0
  87. package/dist/src/families/grok/history.d.ts +2 -0
  88. package/dist/src/families/grok/history.js +157 -0
  89. package/dist/src/families/grok/live-sessions.d.ts +4 -0
  90. package/dist/src/families/grok/live-sessions.js +80 -0
  91. package/dist/src/families/grok/login-key.d.ts +14 -0
  92. package/dist/src/families/grok/login-key.js +37 -0
  93. package/dist/src/families/history.d.ts +20 -0
  94. package/dist/src/families/history.js +81 -0
  95. package/dist/src/families/live-sessions.d.ts +26 -0
  96. package/dist/src/families/live-sessions.js +9 -0
  97. package/dist/src/families/login-keys.js +5 -1
  98. package/dist/src/families/messaging.d.ts +27 -0
  99. package/dist/src/families/messaging.js +6 -0
  100. package/dist/src/families/pi/history.d.ts +2 -0
  101. package/dist/src/families/pi/history.js +124 -0
  102. package/dist/src/families/pi/live-sessions.d.ts +2 -0
  103. package/dist/src/families/pi/live-sessions.js +70 -0
  104. package/dist/src/families/shared/history-text.d.ts +65 -0
  105. package/dist/src/families/shared/history-text.js +261 -0
  106. package/dist/src/menubar/hotkey.d.ts +86 -0
  107. package/dist/src/menubar/hotkey.js +159 -0
  108. package/dist/src/menubar/script.d.ts +2 -0
  109. package/dist/src/menubar/script.js +118 -22
  110. package/dist/src/menubar/snapshot.d.ts +8 -4
  111. package/dist/src/menubar/snapshot.js +45 -13
  112. package/dist/src/menubar/strings.d.ts +24 -6
  113. package/dist/src/menubar/strings.js +24 -6
  114. package/dist/src/panel/handler.d.ts +69 -0
  115. package/dist/src/panel/handler.js +686 -15
  116. package/dist/src/panel/i18n.d.ts +304 -3
  117. package/dist/src/panel/i18n.js +620 -18
  118. package/dist/src/panel/orca.d.ts +48 -0
  119. package/dist/src/panel/orca.js +153 -0
  120. package/dist/src/panel/page-logic.d.ts +255 -13
  121. package/dist/src/panel/page-logic.js +483 -1
  122. package/dist/src/panel/page-script.js +2260 -204
  123. package/dist/src/panel/page-styles.js +404 -32
  124. package/dist/src/panel/page.js +1 -0
  125. package/dist/src/plugins/check.js +16 -4
  126. package/dist/src/plugins/loader.d.ts +8 -1
  127. package/dist/src/plugins/loader.js +72 -7
  128. package/dist/src/runtime.d.ts +5 -0
  129. package/dist/src/runtime.js +27 -5
  130. package/dist/src/types.d.ts +116 -1
  131. package/dist/testing/index.d.ts +5 -0
  132. package/dist/testing/index.js +5 -0
  133. package/mods/claude/.claude-plugin/plugin.json +7 -0
  134. package/mods/claude/hooks/hooks.json +1 -0
  135. package/mods/claude/hooks/register.js +261 -0
  136. package/package.json +5 -2
  137. package/schemas/autostart.json +74 -1
  138. package/schemas/browser-set.json +110 -0
  139. package/schemas/browser.json +22 -2
  140. package/schemas/config.json +26 -1
  141. package/schemas/history-index.json +209 -0
  142. package/schemas/history-projects.json +133 -0
  143. package/schemas/history-show.json +275 -0
  144. package/schemas/history.json +410 -0
  145. package/schemas/menubar-hotkey.json +139 -0
  146. package/schemas/menubar-snapshot.json +36 -2
  147. package/schemas/menubar.json +74 -1
  148. package/schemas/messages-inbound.json +258 -0
  149. package/schemas/messages.json +164 -0
  150. package/schemas/send.json +165 -0
  151. package/schemas/sessions-copy.json +113 -0
  152. package/schemas/sessions-open-run.json +97 -0
  153. package/schemas/sessions.json +237 -0
  154. package/skills/sideby/SKILL.md +10 -5
  155. package/skills/sideby/references/accounts.md +11 -0
  156. package/skills/sideby/references/ai-tasks.md +17 -1
  157. package/skills/sideby/references/panel.md +6 -4
  158. package/skills/sideby/references/quota.md +2 -2
  159. package/skills/sideby/references/sessions.md +79 -0
@@ -0,0 +1,145 @@
1
+ import type { DatabaseSync } from 'node:sqlite';
2
+ import type { ParsedSession, TitleSource } from '../families/history.ts';
3
+ export interface SessionRow {
4
+ id: number;
5
+ account: string;
6
+ accountLabel: string;
7
+ family: string;
8
+ sessionId: string;
9
+ path: string;
10
+ cwd: string;
11
+ project: string;
12
+ cwdGone: boolean;
13
+ title: string;
14
+ titleFrom: TitleSource;
15
+ firstPrompt: string;
16
+ branch: string;
17
+ model: string;
18
+ startedAt: number;
19
+ updatedAt: number;
20
+ messages: number;
21
+ script: boolean;
22
+ parent: string;
23
+ }
24
+ export interface SessionInput {
25
+ account: string;
26
+ accountLabel: string;
27
+ family: string;
28
+ path: string;
29
+ sig: string;
30
+ project: string;
31
+ cwdGone: boolean;
32
+ session: ParsedSession;
33
+ }
34
+ export interface Filters {
35
+ project?: string;
36
+ /** Any of these Projects (a Project Category). */
37
+ projects?: string[];
38
+ family?: string;
39
+ account?: string;
40
+ /** Last activity at or after this time, ms. */
41
+ since?: number;
42
+ scripts?: boolean;
43
+ }
44
+ export interface Outline {
45
+ id: number;
46
+ updatedAt: number;
47
+ project: string;
48
+ account: string;
49
+ family: string;
50
+ }
51
+ export interface Match {
52
+ id: number;
53
+ /** Higher is better; 1 for a match that has no FTS rank (short words only). */
54
+ relevance: number;
55
+ }
56
+ export declare class HistoryIndex {
57
+ #private;
58
+ readonly path: string;
59
+ readonly keepText: boolean;
60
+ readonly db: DatabaseSync;
61
+ /** Goes up on every write, so callers can keep what they derived from the index until it changes. */
62
+ version: number;
63
+ private constructor();
64
+ /**
65
+ * Opens (and creates or upgrades) the database at `path`, or one in memory for `':memory:'`. With `keepText`
66
+ * false the prompts and replies are not stored. Undefined when this Node has no `node:sqlite` with FTS5.
67
+ */
68
+ static open(path: string, keepText: boolean): Promise<HistoryIndex | undefined>;
69
+ /** Deletes the database file and its journal files (a link among them is removed, never what it points to). */
70
+ static remove(path: string): Promise<boolean>;
71
+ close(): void;
72
+ /** The signature each known record file was read at, with its Account. */
73
+ fileSigs(): Map<string, {
74
+ sig: string;
75
+ account: string;
76
+ }>;
77
+ /** Stores one record file: its Session, or that it holds none (`session` undefined). */
78
+ put(account: string, path: string, sig: string, input?: SessionInput): void;
79
+ /** Gives each Account's Sessions its current label, in the rows and in the searchable place, where it changed. */
80
+ relabel(labels: ReadonlyMap<string, string>): void;
81
+ /** Every working directory Sessions were recorded in, with the Project and folder state stored for it. */
82
+ places(): {
83
+ cwd: string;
84
+ project: string;
85
+ gone: boolean;
86
+ }[];
87
+ /** Moves the Sessions recorded in `cwd` under `from` to Project `to`, with the folder state `gone`. */
88
+ moveProject(cwd: string, from: string, to: string, gone: boolean): void;
89
+ /** Stores that a record file could not be read, so it is tried again only once it changes. */
90
+ putFailed(account: string, path: string, sig: string): void;
91
+ /** Forgets record files that are gone. */
92
+ remove(paths: Iterable<string>): void;
93
+ /** Sets the Host's own title of an Account's Sessions kept apart from the record (Codex), unless the user named one. */
94
+ setHostTitles(account: string, titles: Map<string, string>): void;
95
+ /**
96
+ * Sessions that match every word (in title, place, prompts or replies) and the filters. Words of three characters
97
+ * or more go through the trigram index and are ranked by bm25 (title and place before prompts before replies);
98
+ * shorter ones are matched with LIKE. Subagent Sessions count for their parent (filters then apply to the parent).
99
+ */
100
+ match(words: string[], f: Filters): Match[];
101
+ /** Top-level Sessions matching the filters, newest first. */
102
+ recent(f: Filters, limit: number, offset: number): {
103
+ rows: SessionRow[];
104
+ total: number;
105
+ };
106
+ /** What grouping needs of every top-level Session matching the filters, newest first. */
107
+ outline(f: Filters): Outline[];
108
+ /** The same for the given Session ids. */
109
+ outlineOf(ids: number[]): Map<number, Outline>;
110
+ rows(ids: number[]): SessionRow[];
111
+ /** The stored prompts and replies of a Session, for a snippet. */
112
+ text(id: number): {
113
+ prompts: string;
114
+ replies: string;
115
+ };
116
+ /** How many subagent Sessions each Session (by account and id) started. */
117
+ children(rows: SessionRow[]): Map<number, number>;
118
+ /** Sessions whose id is `id` or starts with it (eight characters or more). */
119
+ find(id: string): SessionRow[];
120
+ /** Record paths of Sessions matching the filters (subagents included), newest first: what a tool-output scan reads. */
121
+ paths(f: Filters): {
122
+ path: string;
123
+ sessionId: string;
124
+ parent: string;
125
+ account: string;
126
+ family: string;
127
+ }[];
128
+ /** The row of the Session read from `path`, which stays the same while the row is written again. */
129
+ idOf(path: string): number | undefined;
130
+ /** The Session that started `child`, by Account and id. */
131
+ parentOf(account: string, sessionId: string): number | undefined;
132
+ /** Every Project with how many top-level Sessions it has and their last activity. */
133
+ projects(f: Filters): {
134
+ project: string;
135
+ sessions: number;
136
+ updatedAt: number;
137
+ gone: boolean;
138
+ }[];
139
+ /** Per Account: record files known, Sessions stored, files that could not be read. */
140
+ counts(): Map<string, {
141
+ files: number;
142
+ sessions: number;
143
+ failed: number;
144
+ }>;
145
+ }
@@ -0,0 +1,447 @@
1
+ // The History Index (spec §3.33, ADR-0042): a SQLite database in sideby's state folder, through `node:sqlite`, with
2
+ // one row per record file and one per Session, and an FTS5 `trigram` table over each Session's title, place, prompts
3
+ // and replies. It holds no tool output, injected context or credential; it is rebuilt from the Hosts' files.
4
+ import { constants } from 'node:fs';
5
+ import { chmod, lstat, mkdir, open as openFile, rm } from 'node:fs/promises';
6
+ import { dirname } from 'node:path';
7
+ import { cutText } from '../families/shared/history-text.js';
8
+ import { UserError } from './errors.js';
9
+ /** Bumped whenever the tables or what a reader stores changes; an older database is dropped and rebuilt. */
10
+ const SCHEMA = 3;
11
+ let sqlite;
12
+ /** `node:sqlite` without its experimental warning (ADR-0042); undefined when this Node has none. */
13
+ function loadSqlite() {
14
+ sqlite ??= (async () => {
15
+ const emit = process.emitWarning;
16
+ process.emitWarning = ((w, ...rest) => {
17
+ const text = typeof w === 'string' ? w : w.message;
18
+ if (/SQLite/i.test(text))
19
+ return;
20
+ emit.call(process, w, ...rest);
21
+ });
22
+ try {
23
+ return await import('node:sqlite');
24
+ }
25
+ catch {
26
+ return undefined;
27
+ }
28
+ finally {
29
+ process.emitWarning = emit;
30
+ }
31
+ })();
32
+ return sqlite;
33
+ }
34
+ const COLS = `id, account, account_label AS accountLabel, family, session_id AS sessionId, path, cwd, project,
35
+ cwd_gone AS cwdGone, title, title_from AS titleFrom, first_prompt AS firstPrompt, branch, model,
36
+ started_at AS startedAt, updated_at AS updatedAt, messages, script, parent`;
37
+ function toRow(r) {
38
+ return { ...r, cwdGone: Boolean(r.cwdGone), script: Boolean(r.script) };
39
+ }
40
+ /** `"word"` for FTS5, with quotes doubled. */
41
+ const phrase = (w) => `"${w.replaceAll('"', '""')}"`;
42
+ /** `%word%` for LIKE, with the escape character and wildcards escaped. */
43
+ const like = (w) => `%${w.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
44
+ /** Words a trigram can hold: three characters or more. */
45
+ const long = (w) => [...w].length >= 3;
46
+ /** The searchable place of a Session: its Project, folder, branch and Account. */
47
+ const placeText = (project, cwd, branch, label, account) => [project, cwd, branch, label, account].filter(Boolean).join('\n');
48
+ const JOURNALS = ['', '-wal', '-shm', '-journal'];
49
+ /**
50
+ * Why the index folder of `path` may not be used: it is a link, not a folder, or not the current user's. The
51
+ * index never writes or deletes through a link (the folder or the files in it), so it cannot change someone's files.
52
+ */
53
+ async function unsafeFolder(path) {
54
+ const dir = dirname(path);
55
+ const st = await lstat(dir).catch(() => undefined);
56
+ if (!st)
57
+ return undefined;
58
+ if (st.isSymbolicLink() || !st.isDirectory() || (process.getuid && st.uid !== process.getuid()))
59
+ return `${dir} is a link or not a folder of yours, so sideby does not keep the History Index there; remove it and run the command again`;
60
+ return undefined;
61
+ }
62
+ /** Creates `path` at mode 600 if it is missing, refusing a link or anything but a plain file. */
63
+ async function plainFile(path) {
64
+ for (const suffix of JOURNALS) {
65
+ const st = await lstat(path + suffix).catch(() => undefined);
66
+ if (st && (st.isSymbolicLink() || !st.isFile()))
67
+ throw new Error(`${path + suffix} is a link or not a plain file, so sideby leaves it alone; run \`sideby history index --clear\` to remove it`);
68
+ }
69
+ const fh = await openFile(path, constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
70
+ try {
71
+ await fh.chmod(0o600);
72
+ }
73
+ finally {
74
+ await fh.close();
75
+ }
76
+ }
77
+ export class HistoryIndex {
78
+ path;
79
+ keepText;
80
+ db;
81
+ /** Goes up on every write, so callers can keep what they derived from the index until it changes. */
82
+ version = 0;
83
+ #stmts = new Map();
84
+ constructor(db, path, keepText) {
85
+ this.db = db;
86
+ this.path = path;
87
+ this.keepText = keepText;
88
+ }
89
+ /**
90
+ * Opens (and creates or upgrades) the database at `path`, or one in memory for `':memory:'`. With `keepText`
91
+ * false the prompts and replies are not stored. Undefined when this Node has no `node:sqlite` with FTS5.
92
+ */
93
+ static async open(path, keepText) {
94
+ const mod = await loadSqlite();
95
+ if (!mod)
96
+ return undefined;
97
+ if (path !== ':memory:') {
98
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 }).catch(() => undefined);
99
+ const why = await unsafeFolder(path);
100
+ if (why)
101
+ throw new Error(why);
102
+ await chmod(dirname(path), 0o700);
103
+ // Create the file at mode 600 before SQLite opens it: SQLite gives its journal files the same mode.
104
+ await plainFile(path);
105
+ }
106
+ let db;
107
+ try {
108
+ db = new mod.DatabaseSync(path);
109
+ db.exec('PRAGMA busy_timeout = 5000');
110
+ let v = db.prepare('PRAGMA user_version').get().user_version;
111
+ if (v !== SCHEMA && v !== 0 && path !== ':memory:') {
112
+ // An older database is deleted, not emptied: dropped tables leave their old text in the file's free pages.
113
+ db.close();
114
+ await HistoryIndex.remove(path);
115
+ await plainFile(path);
116
+ db = new mod.DatabaseSync(path);
117
+ db.exec('PRAGMA busy_timeout = 5000');
118
+ v = 0;
119
+ }
120
+ if (path !== ':memory:')
121
+ db.exec('PRAGMA journal_mode = WAL');
122
+ if (v !== SCHEMA) {
123
+ db.exec(`DROP TABLE IF EXISTS files; DROP TABLE IF EXISTS sessions; DROP TABLE IF EXISTS text;`);
124
+ db.exec(`
125
+ CREATE TABLE files(path TEXT PRIMARY KEY, account TEXT NOT NULL, sig TEXT NOT NULL, state TEXT NOT NULL);
126
+ CREATE TABLE sessions(
127
+ id INTEGER PRIMARY KEY, path TEXT NOT NULL UNIQUE, account TEXT NOT NULL, account_label TEXT NOT NULL,
128
+ family TEXT NOT NULL, session_id TEXT NOT NULL, cwd TEXT NOT NULL, project TEXT NOT NULL,
129
+ cwd_gone INTEGER NOT NULL, title TEXT NOT NULL, title_from TEXT NOT NULL, first_prompt TEXT NOT NULL,
130
+ branch TEXT NOT NULL, model TEXT NOT NULL, started_at INTEGER NOT NULL, updated_at INTEGER NOT NULL,
131
+ messages INTEGER NOT NULL, script INTEGER NOT NULL, parent TEXT NOT NULL);
132
+ CREATE INDEX sessions_updated ON sessions(updated_at);
133
+ CREATE INDEX sessions_sid ON sessions(session_id);
134
+ CREATE INDEX sessions_list ON sessions(parent, script, project, updated_at, cwd_gone, family, account);
135
+ CREATE VIRTUAL TABLE text USING fts5(title, place, prompts, replies, tokenize = 'trigram');
136
+ PRAGMA user_version = ${SCHEMA};`);
137
+ }
138
+ }
139
+ catch {
140
+ return undefined;
141
+ }
142
+ return new HistoryIndex(db, path, keepText);
143
+ }
144
+ /** Deletes the database file and its journal files (a link among them is removed, never what it points to). */
145
+ static async remove(path) {
146
+ const why = await unsafeFolder(path);
147
+ if (why)
148
+ throw new UserError(why);
149
+ let removed = false;
150
+ for (const p of JOURNALS.map((suffix) => path + suffix)) {
151
+ try {
152
+ await rm(p);
153
+ removed = true;
154
+ }
155
+ catch {
156
+ // not there
157
+ }
158
+ }
159
+ return removed;
160
+ }
161
+ close() {
162
+ try {
163
+ this.db.close();
164
+ }
165
+ catch {
166
+ // already closed
167
+ }
168
+ }
169
+ #q(sql) {
170
+ let s = this.#stmts.get(sql);
171
+ if (!s) {
172
+ s = this.db.prepare(sql);
173
+ this.#stmts.set(sql, s);
174
+ }
175
+ return s;
176
+ }
177
+ /** The signature each known record file was read at, with its Account. */
178
+ fileSigs() {
179
+ const out = new Map();
180
+ for (const r of this.#q('SELECT path, sig, account FROM files').all())
181
+ out.set(r.path, { sig: r.sig, account: r.account });
182
+ return out;
183
+ }
184
+ #dropSession(path) {
185
+ const old = this.#q('SELECT id FROM sessions WHERE path = ?').get(path);
186
+ if (!old)
187
+ return;
188
+ this.#q('DELETE FROM text WHERE rowid = ?').run(old.id);
189
+ this.#q('DELETE FROM sessions WHERE id = ?').run(old.id);
190
+ }
191
+ /** Stores one record file: its Session, or that it holds none (`session` undefined). */
192
+ put(account, path, sig, input) {
193
+ this.db.exec('BEGIN IMMEDIATE');
194
+ try {
195
+ this.#dropSession(path);
196
+ this.#q('INSERT OR REPLACE INTO files(path, account, sig, state) VALUES (?, ?, ?, ?)').run(path, account, sig, input ? 'ok' : 'empty');
197
+ if (input) {
198
+ const s = input.session;
199
+ const time = (iso) => (iso ? Date.parse(iso) || 0 : 0);
200
+ const r = this.#q(`INSERT INTO sessions(path, account, account_label, family, session_id, cwd, project, cwd_gone, title,
201
+ title_from, first_prompt, branch, model, started_at, updated_at, messages, script, parent)
202
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(path, account, input.accountLabel, input.family, s.sessionId, s.cwd ?? '', input.project, input.cwdGone ? 1 : 0, s.title ?? '', s.titleFrom, cutText(s.prompts[0] ?? '', 2000), s.branch ?? '', s.model ?? '', time(s.startedAt), time(s.updatedAt) || time(s.startedAt), s.messages, s.script ? 1 : 0, s.parent ?? '');
203
+ this.#q('INSERT INTO text(rowid, title, place, prompts, replies) VALUES (?, ?, ?, ?, ?)').run(Number(r.lastInsertRowid), s.title ?? '', placeText(input.project, s.cwd ?? '', s.branch ?? '', input.accountLabel, input.account), this.keepText ? s.prompts.join('\n') : '', this.keepText ? s.replies.join('\n') : '');
204
+ }
205
+ this.db.exec('COMMIT');
206
+ this.version++;
207
+ }
208
+ catch (err) {
209
+ this.db.exec('ROLLBACK');
210
+ throw err;
211
+ }
212
+ }
213
+ /** Gives each Account's Sessions its current label, in the rows and in the searchable place, where it changed. */
214
+ relabel(labels) {
215
+ const stale = this.#q('SELECT DISTINCT account, account_label AS label FROM sessions').all().filter((r) => labels.has(r.account) && labels.get(r.account) !== r.label);
216
+ if (!stale.length)
217
+ return;
218
+ this.db.exec('BEGIN IMMEDIATE');
219
+ try {
220
+ for (const { account } of stale) {
221
+ const label = labels.get(account);
222
+ const rows = this.#q('SELECT id, project, cwd, branch FROM sessions WHERE account = ?').all(account);
223
+ this.#q('UPDATE sessions SET account_label = ? WHERE account = ?').run(label, account);
224
+ for (const r of rows)
225
+ this.#q('UPDATE text SET place = ? WHERE rowid = ?').run(placeText(r.project, r.cwd, r.branch, label, account), r.id);
226
+ }
227
+ this.db.exec('COMMIT');
228
+ this.version++;
229
+ }
230
+ catch (err) {
231
+ this.db.exec('ROLLBACK');
232
+ throw err;
233
+ }
234
+ }
235
+ /** Every working directory Sessions were recorded in, with the Project and folder state stored for it. */
236
+ places() {
237
+ return this.#q("SELECT DISTINCT cwd, project, cwd_gone AS gone FROM sessions WHERE cwd != ''").all().map((r) => ({ cwd: r.cwd, project: r.project, gone: r.gone === 1 }));
238
+ }
239
+ /** Moves the Sessions recorded in `cwd` under `from` to Project `to`, with the folder state `gone`. */
240
+ moveProject(cwd, from, to, gone) {
241
+ this.db.exec('BEGIN IMMEDIATE');
242
+ try {
243
+ const rows = this.#q('SELECT id, branch, account_label AS label, account FROM sessions WHERE cwd = ? AND project = ?').all(cwd, from);
244
+ this.#q('UPDATE sessions SET project = ?, cwd_gone = ? WHERE cwd = ? AND project = ?').run(to, gone ? 1 : 0, cwd, from);
245
+ for (const r of rows)
246
+ this.#q('UPDATE text SET place = ? WHERE rowid = ?').run(placeText(to, cwd, r.branch, r.label, r.account), r.id);
247
+ this.db.exec('COMMIT');
248
+ this.version++;
249
+ }
250
+ catch (err) {
251
+ this.db.exec('ROLLBACK');
252
+ throw err;
253
+ }
254
+ }
255
+ /** Stores that a record file could not be read, so it is tried again only once it changes. */
256
+ putFailed(account, path, sig) {
257
+ this.#q('INSERT OR REPLACE INTO files(path, account, sig, state) VALUES (?, ?, ?, ?)').run(path, account, sig, 'fail');
258
+ }
259
+ /** Forgets record files that are gone. */
260
+ remove(paths) {
261
+ const list = [...paths];
262
+ if (!list.length)
263
+ return;
264
+ this.db.exec('BEGIN IMMEDIATE');
265
+ try {
266
+ for (const p of list) {
267
+ this.#dropSession(p);
268
+ this.#q('DELETE FROM files WHERE path = ?').run(p);
269
+ }
270
+ this.db.exec('COMMIT');
271
+ this.version++;
272
+ }
273
+ catch (err) {
274
+ this.db.exec('ROLLBACK');
275
+ throw err;
276
+ }
277
+ }
278
+ /** Sets the Host's own title of an Account's Sessions kept apart from the record (Codex), unless the user named one. */
279
+ setHostTitles(account, titles) {
280
+ if (!titles.size)
281
+ return;
282
+ const rows = this.#q("SELECT id, session_id AS sid, title FROM sessions WHERE account = ? AND title_from != 'user'").all(account);
283
+ const changed = rows.filter((r) => {
284
+ const t = titles.get(r.sid);
285
+ return t && t !== r.title;
286
+ });
287
+ if (!changed.length)
288
+ return;
289
+ this.db.exec('BEGIN IMMEDIATE');
290
+ try {
291
+ for (const r of changed) {
292
+ const t = titles.get(r.sid);
293
+ this.#q("UPDATE sessions SET title = ?, title_from = 'host' WHERE id = ?").run(t, r.id);
294
+ this.#q('UPDATE text SET title = ? WHERE rowid = ?').run(t, r.id);
295
+ }
296
+ this.db.exec('COMMIT');
297
+ this.version++;
298
+ }
299
+ catch (err) {
300
+ this.db.exec('ROLLBACK');
301
+ throw err;
302
+ }
303
+ }
304
+ /** SQL for the filters, over the columns `col` names (a table alias, or the parent-or-self of a match). */
305
+ #where(f, col = (n) => `s.${n}`) {
306
+ const parts = [];
307
+ const args = [];
308
+ if (f.project !== undefined) {
309
+ parts.push(`${col('project')} = ?`);
310
+ args.push(f.project);
311
+ }
312
+ if (f.projects) {
313
+ parts.push(`${col('project')} IN (SELECT value FROM json_each(?))`);
314
+ args.push(JSON.stringify(f.projects));
315
+ }
316
+ if (f.family) {
317
+ parts.push(`${col('family')} = ?`);
318
+ args.push(f.family);
319
+ }
320
+ if (f.account) {
321
+ parts.push(`${col('account')} = ?`);
322
+ args.push(f.account);
323
+ }
324
+ if (f.since) {
325
+ parts.push(`${col('updated_at')} >= ?`);
326
+ args.push(f.since);
327
+ }
328
+ if (!f.scripts)
329
+ parts.push(`${col('script')} = 0`);
330
+ return { sql: parts.length ? parts.join(' AND ') : '1', args };
331
+ }
332
+ /**
333
+ * Sessions that match every word (in title, place, prompts or replies) and the filters. Words of three characters
334
+ * or more go through the trigram index and are ranked by bm25 (title and place before prompts before replies);
335
+ * shorter ones are matched with LIKE. Subagent Sessions count for their parent (filters then apply to the parent).
336
+ */
337
+ match(words, f) {
338
+ const longs = words.filter(long);
339
+ const shorts = words.filter((w) => !long(w));
340
+ const args = [];
341
+ const conds = [];
342
+ let rank = '1.0';
343
+ if (longs.length) {
344
+ conds.push('text MATCH ?');
345
+ args.push(longs.map(phrase).join(' '));
346
+ rank = '-bm25(text, 6.0, 4.0, 2.0, 1.0)';
347
+ }
348
+ for (const w of shorts) {
349
+ conds.push("(text.title LIKE ? ESCAPE '\\' OR text.place LIKE ? ESCAPE '\\' OR text.prompts LIKE ? ESCAPE '\\' OR text.replies LIKE ? ESCAPE '\\')");
350
+ const l = like(w);
351
+ args.push(l, l, l, l);
352
+ }
353
+ // Lift a matching subagent Session to its parent, and apply the filters to whichever row stands for it.
354
+ const where = this.#where(f, (n) => `coalesce(p.${n}, s.${n})`);
355
+ return this.#q(`WITH hits(id, rel) AS MATERIALIZED (SELECT text.rowid, ${rank} FROM text WHERE ${conds.join(' AND ') || '1'})
356
+ SELECT coalesce(p.id, s.id) AS id, max(h.rel) AS relevance
357
+ FROM hits h JOIN sessions s ON s.id = h.id
358
+ LEFT JOIN sessions p ON s.parent != '' AND p.account = s.account AND p.session_id = s.parent AND p.parent = ''
359
+ WHERE ${where.sql} GROUP BY 1`)
360
+ .all(...args, ...where.args)
361
+ .map((r) => {
362
+ const m = r;
363
+ return { id: m.id, relevance: Math.max(m.relevance, 1e-6) };
364
+ });
365
+ }
366
+ /** Top-level Sessions matching the filters, newest first. */
367
+ recent(f, limit, offset) {
368
+ const w = this.#where(f);
369
+ const base = `FROM sessions s WHERE s.parent = '' AND ${w.sql}`;
370
+ const total = this.#q(`SELECT count(*) AS n ${base}`).get(...w.args).n;
371
+ const rows = this.#q(`SELECT ${COLS} ${base} ORDER BY s.updated_at DESC LIMIT ? OFFSET ?`)
372
+ .all(...w.args, limit, offset)
373
+ .map((r) => toRow(r));
374
+ return { rows, total };
375
+ }
376
+ /** What grouping needs of every top-level Session matching the filters, newest first. */
377
+ outline(f) {
378
+ const w = this.#where(f);
379
+ return this.#q(`SELECT id, updated_at AS updatedAt, project, account, family FROM sessions s
380
+ WHERE s.parent = '' AND ${w.sql} ORDER BY s.updated_at DESC, s.id DESC`).all(...w.args);
381
+ }
382
+ /** The same for the given Session ids. */
383
+ outlineOf(ids) {
384
+ const out = new Map();
385
+ if (!ids.length)
386
+ return out;
387
+ for (const r of this.#q(`SELECT id, updated_at AS updatedAt, project, account, family FROM sessions
388
+ WHERE id IN (SELECT value FROM json_each(?))`).all(JSON.stringify(ids)))
389
+ out.set(r.id, r);
390
+ return out;
391
+ }
392
+ rows(ids) {
393
+ if (!ids.length)
394
+ return [];
395
+ return this.#q(`SELECT ${COLS} FROM sessions WHERE id IN (SELECT value FROM json_each(?))`).all(JSON.stringify(ids)).map(toRow);
396
+ }
397
+ /** The stored prompts and replies of a Session, for a snippet. */
398
+ text(id) {
399
+ const r = this.#q('SELECT prompts, replies FROM text WHERE rowid = ?').get(id);
400
+ return r ?? { prompts: '', replies: '' };
401
+ }
402
+ /** How many subagent Sessions each Session (by account and id) started. */
403
+ children(rows) {
404
+ const out = new Map();
405
+ for (const r of rows) {
406
+ const n = this.#q("SELECT count(*) AS n FROM sessions WHERE parent = ? AND account = ? AND parent != ''").get(r.sessionId, r.account).n;
407
+ if (n)
408
+ out.set(r.id, n);
409
+ }
410
+ return out;
411
+ }
412
+ /** Sessions whose id is `id` or starts with it (eight characters or more). */
413
+ find(id) {
414
+ const exact = this.#q(`SELECT ${COLS} FROM sessions WHERE session_id = ?`).all(id);
415
+ if (exact.length || [...id].length < 8)
416
+ return exact.map(toRow);
417
+ return this.#q(`SELECT ${COLS} FROM sessions WHERE session_id LIKE ? ESCAPE '\\' LIMIT 20`).all(`${id.replace(/[\\%_]/g, (c) => `\\${c}`)}%`).map(toRow);
418
+ }
419
+ /** Record paths of Sessions matching the filters (subagents included), newest first: what a tool-output scan reads. */
420
+ paths(f) {
421
+ const w = this.#where({ ...f, scripts: true });
422
+ return this.#q(`SELECT s.path, s.session_id AS sessionId, s.parent, s.account, s.family FROM sessions s WHERE ${w.sql}
423
+ ORDER BY s.updated_at DESC`).all(...w.args);
424
+ }
425
+ /** The row of the Session read from `path`, which stays the same while the row is written again. */
426
+ idOf(path) {
427
+ return this.#q('SELECT id FROM sessions WHERE path = ?').get(path)?.id;
428
+ }
429
+ /** The Session that started `child`, by Account and id. */
430
+ parentOf(account, sessionId) {
431
+ return this.#q('SELECT id FROM sessions WHERE account = ? AND session_id = ?').get(account, sessionId)?.id;
432
+ }
433
+ /** Every Project with how many top-level Sessions it has and their last activity. */
434
+ projects(f) {
435
+ const w = this.#where({ ...f, project: undefined });
436
+ return this.#q(`SELECT project, count(*) AS sessions, max(updated_at) AS updatedAt, min(cwd_gone) AS gone
437
+ FROM sessions s WHERE s.parent = '' AND ${w.sql} GROUP BY project ORDER BY updatedAt DESC`).all(...w.args).map((r) => ({ ...r, gone: Boolean(r.gone) }));
438
+ }
439
+ /** Per Account: record files known, Sessions stored, files that could not be read. */
440
+ counts() {
441
+ const out = new Map();
442
+ for (const r of this.#q(`SELECT account, count(*) AS files, sum(state = 'ok') AS sessions, sum(state = 'fail') AS failed
443
+ FROM files GROUP BY account`).all())
444
+ out.set(r.account, { files: r.files, sessions: r.sessions ?? 0, failed: r.failed ?? 0 });
445
+ return out;
446
+ }
447
+ }
@@ -0,0 +1,13 @@
1
+ export interface Project {
2
+ /** The repository root, or the working directory outside a repository. */
3
+ path: string;
4
+ /** True when the working directory no longer exists. */
5
+ gone: boolean;
6
+ }
7
+ /** Resolves Projects, remembering each working directory for the life of this object. */
8
+ export declare class ProjectResolver {
9
+ #private;
10
+ resolve(cwd: string | undefined, hostRoot?: string): Promise<Project>;
11
+ }
12
+ /** A short name for a Project: its folder name, with as many parent folders as it takes to tell it from another Project of the same name. */
13
+ export declare function projectNames(paths: Iterable<string>): Map<string, string>;