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,193 @@
1
+ import { readdir, readFile, stat } from 'node:fs/promises';
2
+ import { basename, join, resolve } from 'node:path';
3
+ import { accountProcesses, headerField, isInside, isoOf, mapLimit, readHead, } from '../../core/live-sessions-procs.js';
4
+ const ROLLOUT_ID = /^rollout-.*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i;
5
+ /** Codex subcommands that serve other programs rather than run a session. */
6
+ const SERVERS = new Set(['app-server', 'exec-server', 'mcp-server', 'mcp', 'login', 'logout', 'proto']);
7
+ const INDEX_MAX = 8 * 1024 * 1024;
8
+ /** Codex options that take a value as the next word (Codex 0.163.0 `--help`). */
9
+ const VALUED = new Set([
10
+ '-c',
11
+ '--config',
12
+ '--enable',
13
+ '--disable',
14
+ '-i',
15
+ '--image',
16
+ '-m',
17
+ '--model',
18
+ '--local-provider',
19
+ '-p',
20
+ '--profile',
21
+ '-s',
22
+ '--sandbox',
23
+ '-a',
24
+ '--ask-for-approval',
25
+ '-C',
26
+ '--cd',
27
+ '--add-dir',
28
+ ]);
29
+ /**
30
+ * The subcommand of a `codex` process (`exec`, `app-server`), or undefined for a plain session or when it cannot
31
+ * be told. `argv` are the arguments after the program; `exact` says they come word by word from the system. From the
32
+ * flattened `ps` line a word could be the start of a quoted prompt (`codex "mcp integration needs fixing"`), so a
33
+ * server word counts there only when nothing but options follows it.
34
+ */
35
+ export function codexSubcommand(argv, exact) {
36
+ for (let i = 0; i < argv.length; i++) {
37
+ const a = argv[i];
38
+ if (a === '--')
39
+ return undefined;
40
+ if (a.startsWith('-')) {
41
+ if (VALUED.has(a))
42
+ i++;
43
+ continue;
44
+ }
45
+ // The first word that is not an option: a subcommand, or the prompt of a plain session.
46
+ if (exact || !SERVERS.has(a))
47
+ return a;
48
+ const after = argv[i + 1];
49
+ return after === undefined || after.startsWith('-') ? a : undefined;
50
+ }
51
+ return undefined;
52
+ }
53
+ const samePath = (a, b) => resolve(a) === resolve(b);
54
+ /** Whether a running `codex` with this `CODEX_HOME` belongs to the Account. */
55
+ export const codexHomeIs = (account, codexHome) => codexHome ? samePath(codexHome, account.dir) : account.isMain;
56
+ async function titles(dir, problems, ref) {
57
+ const out = new Map();
58
+ const file = join(dir, 'session_index.jsonl');
59
+ try {
60
+ if ((await stat(file)).size > INDEX_MAX)
61
+ return out;
62
+ for (const line of (await readFile(file, 'utf8')).split('\n')) {
63
+ if (!line)
64
+ continue;
65
+ try {
66
+ const e = JSON.parse(line);
67
+ if (typeof e.id === 'string' && typeof e.thread_name === 'string' && e.thread_name)
68
+ out.set(e.id, e.thread_name);
69
+ }
70
+ catch {
71
+ // a line cut off while Codex writes it
72
+ }
73
+ }
74
+ }
75
+ catch (err) {
76
+ // No index yet is fine; anything else only costs the titles.
77
+ if (err.code !== 'ENOENT')
78
+ problems.push(`${ref}: could not read ${file} (${err.code}), so its sessions show their directory names; check that the file is readable`);
79
+ }
80
+ return out;
81
+ }
82
+ async function fromRollout(path, extra, names, problems, ref) {
83
+ const idFromName = ROLLOUT_ID.exec(basename(path))?.[1];
84
+ let head = '';
85
+ try {
86
+ head = await readHead(path);
87
+ }
88
+ catch (err) {
89
+ if (err.code !== 'ENOENT')
90
+ problems.push(`${ref}: could not read ${path} (${err.code}); check that the file is readable`);
91
+ return null;
92
+ }
93
+ const sessionId = headerField(head, 'id') ?? idFromName;
94
+ if (!sessionId)
95
+ return null;
96
+ const cwd = headerField(head, 'cwd');
97
+ const started = headerField(head, 'timestamp');
98
+ let mtime;
99
+ try {
100
+ mtime = (await stat(path)).mtimeMs;
101
+ }
102
+ catch {
103
+ // removed meanwhile
104
+ }
105
+ const title = names.get(sessionId) ?? (cwd ? basename(cwd) : undefined);
106
+ return {
107
+ sessionId,
108
+ ...(title ? { title } : {}),
109
+ status: 'unknown',
110
+ ...(cwd ? { cwd } : {}),
111
+ ...(extra.pid !== undefined ? { pid: extra.pid } : {}),
112
+ ...(started ? { startedAt: started } : {}),
113
+ ...(isoOf(mtime) ? { updatedAt: isoOf(mtime) } : {}),
114
+ guessed: extra.guessed,
115
+ transcript: path,
116
+ };
117
+ }
118
+ /**
119
+ * The newest rollout under `root`. A folder that cannot be read throws (the Account's sessions cannot be known); a
120
+ * file that cannot be looked at is named in `problems`; one removed meanwhile is skipped.
121
+ */
122
+ async function newestRollout(root, problems, ref) {
123
+ let entries;
124
+ try {
125
+ entries = await readdir(root, { recursive: true, withFileTypes: true });
126
+ }
127
+ catch (err) {
128
+ if (err.code === 'ENOENT')
129
+ return undefined;
130
+ throw err;
131
+ }
132
+ let best;
133
+ for (const e of entries) {
134
+ if (!e.isFile() || !ROLLOUT_ID.test(e.name))
135
+ continue;
136
+ const path = join(e.parentPath, e.name);
137
+ try {
138
+ const { mtimeMs } = await stat(path);
139
+ if (!best || mtimeMs > best.mtimeMs)
140
+ best = { path, mtimeMs };
141
+ }
142
+ catch (err) {
143
+ if (err.code !== 'ENOENT')
144
+ problems.push(`${ref}: could not read ${path} (${err.code}); check that the file is readable`);
145
+ }
146
+ }
147
+ return best;
148
+ }
149
+ export const codexLiveSessions = {
150
+ family: 'codex',
151
+ async read(account, procs, problems) {
152
+ const mine = await accountProcesses(procs, {
153
+ bin: 'codex',
154
+ envName: 'CODEX_HOME',
155
+ belongs: (home) => codexHomeIs(account, home),
156
+ skip: (argv, exact) => SERVERS.has(codexSubcommand(argv, exact) ?? ''),
157
+ }, problems);
158
+ if (!mine.length)
159
+ return [];
160
+ const root = join(account.dir, 'sessions');
161
+ // Only a missing directory means "no sessions yet"; another error is the Account's to report.
162
+ try {
163
+ await readdir(root);
164
+ }
165
+ catch (err) {
166
+ if (err.code === 'ENOENT')
167
+ return [];
168
+ throw err;
169
+ }
170
+ const names = await titles(account.dir, problems, account.ref);
171
+ const seen = new Set();
172
+ const out = [];
173
+ // `lsof` takes a moment per process: ask a few at once.
174
+ const open = await mapLimit(mine, 4, async (pid) => ({ pid, files: await procs.openFiles(pid) }));
175
+ for (const { pid, files } of open) {
176
+ for (const f of files) {
177
+ if (!isInside(root, f) || !ROLLOUT_ID.test(basename(f)))
178
+ continue;
179
+ const s = await fromRollout(f, { pid, guessed: false }, names, problems, account.ref);
180
+ if (s && !seen.has(s.sessionId)) {
181
+ seen.add(s.sessionId);
182
+ out.push(s);
183
+ }
184
+ }
185
+ }
186
+ if (out.length)
187
+ return out;
188
+ // Codex may write its rollout without keeping it open: the newest one is a guess.
189
+ const newest = await newestRollout(root, problems, account.ref);
190
+ const guess = newest && (await fromRollout(newest.path, { guessed: true }, names, problems, account.ref));
191
+ return guess ? [guess] : [];
192
+ },
193
+ };
@@ -0,0 +1,3 @@
1
+ import type { Account, QuotaFetch, QuotaFetchContext, QuotaResult } from '../../types.ts';
2
+ export declare function fetchCodexQuota(account: Account, ctx: QuotaFetchContext): Promise<QuotaResult>;
3
+ export declare const codexQuotaFetch: QuotaFetch;
@@ -0,0 +1,123 @@
1
+ // Current quota through Codex's documented app-server protocol (ADR-0038). The Host handles its own login;
2
+ // no thread, model turn, credential extraction or direct HTTP request.
3
+ import { spawn } from 'node:child_process';
4
+ import { tmpdir } from 'node:os';
5
+ import { createInterface } from 'node:readline';
6
+ import { isObj, rateLimits } from './rate-limits.js';
7
+ const failed = (detail) => ({ status: 'unavailable', reason: 'fetch-failed', detail });
8
+ /** Prefer the general Codex bucket; a model-specific bucket is not the account's general quota. */
9
+ function quotaAnswer(result) {
10
+ if (!isObj(result))
11
+ return failed('Codex returned no quota; update Codex, then refresh');
12
+ const buckets = result.rateLimitsByLimitId;
13
+ const raw = buckets === undefined || buckets === null ? result.rateLimits : isObj(buckets) ? buckets.codex : null;
14
+ if (!isObj(raw) || (raw.limitId !== undefined && raw.limitId !== 'codex'))
15
+ return failed('Codex returned no general quota; update Codex, then refresh');
16
+ const window = (w) => isObj(w)
17
+ ? {
18
+ used_percent: w.usedPercent,
19
+ window_minutes: w.windowDurationMins,
20
+ resets_at: w.resetsAt,
21
+ }
22
+ : w;
23
+ const parsed = rateLimits({
24
+ rate_limits: {
25
+ limit_id: 'codex',
26
+ primary: window(raw.primary),
27
+ secondary: window(raw.secondary),
28
+ plan_type: raw.planType,
29
+ },
30
+ });
31
+ if (!parsed)
32
+ return failed('Codex returned an unrecognized quota; update Codex, then refresh');
33
+ return {
34
+ status: 'ok',
35
+ ...parsed,
36
+ observedAt: new Date().toISOString(),
37
+ source: 'codex app-server account/rateLimits/read',
38
+ };
39
+ }
40
+ export async function fetchCodexQuota(account, ctx) {
41
+ if (ctx.signal.aborted)
42
+ return failed('the Codex quota check was stopped; refresh to try again');
43
+ const args = [...(!account.isMain ? ['-c', 'cli_auth_credentials_store="file"'] : []), 'app-server'];
44
+ const child = spawn('codex', args, {
45
+ cwd: tmpdir(),
46
+ env: ctx.hostEnv,
47
+ stdio: ['pipe', 'pipe', 'ignore'],
48
+ });
49
+ const lines = createInterface({ input: child.stdout });
50
+ return new Promise((resolve) => {
51
+ let done = false;
52
+ let pending = 1;
53
+ const stop = () => {
54
+ if (child.exitCode === null && child.signalCode === null)
55
+ child.kill('SIGTERM');
56
+ };
57
+ const settle = (q) => {
58
+ if (done)
59
+ return;
60
+ done = true;
61
+ ctx.signal.removeEventListener('abort', abort);
62
+ lines.close();
63
+ child.stdin.end();
64
+ // Only this short-lived query process is ended, never an existing Codex session.
65
+ const timer = setTimeout(stop, 1000);
66
+ timer.unref();
67
+ child.once('close', () => clearTimeout(timer));
68
+ resolve(q);
69
+ };
70
+ const abort = () => {
71
+ stop();
72
+ settle(failed('the Codex quota check was stopped; refresh to try again'));
73
+ };
74
+ const send = (request) => child.stdin.write(`${JSON.stringify(request)}\n`);
75
+ child.stdin.on('error', () => settle(failed('Codex closed the quota query; refresh to try again')));
76
+ child.on('error', (err) => settle(failed(err.code === 'ENOENT'
77
+ ? 'Codex is not installed or not on PATH; install Codex, then refresh'
78
+ : 'could not start Codex; check its installation, then refresh')));
79
+ child.on('close', () => settle(failed('Codex exited without answering; update Codex, then refresh')));
80
+ ctx.signal.addEventListener('abort', abort, { once: true });
81
+ lines.on('line', (line) => {
82
+ if (done)
83
+ return;
84
+ let msg;
85
+ try {
86
+ msg = JSON.parse(line);
87
+ }
88
+ catch {
89
+ return;
90
+ }
91
+ if (!isObj(msg) || msg.id !== pending)
92
+ return;
93
+ if (isObj(msg.error)) {
94
+ // Never include the Host's raw error: it may contain credentials or account identifiers.
95
+ const detail = msg.error.code === -32601
96
+ ? 'this Codex version cannot report quota; update Codex, then refresh'
97
+ : `Codex could not read quota; refresh or run \`sideby login ${account.ref}\` if signed out`;
98
+ settle(failed(detail));
99
+ }
100
+ else if (pending === 1) {
101
+ pending = 2;
102
+ send({ method: 'initialized' });
103
+ send({ id: 2, method: 'account/rateLimits/read' });
104
+ }
105
+ else {
106
+ settle(quotaAnswer(msg.result));
107
+ }
108
+ });
109
+ send({
110
+ id: 1,
111
+ method: 'initialize',
112
+ params: { clientInfo: { name: 'sideby', version: '1' }, capabilities: { experimentalApi: false } },
113
+ });
114
+ if (ctx.signal.aborted)
115
+ abort();
116
+ });
117
+ }
118
+ export const codexQuotaFetch = {
119
+ everyMinutes: 15,
120
+ summary: 'Ask Codex for each account’s current quota every 15 minutes',
121
+ localFallbackOnly: true,
122
+ fetch: fetchCodexQuota,
123
+ };
@@ -32,6 +32,8 @@ export function rateLimits(payload) {
32
32
  const rl = payload.rate_limits;
33
33
  if (!isObj(rl))
34
34
  return null;
35
+ if (rl.limit_id !== undefined && rl.limit_id !== 'codex')
36
+ return null;
35
37
  const primary = quotaWindow(rl.primary);
36
38
  if (!primary)
37
39
  return null;
@@ -83,7 +83,7 @@ async function fileLimits(file) {
83
83
  return { best, failed: read.failed };
84
84
  }
85
85
  /** Parsed `rate_limits` per Account directory; a rollout is read again only after it changed. */
86
- export const codexQuotaMemo = new FileMemo({ name: 'codex-quota', version: 1 });
86
+ export const codexQuotaMemo = new FileMemo({ name: 'codex-quota', version: 2 });
87
87
  /** Newest well-formed `rate_limits` across the newest rollout files, by event timestamp. */
88
88
  export async function readCodexQuota(dir) {
89
89
  const files = (await listRollouts(dir)).slice(0, MAX_QUOTA_FILES);
@@ -0,0 +1,3 @@
1
+ import type { Account } from '../../types.ts';
2
+ /** `user_id` of the sign-in entry in `auth.json`, only for matching; it never leaves the Runtime. */
3
+ export declare function grokSignInId(account: Account): Promise<string | undefined>;
@@ -0,0 +1,5 @@
1
+ import { grokSignInIds } from './login-key.js';
2
+ /** `user_id` of the sign-in entry in `auth.json`, only for matching; it never leaves the Runtime. */
3
+ export async function grokSignInId(account) {
4
+ return (await grokSignInIds(account))?.user;
5
+ }
@@ -0,0 +1,2 @@
1
+ import type { HistoryReader } from '../history.ts';
2
+ export declare const grokHistory: HistoryReader;
@@ -0,0 +1,157 @@
1
+ // Grok Build's Session History (spec §3.33): one folder `sessions/<encodeURIComponent(cwd)>/<id>/` per Session (tried
2
+ // with Grok Build 1.0.62 on 2026-10-20). `summary.json` gives the title, repository root, branch, model and times;
3
+ // `chat_history.jsonl` the conversation. `session_kind` is empty for a Session a person started, and `headless` or
4
+ // `subagent…` for a Script Session.
5
+ import { readFile } from 'node:fs/promises';
6
+ import { basename, dirname, join } from 'node:path';
7
+ import { blockText, dirEntries, fileLines, historyFile, isoTime, jsonText, parseRecord, SessionText, str, titleFromText, typedText, } from '../shared/history-text.js';
8
+ const CHAT = 'chat_history.jsonl';
9
+ function decodeCwd(name) {
10
+ try {
11
+ const d = decodeURIComponent(name);
12
+ return d.startsWith('/') ? d : undefined;
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ }
18
+ function promptOf(r) {
19
+ if (r.synthetic_reason !== undefined && r.synthetic_reason !== null)
20
+ return '';
21
+ return typedText(blockText(r.content));
22
+ }
23
+ const replyOf = (r) => blockText(r.content).trim();
24
+ function toolNames(r) {
25
+ if (!Array.isArray(r.tool_calls))
26
+ return [];
27
+ return r.tool_calls.map((c) => {
28
+ const fn = c ?? {};
29
+ return str(fn.function?.name) ?? str(fn.name) ?? 'tool';
30
+ });
31
+ }
32
+ export const grokHistory = {
33
+ family: 'grok',
34
+ async list(account) {
35
+ const out = [];
36
+ const root = join(account.dir, 'sessions');
37
+ for (const c of await dirEntries(root)) {
38
+ if (!c.isDirectory())
39
+ continue;
40
+ for (const s of await dirEntries(join(root, c.name))) {
41
+ if (!s.isDirectory())
42
+ continue;
43
+ const dir = join(root, c.name, s.name);
44
+ const f = await historyFile(join(dir, CHAT), { also: join(dir, 'summary.json') });
45
+ if (f)
46
+ out.push(f);
47
+ }
48
+ }
49
+ return out;
50
+ },
51
+ async parse(file) {
52
+ const dir = dirname(file.path);
53
+ let summary = {};
54
+ try {
55
+ summary = parseRecord(await readFile(join(dir, 'summary.json'), 'utf8')) ?? {};
56
+ }
57
+ catch (err) {
58
+ if (err.code !== 'ENOENT')
59
+ throw err;
60
+ }
61
+ const text = new SessionText();
62
+ let first;
63
+ let last;
64
+ for await (const line of fileLines(file.path)) {
65
+ if (!/"type":"(user|assistant)"/.test(line))
66
+ continue;
67
+ const rec = parseRecord(line);
68
+ if (!rec)
69
+ continue;
70
+ const at = isoTime(rec.timestamp);
71
+ if (at) {
72
+ first ??= at;
73
+ last = at;
74
+ }
75
+ if (rec.type === 'user') {
76
+ const t = promptOf(rec);
77
+ if (t)
78
+ text.prompt(t);
79
+ }
80
+ else {
81
+ const t = replyOf(rec);
82
+ if (t)
83
+ text.reply(t);
84
+ }
85
+ }
86
+ if (!text.count)
87
+ return undefined;
88
+ const kind = str(summary.session_kind);
89
+ const hostTitle = str(summary.generated_title)?.trim();
90
+ const s = {
91
+ sessionId: basename(dir),
92
+ titleFrom: hostTitle ? 'host' : text.first ? 'prompt' : 'none',
93
+ messages: text.count,
94
+ script: Boolean(kind),
95
+ prompts: text.prompts,
96
+ replies: text.replies,
97
+ ...(text.cut ? { cut: true } : {}),
98
+ };
99
+ const title = hostTitle ? titleFromText(hostTitle) : text.first && titleFromText(text.first);
100
+ if (title)
101
+ s.title = title;
102
+ const cwd = decodeCwd(basename(dirname(dir)));
103
+ if (cwd)
104
+ s.cwd = cwd;
105
+ const root = str(summary.git_root_dir);
106
+ if (root)
107
+ s.gitRoot = root;
108
+ const branch = str(summary.head_branch);
109
+ if (branch)
110
+ s.branch = branch;
111
+ const model = str(summary.current_model_id);
112
+ if (model)
113
+ s.model = model;
114
+ const startedAt = isoTime(summary.created_at) ?? first;
115
+ const updatedAt = isoTime(summary.last_active_at) ?? isoTime(summary.updated_at) ?? last;
116
+ if (startedAt)
117
+ s.startedAt = startedAt;
118
+ if (updatedAt)
119
+ s.updatedAt = updatedAt;
120
+ return s;
121
+ },
122
+ async *messages(path) {
123
+ for await (const line of fileLines(path)) {
124
+ if (!/"type":"(user|assistant)"/.test(line))
125
+ continue;
126
+ const rec = parseRecord(line);
127
+ if (!rec)
128
+ continue;
129
+ const at = isoTime(rec.timestamp);
130
+ const when = at ? { at } : {};
131
+ if (rec.type === 'user') {
132
+ const text = promptOf(rec);
133
+ if (text)
134
+ yield { role: 'user', text, ...when };
135
+ }
136
+ else {
137
+ const text = replyOf(rec);
138
+ if (text)
139
+ yield { role: 'assistant', text, ...when };
140
+ for (const tool of toolNames(rec))
141
+ yield { role: 'tool', text: tool, tool, ...when };
142
+ }
143
+ }
144
+ },
145
+ async *toolText(path) {
146
+ for await (const line of fileLines(path)) {
147
+ const rec = parseRecord(line);
148
+ if (!rec)
149
+ continue;
150
+ if (rec.type === 'tool' || (rec.type === 'user' && rec.synthetic_reason === 'tool_result'))
151
+ yield jsonText(rec.content);
152
+ else if (rec.type === 'assistant' && Array.isArray(rec.tool_calls))
153
+ for (const c of rec.tool_calls)
154
+ yield jsonText(c?.function?.arguments ?? c?.arguments);
155
+ }
156
+ },
157
+ };
@@ -0,0 +1,4 @@
1
+ import type { LiveSessionReader } from '../live-sessions.ts';
2
+ /** A session's own directory: `sessions/<encoded cwd>/<id>/`. */
3
+ export declare const grokSessionDir: (dir: string, cwd: string, id: string) => string;
4
+ export declare const grokLiveSessions: LiveSessionReader;
@@ -0,0 +1,80 @@
1
+ // Grok Build's Live Sessions (spec §3.32): `<dir>/active_sessions.json` lists each running session with its pid and
2
+ // the process start time in microseconds (tried with Grok Build on 2026-10-20). The title is Grok's own
3
+ // `generated_title` from the session's `summary.json`.
4
+ import { readFile } from 'node:fs/promises';
5
+ import { basename, join } from 'node:path';
6
+ import { statOrNull } from '../../core/fs-safe.js';
7
+ import { sameStart } from '../../core/live-sessions-procs.js';
8
+ const str = (v) => (typeof v === 'string' && v ? v : undefined);
9
+ /** A session's own directory: `sessions/<encoded cwd>/<id>/`. */
10
+ export const grokSessionDir = (dir, cwd, id) => join(dir, 'sessions', encodeURIComponent(cwd), id);
11
+ async function summaryOf(sessionDir) {
12
+ try {
13
+ const s = JSON.parse(await readFile(join(sessionDir, 'summary.json'), 'utf8'));
14
+ return s && typeof s === 'object' && !Array.isArray(s) ? s : {};
15
+ }
16
+ catch {
17
+ return {};
18
+ }
19
+ }
20
+ export const grokLiveSessions = {
21
+ family: 'grok',
22
+ async read(account, procs, problems) {
23
+ const file = join(account.dir, 'active_sessions.json');
24
+ let raw;
25
+ try {
26
+ raw = await readFile(file, 'utf8');
27
+ }
28
+ catch (err) {
29
+ if (err.code === 'ENOENT')
30
+ return [];
31
+ throw err;
32
+ }
33
+ let list;
34
+ try {
35
+ list = JSON.parse(raw);
36
+ }
37
+ catch {
38
+ problems.push(`${account.ref}: could not read ${file}; Grok Build rewrites it when a session starts or ends`);
39
+ return [];
40
+ }
41
+ if (!Array.isArray(list))
42
+ return [];
43
+ const out = [];
44
+ for (const e of list) {
45
+ const sessionId = str(e?.session_id);
46
+ const pid = typeof e?.pid === 'number' ? e.pid : undefined;
47
+ if (!sessionId || pid === undefined)
48
+ continue;
49
+ const proc = await procs.get(pid);
50
+ if (!proc)
51
+ continue;
52
+ // The pid may have been reused since; without a start time the entry cannot be tied to this process.
53
+ if (typeof e.pid_start !== 'number' || !Number.isFinite(e.pid_start)) {
54
+ problems.push(`${account.ref}: an entry of ${file} has no start time, so sideby cannot tell whether process ${pid} still runs session ${sessionId.slice(0, 8)} and leaves it out; Grok Build writes it again when the session restarts`);
55
+ continue;
56
+ }
57
+ if (!sameStart(proc, e.pid_start / 1000))
58
+ continue;
59
+ const cwd = str(e.cwd);
60
+ const sessionDir = cwd ? grokSessionDir(account.dir, cwd, sessionId) : undefined;
61
+ const summary = sessionDir ? await summaryOf(sessionDir) : {};
62
+ const title = str(summary.generated_title) ?? str(summary.session_summary) ?? (cwd ? basename(cwd) : undefined);
63
+ const opened = str(e.opened_at);
64
+ const updated = str(summary.updated_at) ?? str(summary.last_active_at) ?? opened;
65
+ const transcript = sessionDir ? join(sessionDir, 'chat_history.jsonl') : undefined;
66
+ out.push({
67
+ sessionId,
68
+ ...(title ? { title } : {}),
69
+ status: 'unknown',
70
+ ...(cwd ? { cwd } : {}),
71
+ pid,
72
+ ...(opened ? { startedAt: opened } : {}),
73
+ ...(updated ? { updatedAt: updated } : {}),
74
+ guessed: false,
75
+ ...(transcript && (await statOrNull(transcript)) ? { transcript } : {}),
76
+ });
77
+ }
78
+ return out;
79
+ },
80
+ };
@@ -0,0 +1,14 @@
1
+ import type { Account } from '../../types.ts';
2
+ /**
3
+ * `user_id` and `team_id` of the single sign-in entry in `auth.json`; tokens and every other field are dropped at
4
+ * once. A missing or null `team_id` is ''. Undefined on any problem or an unexpected shape.
5
+ */
6
+ export declare function grokSignInIds(account: Account): Promise<{
7
+ user: string;
8
+ team: string;
9
+ } | undefined>;
10
+ /**
11
+ * A hash of `user_id` and `team_id`, cut to 16 hex characters, only for comparing two Accounts while the Runtime
12
+ * groups a Same Login. Undefined on any problem: the Account then simply does not group.
13
+ */
14
+ export declare function grokLoginKey(account: Account): Promise<string | undefined>;
@@ -0,0 +1,37 @@
1
+ // Grok's Login Key (ADR-0037): which x.ai user and team an Account is signed in as, kept only as a hash.
2
+ import { createHash } from 'node:crypto';
3
+ import { readFile } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ // The shapes Grok Build writes; anything else gives no key rather than a key built from an unexpected value.
6
+ const ID = /^[A-Za-z0-9-]{8,64}$/;
7
+ /**
8
+ * `user_id` and `team_id` of the single sign-in entry in `auth.json`; tokens and every other field are dropped at
9
+ * once. A missing or null `team_id` is ''. Undefined on any problem or an unexpected shape.
10
+ */
11
+ export async function grokSignInIds(account) {
12
+ try {
13
+ const data = JSON.parse(await readFile(join(account.dir, 'auth.json'), 'utf8'));
14
+ if (typeof data !== 'object' || data === null || Array.isArray(data))
15
+ return undefined;
16
+ const entries = Object.values(data);
17
+ if (entries.length !== 1)
18
+ return undefined;
19
+ const entry = entries[0];
20
+ const user = entry?.user_id;
21
+ const team = entry?.team_id ?? '';
22
+ if (typeof user !== 'string' || !ID.test(user) || typeof team !== 'string' || (team && !ID.test(team)))
23
+ return undefined;
24
+ return { user, team };
25
+ }
26
+ catch {
27
+ return undefined;
28
+ }
29
+ }
30
+ /**
31
+ * A hash of `user_id` and `team_id`, cut to 16 hex characters, only for comparing two Accounts while the Runtime
32
+ * groups a Same Login. Undefined on any problem: the Account then simply does not group.
33
+ */
34
+ export async function grokLoginKey(account) {
35
+ const ids = await grokSignInIds(account);
36
+ return ids && createHash('sha256').update(`grok\0${ids.team}\0${ids.user}`).digest('hex').slice(0, 16);
37
+ }
@@ -0,0 +1,20 @@
1
+ import type { FamilyDef, FamilyHistory, ParsedSession } from '../types.ts';
2
+ export type { HistoryFile, HistoryMessage, ParsedSession, TitleSource } from '../types.ts';
3
+ /** A Session History reader: a built-in Family's, or a plugin Family's `history` with its Family id. */
4
+ export interface HistoryReader extends Omit<FamilyHistory, 'resumeArgs' | 'toolText'> {
5
+ family: string;
6
+ /**
7
+ * The text of the Session's tool calls (their input) and tool results, for searching tool output. Never the
8
+ * record's other fields (ids, instructions, settings), so a search cannot match or show them.
9
+ */
10
+ toolText(path: string): AsyncIterable<string>;
11
+ /** Host arguments that resume a Session; built-in Families use `hostResumeArgs`. */
12
+ resumeArgs?(sessionId: string): string[];
13
+ }
14
+ /**
15
+ * A plugin reader's Session as the built-in readers give one: the wrong shape is an error naming the Family, and its
16
+ * text and title are cut to the same limits (a plugin cannot fill the History Index or the Panel without bound).
17
+ */
18
+ export declare function checkParsed(family: string, p: ParsedSession | undefined): ParsedSession | undefined;
19
+ /** The Session History reader of a Family: a built-in one's, else the `history` a plugin Family declares. */
20
+ export declare function historyReader(familyId: string, families?: ReadonlyMap<string, FamilyDef>): HistoryReader | undefined;