sideby 0.19.0 → 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 (161) 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/file-memo.js +26 -4
  23. package/dist/src/core/history-group.d.ts +28 -0
  24. package/dist/src/core/history-group.js +47 -0
  25. package/dist/src/core/history-index.d.ts +145 -0
  26. package/dist/src/core/history-index.js +447 -0
  27. package/dist/src/core/history-project.d.ts +13 -0
  28. package/dist/src/core/history-project.js +87 -0
  29. package/dist/src/core/history.d.ts +210 -0
  30. package/dist/src/core/history.js +952 -0
  31. package/dist/src/core/inbound.d.ts +62 -0
  32. package/dist/src/core/inbound.js +215 -0
  33. package/dist/src/core/launch.d.ts +9 -1
  34. package/dist/src/core/launch.js +58 -24
  35. package/dist/src/core/live-sessions-copy.d.ts +5 -0
  36. package/dist/src/core/live-sessions-copy.js +46 -0
  37. package/dist/src/core/live-sessions-procs.d.ts +89 -0
  38. package/dist/src/core/live-sessions-procs.js +296 -0
  39. package/dist/src/core/live-sessions-title.d.ts +28 -0
  40. package/dist/src/core/live-sessions-title.js +80 -0
  41. package/dist/src/core/live-sessions.d.ts +68 -0
  42. package/dist/src/core/live-sessions.js +163 -0
  43. package/dist/src/core/login-check.d.ts +15 -0
  44. package/dist/src/core/login-check.js +32 -0
  45. package/dist/src/core/messages.d.ts +83 -0
  46. package/dist/src/core/messages.js +433 -0
  47. package/dist/src/core/project-categories.d.ts +14 -0
  48. package/dist/src/core/project-categories.js +48 -0
  49. package/dist/src/core/quota-fetch.d.ts +3 -3
  50. package/dist/src/core/quota-fetch.js +5 -5
  51. package/dist/src/core/quota-levels.d.ts +5 -0
  52. package/dist/src/core/quota-levels.js +5 -0
  53. package/dist/src/core/remote-control.d.ts +2 -0
  54. package/dist/src/core/remote-control.js +34 -59
  55. package/dist/src/core/run-link.d.ts +76 -0
  56. package/dist/src/core/run-link.js +245 -0
  57. package/dist/src/core/same-login.d.ts +4 -3
  58. package/dist/src/core/same-login.js +10 -7
  59. package/dist/src/core/session-select.d.ts +31 -0
  60. package/dist/src/core/session-select.js +44 -0
  61. package/dist/src/families/browser.d.ts +7 -18
  62. package/dist/src/families/browser.js +19 -8
  63. package/dist/src/families/claude/deliver.d.ts +2 -0
  64. package/dist/src/families/claude/deliver.js +43 -0
  65. package/dist/src/families/claude/history.d.ts +2 -0
  66. package/dist/src/families/claude/history.js +192 -0
  67. package/dist/src/families/claude/live-sessions.d.ts +13 -0
  68. package/dist/src/families/claude/live-sessions.js +117 -0
  69. package/dist/src/families/claude/messaging.d.ts +69 -0
  70. package/dist/src/families/claude/messaging.js +165 -0
  71. package/dist/src/families/claude/mod.d.ts +26 -0
  72. package/dist/src/families/claude/mod.js +105 -0
  73. package/dist/src/families/claude/session-files.d.ts +21 -0
  74. package/dist/src/families/claude/session-files.js +54 -0
  75. package/dist/src/families/codex/deliver.d.ts +5 -0
  76. package/dist/src/families/codex/deliver.js +76 -0
  77. package/dist/src/families/codex/history.d.ts +7 -0
  78. package/dist/src/families/codex/history.js +174 -0
  79. package/dist/src/families/codex/index.js +2 -0
  80. package/dist/src/families/codex/live-sessions.d.ts +12 -0
  81. package/dist/src/families/codex/live-sessions.js +193 -0
  82. package/dist/src/families/codex/quota.d.ts +3 -0
  83. package/dist/src/families/codex/quota.js +123 -0
  84. package/dist/src/families/codex/rate-limits.js +2 -0
  85. package/dist/src/families/codex/rollout.js +1 -1
  86. package/dist/src/families/grok/browser.d.ts +3 -0
  87. package/dist/src/families/grok/browser.js +5 -0
  88. package/dist/src/families/grok/history.d.ts +2 -0
  89. package/dist/src/families/grok/history.js +157 -0
  90. package/dist/src/families/grok/live-sessions.d.ts +4 -0
  91. package/dist/src/families/grok/live-sessions.js +80 -0
  92. package/dist/src/families/grok/login-key.d.ts +14 -0
  93. package/dist/src/families/grok/login-key.js +37 -0
  94. package/dist/src/families/history.d.ts +20 -0
  95. package/dist/src/families/history.js +81 -0
  96. package/dist/src/families/live-sessions.d.ts +26 -0
  97. package/dist/src/families/live-sessions.js +9 -0
  98. package/dist/src/families/login-keys.js +5 -1
  99. package/dist/src/families/messaging.d.ts +27 -0
  100. package/dist/src/families/messaging.js +6 -0
  101. package/dist/src/families/pi/history.d.ts +2 -0
  102. package/dist/src/families/pi/history.js +124 -0
  103. package/dist/src/families/pi/live-sessions.d.ts +2 -0
  104. package/dist/src/families/pi/live-sessions.js +70 -0
  105. package/dist/src/families/shared/history-text.d.ts +65 -0
  106. package/dist/src/families/shared/history-text.js +261 -0
  107. package/dist/src/menubar/hotkey.d.ts +86 -0
  108. package/dist/src/menubar/hotkey.js +159 -0
  109. package/dist/src/menubar/script.d.ts +2 -0
  110. package/dist/src/menubar/script.js +118 -22
  111. package/dist/src/menubar/snapshot.d.ts +8 -4
  112. package/dist/src/menubar/snapshot.js +45 -13
  113. package/dist/src/menubar/strings.d.ts +24 -6
  114. package/dist/src/menubar/strings.js +24 -6
  115. package/dist/src/panel/handler.d.ts +69 -0
  116. package/dist/src/panel/handler.js +686 -15
  117. package/dist/src/panel/i18n.d.ts +304 -3
  118. package/dist/src/panel/i18n.js +669 -67
  119. package/dist/src/panel/orca.d.ts +48 -0
  120. package/dist/src/panel/orca.js +153 -0
  121. package/dist/src/panel/page-logic.d.ts +255 -13
  122. package/dist/src/panel/page-logic.js +483 -1
  123. package/dist/src/panel/page-script.js +2265 -207
  124. package/dist/src/panel/page-styles.js +404 -32
  125. package/dist/src/panel/page.js +1 -0
  126. package/dist/src/plugins/account-script.js +61 -27
  127. package/dist/src/plugins/check.js +16 -4
  128. package/dist/src/plugins/loader.d.ts +8 -1
  129. package/dist/src/plugins/loader.js +72 -7
  130. package/dist/src/runtime.d.ts +5 -0
  131. package/dist/src/runtime.js +27 -5
  132. package/dist/src/types.d.ts +116 -1
  133. package/dist/testing/index.d.ts +5 -0
  134. package/dist/testing/index.js +5 -0
  135. package/mods/claude/.claude-plugin/plugin.json +7 -0
  136. package/mods/claude/hooks/hooks.json +1 -0
  137. package/mods/claude/hooks/register.js +261 -0
  138. package/package.json +5 -2
  139. package/schemas/autostart.json +74 -1
  140. package/schemas/browser-set.json +110 -0
  141. package/schemas/browser.json +22 -2
  142. package/schemas/config.json +26 -1
  143. package/schemas/history-index.json +209 -0
  144. package/schemas/history-projects.json +133 -0
  145. package/schemas/history-show.json +275 -0
  146. package/schemas/history.json +410 -0
  147. package/schemas/menubar-hotkey.json +139 -0
  148. package/schemas/menubar-snapshot.json +36 -2
  149. package/schemas/menubar.json +74 -1
  150. package/schemas/messages-inbound.json +258 -0
  151. package/schemas/messages.json +164 -0
  152. package/schemas/send.json +165 -0
  153. package/schemas/sessions-copy.json +113 -0
  154. package/schemas/sessions-open-run.json +97 -0
  155. package/schemas/sessions.json +237 -0
  156. package/skills/sideby/SKILL.md +10 -5
  157. package/skills/sideby/references/accounts.md +11 -0
  158. package/skills/sideby/references/ai-tasks.md +17 -1
  159. package/skills/sideby/references/panel.md +6 -4
  160. package/skills/sideby/references/quota.md +2 -2
  161. package/skills/sideby/references/sessions.md +79 -0
@@ -6,6 +6,11 @@ export const QUOTA_FAIL_PERCENT = 85;
6
6
  export const QUOTA_WARN_PERCENT = 60;
7
7
  /** Days of Usage every Family reports. */
8
8
  export const USAGE_DAYS = 7;
9
+ /** Shared by the Panel and menu bar. Self-contained so the Panel can inline it without other module state. */
10
+ export function quotaIsStale(quota, now) {
11
+ const at = Date.parse(quota.observedAt);
12
+ return Boolean(quota.fetchError) || !Number.isFinite(at) || now - at > 3600_000 || at - now > 60_000;
13
+ }
9
14
  export function quotaLevel(usedPercent) {
10
15
  if (usedPercent >= QUOTA_FAIL_PERCENT)
11
16
  return 'fail';
@@ -41,6 +41,8 @@ export declare function remoteControlGroups(accounts: readonly Account[], ctx: R
41
41
  export declare function groupsToTurnOff(groups: readonly RemoteControlGroup[]): RemoteControlGroup[];
42
42
  /** The groups `on` would change: those that are off, or follow a default that may be off. */
43
43
  export declare function groupsToTurnOn(groups: readonly RemoteControlGroup[]): RemoteControlGroup[];
44
+ /** What `on`, `off` or `undo` says when no file needs it: always `ok: false`, so the CLI exits 1. */
45
+ export declare function remoteControlNothingToDo(action: 'on' | 'off' | 'undo', groups: readonly RemoteControlGroup[]): RemoteControlChange;
44
46
  /**
45
47
  * Sets `remoteControlAtStartup` to `to` in every group that does not hold it yet (a default counts as either),
46
48
  * remembering each old value for undo.
@@ -2,48 +2,27 @@
2
2
  // Claude Account's `settings.json`. Accounts that share a file (a link to the Main Account's) form one group and one
3
3
  // write. Nothing but that key is ever read out of the file into an output, an error or the undo record; writes go
4
4
  // through `writeIfUnchanged`, keep every other key, and never create, replace or retarget a link.
5
- import { mkdir, readFile, rm, stat } from 'node:fs/promises';
6
- import { join } from 'node:path';
7
- import { locate, readObject, render } from './claude-settings-file.js';
8
- import { sha256, writeFileAtomic, writeIfUnchanged } from './fs-safe.js';
5
+ import { rm } from 'node:fs/promises';
6
+ import { keyRecordPath, readKeyRecord, readObject, settingsFileGroups, writeKeyRecord, writeSettingsKey, } from './claude-settings-file.js';
9
7
  export const RC_KEY = 'remoteControlAtStartup';
10
8
  const NO_SETTINGS = 'this account has no settings.json; run `sideby doctor --fix` so it shares the main one, then try again';
11
9
  function stateOf(v) {
12
10
  return v === true ? 'on' : v === false ? 'off' : 'default';
13
11
  }
14
- function recordPath(ctx, file) {
15
- return join(ctx.stateDir, 'remote-control', `${sha256(file).slice(0, 16)}.json`);
16
- }
12
+ const RECORDS = 'remote-control';
13
+ const recordPath = (ctx, file) => keyRecordPath(ctx.stateDir, RECORDS, file);
17
14
  async function readRecord(ctx, file) {
18
- try {
19
- const r = JSON.parse(await readFile(recordPath(ctx, file), 'utf8'));
20
- if (r.file === file && (r.previous === null || typeof r.previous === 'boolean'))
21
- return r;
22
- }
23
- catch {
24
- // no record
25
- }
26
- return null;
15
+ const r = await readKeyRecord(ctx.stateDir, RECORDS, file);
16
+ return r && (r.previous === null || typeof r.previous === 'boolean')
17
+ ? r
18
+ : null;
27
19
  }
28
20
  /** Every Claude Account's setting, grouped by the file it lives in. Writes nothing. */
29
21
  export async function remoteControlGroups(accounts, ctx) {
30
- const byFile = new Map();
31
- for (const account of accounts) {
32
- if (account.family !== 'claude')
33
- continue;
34
- const where = await locate(account);
35
- const have = byFile.get(where.file);
36
- if (have) {
37
- have.accounts.push(account.ref);
38
- continue;
39
- }
40
- const group = {
41
- file: where.file,
42
- accounts: [account.ref],
43
- state: 'missing',
44
- undo: false,
45
- };
46
- byFile.set(where.file, group);
22
+ const out = [];
23
+ for (const { file, accounts: refs, where } of await settingsFileGroups(accounts)) {
24
+ const group = { file, accounts: refs, state: 'missing', undo: false };
25
+ out.push(group);
47
26
  if (where.broken) {
48
27
  group.state = 'blocked';
49
28
  group.reason =
@@ -65,7 +44,7 @@ export async function remoteControlGroups(accounts, ctx) {
65
44
  }
66
45
  }
67
46
  }
68
- return [...byFile.values()];
47
+ return out;
69
48
  }
70
49
  /** The groups `off` would change: those that are on, or follow a default that may be on. */
71
50
  export function groupsToTurnOff(groups) {
@@ -75,16 +54,23 @@ export function groupsToTurnOff(groups) {
75
54
  export function groupsToTurnOn(groups) {
76
55
  return groups.filter((g) => g.state === 'off' || g.state === 'default');
77
56
  }
78
- async function writeKey(file, change, expect) {
79
- const read = await readObject(file);
80
- if ('error' in read)
81
- return `settings.json cannot be changed safely: ${read.error}.`;
82
- const refused = expect(read.obj);
83
- if (refused)
84
- return refused;
85
- const mode = (await stat(file)).mode & 0o777;
86
- const wrote = await writeIfUnchanged(file, sha256(read.text), render(change({ ...read.obj }), read.text), mode);
87
- return wrote ? null : 'settings.json changed while sideby was writing, so nothing was changed. Try again.';
57
+ const writeKey = writeSettingsKey;
58
+ /** What `on`, `off` or `undo` says when no file needs it: always `ok: false`, so the CLI exits 1. */
59
+ export function remoteControlNothingToDo(action, groups) {
60
+ if (action === 'undo')
61
+ return { ok: false, results: [], message: 'There is nothing from sideby to undo.' };
62
+ if (!groups.length)
63
+ return { ok: false, results: [], message: 'No Claude accounts found, so nothing was changed.' };
64
+ const stuck = groups.find((g) => g.state === 'blocked' || (action === 'on' && g.state === 'missing'));
65
+ return {
66
+ ok: false,
67
+ results: [],
68
+ message: stuck
69
+ ? `Nothing was changed: ${stuck.reason}`
70
+ : action === 'on'
71
+ ? 'Remote Control already starts by itself (already on, nothing changed).'
72
+ : 'Remote Control already does not start by itself (already off, nothing changed).',
73
+ };
88
74
  }
89
75
  /**
90
76
  * Sets `remoteControlAtStartup` to `to` in every group that does not hold it yet (a default counts as either),
@@ -93,18 +79,8 @@ async function writeKey(file, change, expect) {
93
79
  export async function setRemoteControl(accounts, ctx, to) {
94
80
  const groups = await remoteControlGroups(accounts, ctx);
95
81
  const todo = to ? groupsToTurnOn(groups) : groupsToTurnOff(groups);
96
- if (todo.length === 0) {
97
- const stuck = groups.find((g) => g.state === 'blocked' || (to && g.state === 'missing'));
98
- return stuck
99
- ? { ok: false, results: [], message: `Nothing was changed: ${stuck.reason}` }
100
- : {
101
- ok: true,
102
- results: [],
103
- message: to
104
- ? 'Remote Control already starts by itself; nothing changed.'
105
- : 'Remote Control already does not start by itself; nothing changed.',
106
- };
107
- }
82
+ if (todo.length === 0)
83
+ return remoteControlNothingToDo(to ? 'on' : 'off', groups);
108
84
  const results = [];
109
85
  for (const g of todo) {
110
86
  let previous = null;
@@ -123,8 +99,7 @@ export async function setRemoteControl(accounts, ctx, to) {
123
99
  wrote: to,
124
100
  at: new Date().toISOString(),
125
101
  };
126
- await mkdir(join(ctx.stateDir, 'remote-control'), { recursive: true });
127
- await writeFileAtomic(recordPath(ctx, g.file), `${JSON.stringify(record, null, 2)}\n`, 0o600);
102
+ await writeKeyRecord(ctx.stateDir, RECORDS, g.file, record);
128
103
  results.push({ file: g.file, accounts: g.accounts, ok: true, message: to ? 'Turned on.' : 'Turned off.' });
129
104
  }
130
105
  const ok = results.every((r) => r.ok);
@@ -150,7 +125,7 @@ export function groupsToUndo(groups) {
150
125
  export async function undoRemoteControlOff(accounts, ctx) {
151
126
  const todo = groupsToUndo(await remoteControlGroups(accounts, ctx));
152
127
  if (todo.length === 0)
153
- return { ok: false, results: [], message: 'There is nothing from sideby to undo.' };
128
+ return remoteControlNothingToDo('undo', []);
154
129
  const results = [];
155
130
  for (const g of todo) {
156
131
  const record = await readRecord(ctx, g.file);
@@ -0,0 +1,76 @@
1
+ import type { Runtime } from '../runtime.ts';
2
+ import type { Env } from '../types.ts';
3
+ /** One Run a Session works for, as the index names it. */
4
+ export interface RunEntry {
5
+ title: string;
6
+ laneTitle?: string;
7
+ role?: string;
8
+ /** The Run Board file (absolute path). */
9
+ board: string;
10
+ /** `file://<board>`, with `#lane-<id>` for a lane. */
11
+ url: string;
12
+ }
13
+ /** What a Live Session shows of its Run: the first by role, and the other Runs it also works for. */
14
+ export interface SessionRun extends RunEntry {
15
+ others?: Pick<RunEntry, 'title' | 'laneTitle' | 'role' | 'board'>[];
16
+ }
17
+ /** The largest Session Index sideby reads; a bigger one is ignored. */
18
+ export declare const INDEX_MAX_BYTES: number;
19
+ /** Which entry a Session shows first when it works for several Runs; any other role comes after these. */
20
+ export declare const ROLE_ORDER: string[];
21
+ /** The orchestrator's state folder: `AGENT_DISPATCH_STATE_DIR`, else `$XDG_STATE_HOME/agent-dispatch`, else `~/.local/state/agent-dispatch`. */
22
+ export declare function dispatchStateDir(env: Env, home: string): string;
23
+ export declare const sessionIndexPath: (env: Env, home: string) => string;
24
+ /**
25
+ * Parses a Session Index: `{ schemaVersion: 1, revision?, generatedAt?, sessions: { <id>: { entries: [...] } } }`,
26
+ * each entry `{ run, runTitle, board, lane, laneTitle, role, url }`. Undefined when it is not version 1; entries
27
+ * without a title, `board` or `url` are left out. The board files are checked by `checkedEntry`.
28
+ */
29
+ export declare function parseSessionIndex(json: string): Map<string, RunEntry[]> | undefined;
30
+ /** Reads the Session Index; undefined when there is none or it cannot be used. Never follows a link at the file. */
31
+ export declare function readSessionIndex(path: string): Promise<Map<string, RunEntry[]> | undefined>;
32
+ export interface BoardCheck {
33
+ /** The real path of `<state>/boards`. */
34
+ boardsDir: string;
35
+ uid: number | undefined;
36
+ /** The boards folder's device and inode when it was checked. */
37
+ dev: number;
38
+ ino: number;
39
+ }
40
+ /** A board file's device and inode when it was checked. */
41
+ export interface BoardIdentity {
42
+ dev: number;
43
+ ino: number;
44
+ }
45
+ /** The orchestrator's boards folder, when it is a real folder of the current user. */
46
+ export declare function boardsCheck(env: Env, home: string, uid?: number | undefined): Promise<BoardCheck | undefined>;
47
+ /**
48
+ * The entry when its board is a regular `.html` file of the current user, not a link, right inside the boards
49
+ * folder, and its `url` is exactly `file://<board>` with an optional `#lane-<id>`; undefined otherwise.
50
+ */
51
+ export declare function checkedEntry(e: RunEntry, check: BoardCheck): Promise<RunEntry | undefined>;
52
+ /**
53
+ * True while `board` and its boards folder are still the files that were checked: neither is a link, both belong to
54
+ * the user, their device and inode are unchanged, and the board's real path is still right inside the folder. Asked
55
+ * right before the board is opened, so a file swapped after the check is not opened.
56
+ */
57
+ export declare function stillTheBoard(board: string, check: BoardCheck, id: BoardIdentity): Promise<boolean>;
58
+ /** The entries in the order a Session shows them: coordinator, write, review, research, then any other role. */
59
+ export declare function byRole(list: readonly RunEntry[]): RunEntry[];
60
+ /** The Run each of `sessionIds` works for; an empty map when there is no index, no boards folder or no match. */
61
+ export declare function runsForSessions(env: Env, home: string, sessionIds: readonly string[], uid?: number): Promise<Map<string, SessionRun>>;
62
+ /** The same Sessions, each with `run` where the Session Index ties it to a Run. */
63
+ export declare function withRuns<T extends {
64
+ sessionId: string;
65
+ }>(env: Env, home: string, sessions: T[], uid?: number): Promise<(T & {
66
+ run?: SessionRun;
67
+ })[]>;
68
+ /**
69
+ * Opens the Run Board of `sessionId` with the system's default program. The path comes only from the Session Index,
70
+ * read and checked again here, and checked once more right before the program starts; returns the board and the
71
+ * command that opened it.
72
+ */
73
+ export declare function openRunBoard(rt: Runtime, sessionId: string): Promise<{
74
+ board: string;
75
+ command: string[];
76
+ }>;
@@ -0,0 +1,245 @@
1
+ // Run Links (spec §3.32 step 2b, ADR-0041): which Run of a local orchestrator a Live Session works for, read from
2
+ // the orchestrator's optional Session Index, and its Run Board, a static HTML file in the orchestrator's state
3
+ // folder. Read-only and best effort: no index, one too big, of another version or that does not parse, or a board
4
+ // file that does not check out, all mean "no Run" and nothing else changes. No network request.
5
+ import { constants } from 'node:fs';
6
+ import { lstat, open, realpath } from 'node:fs/promises';
7
+ import { basename, dirname, isAbsolute, join } from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { openWithDefault } from './edit-settings.js';
10
+ import { UserError } from './errors.js';
11
+ /** The largest Session Index sideby reads; a bigger one is ignored. */
12
+ export const INDEX_MAX_BYTES = 256 * 1024;
13
+ const MAX_TEXT = 120;
14
+ // Built from a string: a regex literal with control characters reads as a typo to linters.
15
+ // biome-ignore lint/complexity/useRegexLiterals: the literal form is what noControlCharactersInRegex rejects
16
+ const CONTROL = new RegExp(String.raw `[\x00-\x1f\x7f-\x9f]+`, 'g');
17
+ /** Which entry a Session shows first when it works for several Runs; any other role comes after these. */
18
+ export const ROLE_ORDER = ['coordinator', 'write', 'review', 'research'];
19
+ /** The orchestrator's state folder: `AGENT_DISPATCH_STATE_DIR`, else `$XDG_STATE_HOME/agent-dispatch`, else `~/.local/state/agent-dispatch`. */
20
+ export function dispatchStateDir(env, home) {
21
+ const own = env.AGENT_DISPATCH_STATE_DIR;
22
+ if (own && isAbsolute(own))
23
+ return own;
24
+ const xdg = env.XDG_STATE_HOME;
25
+ return join(xdg && isAbsolute(xdg) ? xdg : join(home, '.local', 'state'), 'agent-dispatch');
26
+ }
27
+ export const sessionIndexPath = (env, home) => join(dispatchStateDir(env, home), 'session-index.json');
28
+ // Titles come from another program: one line, no control characters, a sane length.
29
+ function text(value) {
30
+ if (typeof value !== 'string')
31
+ return undefined;
32
+ const one = value.replace(CONTROL, ' ').trim();
33
+ if (!one)
34
+ return undefined;
35
+ return one.length > MAX_TEXT ? `${one.slice(0, MAX_TEXT - 1)}…` : one;
36
+ }
37
+ function entry(raw) {
38
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
39
+ return undefined;
40
+ const r = raw;
41
+ if (typeof r.board !== 'string' || typeof r.url !== 'string')
42
+ return undefined;
43
+ const title = text(r.runTitle) ?? text(r.run);
44
+ if (!title)
45
+ return undefined;
46
+ const laneTitle = text(r.laneTitle) ?? text(r.lane);
47
+ const role = text(r.role);
48
+ return { title, ...(laneTitle ? { laneTitle } : {}), ...(role ? { role } : {}), board: r.board, url: r.url };
49
+ }
50
+ /**
51
+ * Parses a Session Index: `{ schemaVersion: 1, revision?, generatedAt?, sessions: { <id>: { entries: [...] } } }`,
52
+ * each entry `{ run, runTitle, board, lane, laneTitle, role, url }`. Undefined when it is not version 1; entries
53
+ * without a title, `board` or `url` are left out. The board files are checked by `checkedEntry`.
54
+ */
55
+ export function parseSessionIndex(json) {
56
+ let doc;
57
+ try {
58
+ doc = JSON.parse(json);
59
+ }
60
+ catch {
61
+ return undefined;
62
+ }
63
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc))
64
+ return undefined;
65
+ const d = doc;
66
+ if (d.schemaVersion !== 1 || !d.sessions || typeof d.sessions !== 'object' || Array.isArray(d.sessions))
67
+ return undefined;
68
+ const out = new Map();
69
+ for (const [id, value] of Object.entries(d.sessions)) {
70
+ if (!id || id.length > 200 || !value || typeof value !== 'object')
71
+ continue;
72
+ const list = value.entries;
73
+ if (!Array.isArray(list))
74
+ continue;
75
+ const runs = list.map(entry).filter((e) => e !== undefined);
76
+ if (runs.length)
77
+ out.set(id, runs);
78
+ }
79
+ return out;
80
+ }
81
+ /** Reads the Session Index; undefined when there is none or it cannot be used. Never follows a link at the file. */
82
+ export async function readSessionIndex(path) {
83
+ let fh;
84
+ try {
85
+ fh = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
86
+ const st = await fh.stat();
87
+ if (!st.isFile() || st.size > INDEX_MAX_BYTES)
88
+ return undefined;
89
+ const buf = Buffer.alloc(INDEX_MAX_BYTES + 1);
90
+ const { bytesRead } = await fh.read(buf, 0, buf.length, 0);
91
+ if (bytesRead > INDEX_MAX_BYTES)
92
+ return undefined;
93
+ return parseSessionIndex(buf.subarray(0, bytesRead).toString('utf8'));
94
+ }
95
+ catch {
96
+ return undefined;
97
+ }
98
+ finally {
99
+ await fh?.close().catch(() => { });
100
+ }
101
+ }
102
+ /** The orchestrator's boards folder, when it is a real folder of the current user. */
103
+ export async function boardsCheck(env, home, uid = process.getuid?.()) {
104
+ const dir = join(dispatchStateDir(env, home), 'boards');
105
+ try {
106
+ const st = await lstat(dir);
107
+ if (!st.isDirectory() || (uid !== undefined && st.uid !== uid))
108
+ return undefined;
109
+ return { boardsDir: await realpath(dir), uid, dev: st.dev, ino: st.ino };
110
+ }
111
+ catch {
112
+ return undefined;
113
+ }
114
+ }
115
+ const LANE = /^#lane-[A-Za-z0-9%._~-]+$/;
116
+ /**
117
+ * The entry when its board is a regular `.html` file of the current user, not a link, right inside the boards
118
+ * folder, and its `url` is exactly `file://<board>` with an optional `#lane-<id>`; undefined otherwise.
119
+ */
120
+ export async function checkedEntry(e, check) {
121
+ return (await inspectEntry(e, check))?.entry;
122
+ }
123
+ /** `checkedEntry`, with the board file's identity at the time of the check. */
124
+ async function inspectEntry(e, check) {
125
+ const name = basename(e.board);
126
+ if (!isAbsolute(e.board) || !name.endsWith('.html') || name === '.html')
127
+ return undefined;
128
+ let st;
129
+ try {
130
+ st = await lstat(e.board);
131
+ if (!st.isFile() || (check.uid !== undefined && st.uid !== check.uid))
132
+ return undefined;
133
+ if ((await realpath(dirname(e.board))) !== check.boardsDir)
134
+ return undefined;
135
+ if ((await realpath(e.board)) !== join(check.boardsDir, name))
136
+ return undefined;
137
+ const url = new URL(e.url);
138
+ if (url.protocol !== 'file:' || url.host || url.search || url.username || url.password)
139
+ return undefined;
140
+ if (url.hash && !LANE.test(url.hash))
141
+ return undefined;
142
+ url.hash = '';
143
+ if (fileURLToPath(url) !== e.board)
144
+ return undefined;
145
+ }
146
+ catch {
147
+ return undefined;
148
+ }
149
+ return { entry: e, id: { dev: st.dev, ino: st.ino } };
150
+ }
151
+ /**
152
+ * True while `board` and its boards folder are still the files that were checked: neither is a link, both belong to
153
+ * the user, their device and inode are unchanged, and the board's real path is still right inside the folder. Asked
154
+ * right before the board is opened, so a file swapped after the check is not opened.
155
+ */
156
+ export async function stillTheBoard(board, check, id) {
157
+ try {
158
+ const dir = await lstat(dirname(board));
159
+ if (!dir.isDirectory() || dir.dev !== check.dev || dir.ino !== check.ino)
160
+ return false;
161
+ if (check.uid !== undefined && dir.uid !== check.uid)
162
+ return false;
163
+ const st = await lstat(board);
164
+ if (!st.isFile() || st.dev !== id.dev || st.ino !== id.ino)
165
+ return false;
166
+ if (check.uid !== undefined && st.uid !== check.uid)
167
+ return false;
168
+ return (await realpath(board)) === join(check.boardsDir, basename(board));
169
+ }
170
+ catch {
171
+ return false;
172
+ }
173
+ }
174
+ const rank = (role) => {
175
+ const i = ROLE_ORDER.indexOf(role ?? '');
176
+ return i === -1 ? ROLE_ORDER.length : i;
177
+ };
178
+ /** The entries in the order a Session shows them: coordinator, write, review, research, then any other role. */
179
+ export function byRole(list) {
180
+ return list
181
+ .map((e, i) => ({ e, i }))
182
+ .sort((a, b) => rank(a.e.role) - rank(b.e.role) || a.i - b.i)
183
+ .map(({ e }) => e);
184
+ }
185
+ /** The checked entries of `sessionId`, in the order it shows them. */
186
+ async function checkedRuns(entries, check) {
187
+ const ok = await Promise.all(entries.map((e) => checkedEntry(e, check)));
188
+ return byRole(ok.filter((e) => e !== undefined));
189
+ }
190
+ /** The Run each of `sessionIds` works for; an empty map when there is no index, no boards folder or no match. */
191
+ export async function runsForSessions(env, home, sessionIds, uid) {
192
+ const out = new Map();
193
+ if (!sessionIds.length)
194
+ return out;
195
+ const index = await readSessionIndex(sessionIndexPath(env, home));
196
+ if (!index)
197
+ return out;
198
+ const wanted = sessionIds.filter((id) => index.has(id));
199
+ if (!wanted.length)
200
+ return out;
201
+ const check = await boardsCheck(env, home, uid);
202
+ if (!check)
203
+ return out;
204
+ for (const id of wanted) {
205
+ const [first, ...rest] = await checkedRuns(index.get(id), check);
206
+ if (!first)
207
+ continue;
208
+ const others = rest.map((e) => ({
209
+ title: e.title,
210
+ ...(e.laneTitle ? { laneTitle: e.laneTitle } : {}),
211
+ ...(e.role ? { role: e.role } : {}),
212
+ board: e.board,
213
+ }));
214
+ out.set(id, { ...first, ...(others.length ? { others } : {}) });
215
+ }
216
+ return out;
217
+ }
218
+ /** The same Sessions, each with `run` where the Session Index ties it to a Run. */
219
+ export async function withRuns(env, home, sessions, uid) {
220
+ const runs = await runsForSessions(env, home, sessions.map((s) => s.sessionId), uid);
221
+ return sessions.map((s) => {
222
+ const run = runs.get(s.sessionId);
223
+ return run ? { ...s, run } : s;
224
+ });
225
+ }
226
+ /**
227
+ * Opens the Run Board of `sessionId` with the system's default program. The path comes only from the Session Index,
228
+ * read and checked again here, and checked once more right before the program starts; returns the board and the
229
+ * command that opened it.
230
+ */
231
+ export async function openRunBoard(rt, sessionId) {
232
+ const gone = () => new UserError('This session is not part of a run any more, or its board file is gone; ask the coordinating AI to show the board again', { code: 'no-run' });
233
+ const entries = (await readSessionIndex(sessionIndexPath(rt.env, rt.paths.home)))?.get(sessionId);
234
+ const check = entries && (await boardsCheck(rt.env, rt.paths.home));
235
+ if (!entries || !check)
236
+ throw gone();
237
+ const ok = (await Promise.all(entries.map((e) => inspectEntry(e, check)))).filter((x) => x !== undefined);
238
+ const first = byRole(ok.map((x) => x.entry))[0];
239
+ const id = ok.find((x) => x.entry === first)?.id;
240
+ if (!first || !id)
241
+ throw gone();
242
+ if (!(await stillTheBoard(first.board, check, id)))
243
+ throw new UserError('The board file changed while sideby checked it; ask the coordinating AI to show the board again', { code: 'board-changed' });
244
+ return { board: first.board, command: await openWithDefault(rt, first.board, { text: false }) };
245
+ }
@@ -1,9 +1,10 @@
1
1
  import type { Account, AccountIdentity, QuotaResult } from '../types.ts';
2
- /** Families whose Accounts can be a Same Login (ADR-0016, ADR-0028). */
2
+ /** Families whose Accounts can be a Same Login (ADR-0016, ADR-0028, ADR-0037). */
3
3
  export declare const SAME_LOGIN_FAMILIES: ReadonlySet<string>;
4
4
  /**
5
5
  * Families whose Identity alone does not tell one Quota apart, so two Accounts also need equal Login Keys. Codex: one
6
- * email can belong to several ChatGPT workspaces, each with its own Quota (ADR-0028).
6
+ * email can belong to several ChatGPT workspaces, each with its own Quota (ADR-0028). Grok: one email
7
+ * can sign in on its own or in an x.ai team (ADR-0037).
7
8
  */
8
9
  export declare const LOGIN_KEY_FAMILIES: ReadonlySet<string>;
9
10
  export interface LoginMember {
@@ -26,4 +27,4 @@ export declare function sameLoginGroups(members: readonly LoginMember[]): Map<st
26
27
  * The Quota an Account of a Same Login shows: the freshest `ok` reading of the group (its own wins a tie), marked
27
28
  * with `from` when it is another member's. Without any `ok` reading the Account keeps its own result.
28
29
  */
29
- export declare function sharedQuota(ref: string, readings: ReadonlyMap<string, QuotaResult>, peers: readonly string[]): QuotaResult;
30
+ export declare function sharedQuota(ref: string, readings: ReadonlyMap<string, QuotaResult>, peers: readonly string[], localFallbackOnly?: boolean): QuotaResult;
@@ -1,10 +1,11 @@
1
- /** Families whose Accounts can be a Same Login (ADR-0016, ADR-0028). */
2
- export const SAME_LOGIN_FAMILIES = new Set(['claude', 'codex']);
1
+ /** Families whose Accounts can be a Same Login (ADR-0016, ADR-0028, ADR-0037). */
2
+ export const SAME_LOGIN_FAMILIES = new Set(['claude', 'codex', 'grok']);
3
3
  /**
4
4
  * Families whose Identity alone does not tell one Quota apart, so two Accounts also need equal Login Keys. Codex: one
5
- * email can belong to several ChatGPT workspaces, each with its own Quota (ADR-0028).
5
+ * email can belong to several ChatGPT workspaces, each with its own Quota (ADR-0028). Grok: one email
6
+ * can sign in on its own or in an x.ai team (ADR-0037).
6
7
  */
7
- export const LOGIN_KEY_FAMILIES = new Set(['codex']);
8
+ export const LOGIN_KEY_FAMILIES = new Set(['codex', 'grok']);
8
9
  const norm = (s) => s?.trim().toLowerCase();
9
10
  /**
10
11
  * Whether two Accounts are the same login: same Family (one that groups), both subscriptions, the same email, and the
@@ -37,7 +38,7 @@ export function sameLoginGroups(members) {
37
38
  * The Quota an Account of a Same Login shows: the freshest `ok` reading of the group (its own wins a tie), marked
38
39
  * with `from` when it is another member's. Without any `ok` reading the Account keeps its own result.
39
40
  */
40
- export function sharedQuota(ref, readings, peers) {
41
+ export function sharedQuota(ref, readings, peers, localFallbackOnly = false) {
41
42
  const own = readings.get(ref) ?? { status: 'unavailable', reason: 'unrecognized' };
42
43
  let best;
43
44
  for (const r of [ref, ...peers]) {
@@ -47,8 +48,10 @@ export function sharedQuota(ref, readings, peers) {
47
48
  const t = Date.parse(q.observedAt);
48
49
  if (!Number.isFinite(t))
49
50
  continue;
50
- if (!best || t > best.t)
51
- best = { ref: r, q, t };
51
+ // A peer's replayed rollout must not overwrite an authoritative fetch either (ADR-0038).
52
+ const rank = localFallbackOnly && q.fetched ? 1 : 0;
53
+ if (!best || rank > best.rank || (rank === best.rank && t > best.t))
54
+ best = { ref: r, q, t, rank };
52
55
  }
53
56
  if (!best || best.ref === ref)
54
57
  return own;
@@ -0,0 +1,31 @@
1
+ import type { Runtime } from '../runtime.ts';
2
+ import { type LiveSession, type LiveSessionsResult } from './live-sessions.ts';
3
+ import type { LiveSessionDeps } from './live-sessions-procs.ts';
4
+ /** How the candidates are offered when a target names several Sessions. */
5
+ export interface SessionNext {
6
+ verb: string;
7
+ command: (id: string) => string;
8
+ }
9
+ /**
10
+ * The one Session `target` names: a session id (or its first 8 or more characters), else an Account whose single
11
+ * Live Session it is. Several Sessions, or none, are a UserError that says what to run next.
12
+ */
13
+ export declare function pickSession(target: string, sessions: readonly LiveSession[], account: {
14
+ ref: string;
15
+ label: string;
16
+ } | undefined,
17
+ /** How the candidates are offered; `sessions copy` when left out. */
18
+ next?: SessionNext): LiveSession;
19
+ /**
20
+ * Lists the Live Sessions and picks the one `target` names, reading `target` as an Account (ref or alias) when it is
21
+ * one. `onListed` sees the listing before the pick, so its problems can be shown also when the pick fails; the
22
+ * listing is returned too, for callers that look for the sending Session in it.
23
+ */
24
+ export declare function selectSession(rt: Runtime, target: string, opts?: {
25
+ next?: SessionNext;
26
+ deps?: LiveSessionDeps;
27
+ onListed?: (listed: LiveSessionsResult) => void;
28
+ }): Promise<{
29
+ session: LiveSession;
30
+ listed: LiveSessionsResult;
31
+ }>;
@@ -0,0 +1,44 @@
1
+ import { UserError } from './errors.js';
2
+ import { listLiveSessions, shortId } from './live-sessions.js';
3
+ const COPY = { verb: 'copy', command: (id) => `sideby sessions copy ${id}` };
4
+ /**
5
+ * The one Session `target` names: a session id (or its first 8 or more characters), else an Account whose single
6
+ * Live Session it is. Several Sessions, or none, are a UserError that says what to run next.
7
+ */
8
+ export function pickSession(target, sessions, account,
9
+ /** How the candidates are offered; `sessions copy` when left out. */
10
+ next = COPY) {
11
+ const byId = sessions.filter((s) => s.sessionId === target || (target.length >= 8 && s.sessionId.startsWith(target)));
12
+ if (byId.length === 1)
13
+ return byId[0];
14
+ const list = byId.length ? byId : account ? sessions.filter((s) => s.account === account.ref) : [];
15
+ if (list.length === 1)
16
+ return list[0];
17
+ if (!list.length) {
18
+ if (account)
19
+ throw new UserError(`${account.label} has no running session now; start one with \`sideby run ${account.label}\`, or run \`sideby sessions\` to see the others`, { code: 'no-session' });
20
+ throw new UserError(`no running session or account named ${target}; run \`sideby sessions\` to see the running sessions`, { code: 'no-session' });
21
+ }
22
+ const who = account && !byId.length ? account.label : target;
23
+ const rows = list.map((s) => ` ${next.command(shortId(s.sessionId))} ${s.label}`).join('\n');
24
+ throw new UserError(`${who} runs ${list.length} sessions now; ${next.verb} one by its id:\n${rows}`, {
25
+ code: 'several-sessions',
26
+ });
27
+ }
28
+ /**
29
+ * Lists the Live Sessions and picks the one `target` names, reading `target` as an Account (ref or alias) when it is
30
+ * one. `onListed` sees the listing before the pick, so its problems can be shown also when the pick fails; the
31
+ * listing is returned too, for callers that look for the sending Session in it.
32
+ */
33
+ export async function selectSession(rt, target, opts = {}) {
34
+ const listed = await listLiveSessions(rt, {}, opts.deps);
35
+ opts.onListed?.(listed);
36
+ let account;
37
+ try {
38
+ account = { ref: (await rt.resolve(target)).ref, label: target };
39
+ }
40
+ catch {
41
+ // not an Account: a session id
42
+ }
43
+ return { session: pickSession(target, listed.sessions, account, opts.next), listed };
44
+ }
@@ -1,20 +1,9 @@
1
- import type { Account } from '../types.ts';
2
- export interface WebsiteDef {
1
+ import type { FamilyDef, FamilyWebsite } from '../types.ts';
2
+ export type WebsiteDef = FamilyWebsite & {
3
3
  /** The Family id. */
4
4
  family: string;
5
- /** Where "Open in browser" goes. */
6
- url: string;
7
- /**
8
- * The Local Storage origin whose key names may hold `signInId`, and the reader of that id from the Host's login
9
- * file. The id is compared in memory only; it is never shown, returned, logged or cached. Missing when the website
10
- * keeps no id the Host also has (grok.com), so the Account can only be opened in a Browser Profile the user picks.
11
- */
12
- match?: {
13
- origin: string;
14
- signInId(account: Account): Promise<string | undefined>;
15
- };
16
- }
17
- /** The website of a built-in Family id, if it has one. */
18
- export declare function websiteDef(familyId: string): WebsiteDef | undefined;
19
- /** Every website that can be matched, for the origins to read. */
20
- export declare function matchedOrigins(): string[];
5
+ };
6
+ /** The website of a Family: sideby's own for a built-in one, else the one its plugin declares. */
7
+ export declare function websiteDef(families: ReadonlyMap<string, FamilyDef>, familyId: string): WebsiteDef | undefined;
8
+ /** Every website origin that can be matched, for the origins to read. */
9
+ export declare function matchedOrigins(families: ReadonlyMap<string, FamilyDef>): string[];