sideby 0.19.1 → 0.21.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 +305 -3
  117. package/dist/src/panel/i18n.js +622 -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 +260 -13
  121. package/dist/src/panel/page-logic.js +497 -1
  122. package/dist/src/panel/page-script.js +2309 -204
  123. package/dist/src/panel/page-styles.js +398 -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,32 @@
1
+ /** How to get a different login when the browser keeps signing in as the old one. */
2
+ const OTHER_LOGIN = 'sign out of it in the browser, or open the sign-in link in a private window';
3
+ /** The line before the sign-in: who the Account is now, and how to choose another login. Undefined when signed out. */
4
+ export function loginBeforeLine(ref, before) {
5
+ if (before.login !== 'logged-in' || !before.email)
6
+ return undefined;
7
+ const same = before.sameLogin.length ? `, the same login as ${before.sameLogin.join(', ')}` : '';
8
+ return `${ref} is signed in as ${before.email}${same}. To use another login, first ${OTHER_LOGIN}.`;
9
+ }
10
+ /** The result after the sign-in, with what to do next when it did not give the Account a login of its own. */
11
+ export function loginAfterLine(ref, before, after) {
12
+ if (after.login === 'logged-out')
13
+ return { line: `${ref} is not signed in.`, ok: false };
14
+ if (after.login !== 'logged-in' || !after.email)
15
+ return undefined;
16
+ const again = `${OTHER_LOGIN}, then run \`sideby login ${ref}\` again`;
17
+ const peers = after.sameLogin.join(', ');
18
+ if (after.sameLogin.length && before.email === after.email && before.sameLogin.length)
19
+ return {
20
+ line: `${ref} is still signed in as ${after.email}, the same login as ${peers}: the browser used the login it was signed in to. To use another one, ${again}.`,
21
+ ok: false,
22
+ };
23
+ if (after.sameLogin.length)
24
+ return {
25
+ line: `${ref} is now signed in as ${after.email}, the same login as ${peers}, so they share one quota. To use another login, ${again}.`,
26
+ ok: false,
27
+ };
28
+ const split = before.sameLogin.length
29
+ ? `; it no longer shares a quota with ${before.sameLogin.join(', ')}`
30
+ : '';
31
+ return { line: `${ref} is signed in as ${after.email}${split}.`, ok: true };
32
+ }
@@ -0,0 +1,83 @@
1
+ import type { Runtime } from '../runtime.ts';
2
+ import type { LiveSession } from './live-sessions.ts';
3
+ import { type LiveSessionDeps, type ProcessInfo } from './live-sessions-procs.ts';
4
+ /** stored: kept as a file only; delivered: the Host's channel accepted it; read: the target Session shows it; paste-needed: the user must paste `pasteText` into the target. */
5
+ export type MessageStatus = 'stored' | 'delivered' | 'read' | 'paste-needed';
6
+ export interface MessageReceipt {
7
+ /** Short id, also written into the delivered text so it can be found in the target's record. */
8
+ id: string;
9
+ /** The target Session's Session Label. */
10
+ to: string;
11
+ toSessionId: string;
12
+ /** The Account ref that holds the target Session. */
13
+ toAccount: string;
14
+ /** Sender's Session Label when sideby could tell which Session sent it. */
15
+ from?: string;
16
+ status: MessageStatus;
17
+ /** Where the Message file is. */
18
+ file: string;
19
+ /** Copied screenshots next to the Message file. */
20
+ attachments: string[];
21
+ /** One line the user pastes into the target when status is paste-needed (else the same line, for reference). */
22
+ pasteText: string;
23
+ /** Plain-language note: why paste is needed, or that the target must approve it (bypass mode). */
24
+ note?: string;
25
+ /** Delivered, but the target shows it only once the user approves it in its terminal (ADR-0045). */
26
+ needsApproval?: boolean;
27
+ sentAt: string;
28
+ }
29
+ export interface SendOptions {
30
+ text: string;
31
+ /** Paths of images to attach (copied into the Message's folder). */
32
+ images?: readonly string[];
33
+ /** Sender Session id when known (the CLI detects it from its parent Host process). */
34
+ fromSessionId?: string;
35
+ lang?: 'en' | 'zh';
36
+ }
37
+ /** What sending touches on the machine; tests replace each part. */
38
+ export interface MessageDeps {
39
+ /** The programs Live Sessions are read with (`ps`, `lsof`). */
40
+ procs?: LiveSessionDeps;
41
+ /** Folders a Claude message socket's `cc-socks` may sit in; `socketRoots(rt.env)` when left out. */
42
+ tempRoots?: readonly string[];
43
+ /** The user a socket must belong to; the current user when left out. */
44
+ uid?: number;
45
+ /** The process whose parents are searched for the sending Session; this process when left out. */
46
+ selfPid?: number;
47
+ /** How a line reaches a socket; `verify` runs after connecting and before writing. */
48
+ write?: (path: string, line: string, timeoutMs: number, verify: () => Promise<string | null>) => Promise<void>;
49
+ timeoutMs?: number;
50
+ /** How `codex <args>` runs for Codex delivery; resolves to its exit code. */
51
+ runCodex?: (args: readonly string[], env: NodeJS.ProcessEnv, timeoutMs: number) => Promise<number>;
52
+ }
53
+ /** The largest screenshot sideby copies. */
54
+ export declare const MAX_IMAGE_BYTES: number;
55
+ /** The image type of a file's first bytes (`png`, `jpg`, `gif`, `webp`), or null. */
56
+ export declare function imageType(head: Buffer): string | null;
57
+ /** A folder name for a session id: the id itself when it is plain, else its hex; never `.`, `..` or a separator. */
58
+ export declare const safeName: (id: string) => string;
59
+ /**
60
+ * Checks `<state>/messages/<sub…>` one folder at a time: each must be a real folder (not a link) of the current
61
+ * user that group and others cannot write. A missing one is made (mode 700) when `create` is set, else the answer is
62
+ * null. Only a folder sideby made here gets its mode set. Every Message path goes through this first.
63
+ */
64
+ export declare function messageFolder(stateDir: string, sub: readonly string[], create: boolean): Promise<string | null>;
65
+ /** The Live Session whose Host process is a parent of `pid` (the Session `sideby send` runs inside), if any. */
66
+ export declare function senderSession(pid: number, procs: readonly ProcessInfo[], sessions: readonly LiveSession[]): LiveSession | undefined;
67
+ /** The line the user pastes into the target (and keeps for reference when it was delivered). */
68
+ export declare function pasteLine(id: string, file: string, screenshots: number, lang: 'en' | 'zh'): string;
69
+ /** The text a Claude session receives: who sent it, the text, then one line per screenshot so it can read them. */
70
+ export declare function deliveredText(id: string, from: string | undefined, text: string, attachments: readonly string[]): string;
71
+ /** Sends `opts` to the Live Session `target` names (an Account ref/alias with one Live Session, or a session id or its first 8 chars). */
72
+ export declare function sendMessage(rt: Runtime, target: string, opts: SendOptions, deps?: MessageDeps): Promise<MessageReceipt>;
73
+ /** How long after sending a held Message counts as dropped: Claude Code's five minutes plus one of margin. */
74
+ export declare const APPROVAL_EXPIRED_MS: number;
75
+ /**
76
+ * Messages sideby kept, newest first, with their current status (re-checks `delivered` for `read`). A `read` found
77
+ * is saved into the receipt unless `persist` is false (a read-only Panel only computes it).
78
+ */
79
+ export declare function listMessages(rt: Runtime, opts?: {
80
+ to?: string;
81
+ limit?: number;
82
+ persist?: boolean;
83
+ }): Promise<MessageReceipt[]>;
@@ -0,0 +1,433 @@
1
+ // Messages between Sessions (spec §3.32 step 2, ADR-0040): text and screenshots one Session sends another. A Message
2
+ // is kept as a file in sideby's state directory before any delivery, so it is never lost; it is then delivered
3
+ // through the Host's own channel where it has one, or handed to the user to paste.
4
+ import { randomBytes } from 'node:crypto';
5
+ import { constants } from 'node:fs';
6
+ import { chmod, lstat, mkdir, open, readdir, readFile } from 'node:fs/promises';
7
+ import { basename, dirname, join, resolve } from 'node:path';
8
+ import { tailLinesWith } from '../families/claude/session-files.js';
9
+ import { DELIVERERS } from '../families/messaging.js';
10
+ import { UserError } from './errors.js';
11
+ import { writeFileAtomic } from './fs-safe.js';
12
+ import { processView, systemDeps } from './live-sessions-procs.js';
13
+ import { selectSession } from './session-select.js';
14
+ /** The largest screenshot sideby copies. */
15
+ export const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
16
+ const IMAGE_TYPES = [
17
+ ['png', (b) => b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))],
18
+ ['jpg', (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff],
19
+ ['gif', (b) => b.subarray(0, 4).toString('latin1') === 'GIF8'],
20
+ [
21
+ 'webp',
22
+ (b) => b.subarray(0, 4).toString('latin1') === 'RIFF' && b.subarray(8, 12).toString('latin1') === 'WEBP',
23
+ ],
24
+ ];
25
+ /** The image type of a file's first bytes (`png`, `jpg`, `gif`, `webp`), or null. */
26
+ export function imageType(head) {
27
+ return IMAGE_TYPES.find(([, is]) => is(head))?.[0] ?? null;
28
+ }
29
+ const badImage = (message) => new UserError(message, { code: 'bad-image' });
30
+ const notImage = (p) => badImage(`${p} is not a PNG, JPEG, GIF or WebP image. Attach a screenshot in one of those formats, or mention the file path in your message`);
31
+ const tooLarge = (p) => badImage(`${p} is over 20 MB. Crop it or pick a smaller screenshot`);
32
+ /**
33
+ * Opens each image (a regular file, not a link) and checks its type and size before anything is written. The handles
34
+ * stay open, so what is copied later is the file that was checked; the caller closes them.
35
+ */
36
+ async function openImages(paths) {
37
+ const out = [];
38
+ try {
39
+ for (const p of paths) {
40
+ let fh;
41
+ try {
42
+ fh = await open(resolve(p), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
43
+ }
44
+ catch (err) {
45
+ throw badImage(err.code === 'ELOOP'
46
+ ? `${p} is a symlink. Pass the path to the screenshot file itself`
47
+ : `sideby cannot read ${p}; check the path and that the file is readable, then send again`);
48
+ }
49
+ out.push({ path: p, fh });
50
+ const st = await fh.stat();
51
+ if (!st.isFile())
52
+ throw badImage(`${p} is not a regular file. Pass the path to a screenshot`);
53
+ if (st.size > MAX_IMAGE_BYTES)
54
+ throw tooLarge(p);
55
+ const head = Buffer.alloc(16);
56
+ await fh.read(head, 0, 16, 0);
57
+ if (!imageType(head))
58
+ throw notImage(p);
59
+ }
60
+ }
61
+ catch (err) {
62
+ await Promise.all(out.map((i) => i.fh.close().catch(() => { })));
63
+ throw err;
64
+ }
65
+ return out;
66
+ }
67
+ /**
68
+ * Reads an opened image from its start, never more than the limit allows, and tells its type again from the bytes
69
+ * read: a file that grew or changed since it was checked is refused.
70
+ */
71
+ async function readImage(img) {
72
+ const chunks = [];
73
+ let size = 0;
74
+ let pos = 0;
75
+ for (;;) {
76
+ const buf = Buffer.alloc(1024 * 1024);
77
+ const { bytesRead } = await img.fh.read(buf, 0, buf.length, pos);
78
+ if (!bytesRead)
79
+ break;
80
+ pos += bytesRead;
81
+ size += bytesRead;
82
+ if (size > MAX_IMAGE_BYTES)
83
+ throw tooLarge(img.path);
84
+ chunks.push(buf.subarray(0, bytesRead));
85
+ }
86
+ const bytes = Buffer.concat(chunks);
87
+ const type = imageType(bytes.subarray(0, 16));
88
+ if (!type)
89
+ throw notImage(img.path);
90
+ return { bytes, type };
91
+ }
92
+ const messagesDir = (stateDir) => join(stateDir, 'messages');
93
+ /** A folder name for a session id: the id itself when it is plain, else its hex; never `.`, `..` or a separator. */
94
+ export const safeName = (id) => /^[A-Za-z0-9_-][\w.-]*$/.test(id) && id.length <= 128 ? id : Buffer.from(id).toString('hex').slice(0, 128);
95
+ const isSafeName = (name) => /^[A-Za-z0-9_-][\w.-]*$/.test(name) && name.length <= 128;
96
+ function unsafeFolder(path) {
97
+ return new UserError(`sideby cannot save messages in ${path}: it must be a real folder you own that nobody else can write to. Move or delete ${path}, then send again`, { code: 'messages-unsafe' });
98
+ }
99
+ /**
100
+ * Checks `<state>/messages/<sub…>` one folder at a time: each must be a real folder (not a link) of the current
101
+ * user that group and others cannot write. A missing one is made (mode 700) when `create` is set, else the answer is
102
+ * null. Only a folder sideby made here gets its mode set. Every Message path goes through this first.
103
+ */
104
+ export async function messageFolder(stateDir, sub, create) {
105
+ for (const part of sub)
106
+ if (!isSafeName(part))
107
+ throw unsafeFolder(join(messagesDir(stateDir), part));
108
+ if (create)
109
+ await mkdir(stateDir, { recursive: true, mode: 0o700 });
110
+ const uid = process.getuid?.();
111
+ let dir = stateDir;
112
+ for (const part of ['messages', ...sub]) {
113
+ dir = join(dir, part);
114
+ let st = await lstat(dir).catch((err) => {
115
+ if (err.code === 'ENOENT')
116
+ return null;
117
+ throw err;
118
+ });
119
+ if (!st) {
120
+ if (!create)
121
+ return null;
122
+ let made = true;
123
+ await mkdir(dir, { mode: 0o700 }).catch((err) => {
124
+ if (err.code !== 'EEXIST')
125
+ throw err;
126
+ made = false;
127
+ });
128
+ st = await lstat(dir);
129
+ if (made && st.isDirectory() && !st.isSymbolicLink() && st.uid === uid) {
130
+ await chmod(dir, 0o700);
131
+ st = await lstat(dir);
132
+ }
133
+ }
134
+ if (!st.isDirectory() || (uid !== undefined && st.uid !== uid) || (st.mode & 0o022) !== 0)
135
+ throw unsafeFolder(dir);
136
+ }
137
+ return dir;
138
+ }
139
+ /** The Live Session whose Host process is a parent of `pid` (the Session `sideby send` runs inside), if any. */
140
+ export function senderSession(pid, procs, sessions) {
141
+ const byPid = new Map(procs.map((p) => [p.pid, p]));
142
+ const seen = new Set();
143
+ let cur = byPid.get(pid)?.ppid;
144
+ while (cur !== undefined && cur > 1 && !seen.has(cur)) {
145
+ seen.add(cur);
146
+ const s = sessions.find((x) => x.pid === cur);
147
+ if (s)
148
+ return s;
149
+ cur = byPid.get(cur)?.ppid;
150
+ }
151
+ return undefined;
152
+ }
153
+ /** The line the user pastes into the target (and keeps for reference when it was delivered). */
154
+ export function pasteLine(id, file, screenshots, lang) {
155
+ if (lang === 'zh')
156
+ return `请读取 sideby 存好的消息 ${file}(sideby message ${id})${screenshots ? ',以及里面列出的截图' : ''}。`;
157
+ return `Read the message sideby kept for you at ${file} (sideby message ${id})${screenshots ? ' and the screenshots it lists' : ''}.`;
158
+ }
159
+ /** The text a Claude session receives: who sent it, the text, then one line per screenshot so it can read them. */
160
+ export function deliveredText(id, from, text, attachments) {
161
+ const head = `sideby message ${id} ${from ? `from ${from}` : 'from the user via sideby'}`;
162
+ return [head, ...(text ? [text] : []), ...attachments.map((a) => `Screenshot: ${a}`)].join('\n');
163
+ }
164
+ function messageFile(r, text) {
165
+ const lines = [
166
+ `# sideby message ${r.id}`,
167
+ '',
168
+ `From: ${r.from ?? 'the user'}`,
169
+ `To: ${r.to}`,
170
+ `Sent: ${r.sentAt}`,
171
+ '',
172
+ text,
173
+ ];
174
+ if (r.attachments.length)
175
+ lines.push('', 'Screenshots:', ...r.attachments.map((a) => `- ${a}`));
176
+ return `${lines.join('\n')}\n`;
177
+ }
178
+ const NO_CHANNEL = {
179
+ grok: 'Grok Build cannot receive messages directly yet',
180
+ pi: 'pi cannot receive messages directly yet',
181
+ };
182
+ /** Sends `opts` to the Live Session `target` names (an Account ref/alias with one Live Session, or a session id or its first 8 chars). */
183
+ export async function sendMessage(rt, target, opts, deps = {}) {
184
+ const text = opts.text.trim();
185
+ const paths = opts.images ?? [];
186
+ if (!text && !paths.length)
187
+ throw new UserError('the message is empty; write a message or attach a screenshot', {
188
+ code: 'empty',
189
+ });
190
+ const lang = opts.lang ?? 'en';
191
+ const images = await openImages(paths);
192
+ try {
193
+ return await sendOpened(rt, target, { text, lang, images, fromSessionId: opts.fromSessionId }, deps);
194
+ }
195
+ finally {
196
+ await Promise.all(images.map((i) => i.fh.close().catch(() => { })));
197
+ }
198
+ }
199
+ async function sendOpened(rt, target, opts, deps) {
200
+ const { text, lang } = opts;
201
+ const procDeps = deps.procs ?? systemDeps(rt.env);
202
+ const { session: to, listed } = await selectSession(rt, target, {
203
+ next: { verb: 'send to', command: (id) => `sideby send ${id} "<text>"` },
204
+ deps: procDeps,
205
+ });
206
+ let from;
207
+ if (opts.fromSessionId)
208
+ from = listed.sessions.find((s) => s.sessionId === opts.fromSessionId);
209
+ else {
210
+ const all = await processView(procDeps)
211
+ .list()
212
+ .catch(() => []);
213
+ from = senderSession(deps.selfPid ?? process.pid, all, listed.sessions);
214
+ }
215
+ if (from?.sessionId === to.sessionId)
216
+ throw new UserError(`you are already in ${to.label}; pick another session to send to`, {
217
+ code: 'same-session',
218
+ });
219
+ // Read every screenshot before anything is written, so a refused one leaves nothing behind.
220
+ const copies = [];
221
+ for (const img of opts.images)
222
+ copies.push(await readImage(img));
223
+ // Keep the Message first, so nothing is lost whatever happens next.
224
+ const id = randomBytes(4).toString('hex');
225
+ const sentAt = rt.readContext().now.toISOString();
226
+ const dir = (await messageFolder(rt.readContext().stateDir, [safeName(to.sessionId)], true));
227
+ const stem = `${sentAt.slice(0, 19).replace(/:/g, '-')}Z-${id}`;
228
+ const file = join(dir, `${stem}.md`);
229
+ const attachments = [];
230
+ for (const [i, c] of copies.entries()) {
231
+ const dest = join(dir, `${stem}-${i + 1}.${c.type}`);
232
+ await writeFileAtomic(dest, c.bytes, 0o600);
233
+ attachments.push(dest);
234
+ }
235
+ const receipt = {
236
+ id,
237
+ to: to.label,
238
+ toSessionId: to.sessionId,
239
+ toAccount: to.account,
240
+ ...(from ? { from: from.label } : {}),
241
+ status: 'stored',
242
+ file,
243
+ attachments,
244
+ pasteText: pasteLine(id, file, attachments.length, lang),
245
+ sentAt,
246
+ ...(to.transcript ? { transcript: to.transcript } : {}),
247
+ };
248
+ await writeFileAtomic(file, messageFile(receipt, text), 0o600);
249
+ // From here on the Message is safe: whatever goes wrong, the user gets the line to paste.
250
+ try {
251
+ await saveReceipt(receipt);
252
+ }
253
+ catch (err) {
254
+ // Without a receipt sideby could not follow it later, so it does not deliver it; the Message file is kept.
255
+ receipt.status = 'paste-needed';
256
+ receipt.note = `sideby saved the message file, but could not save its status (${err.code ?? err.message}). Paste the line into the session's tab`;
257
+ return publicReceipt(receipt);
258
+ }
259
+ let result;
260
+ try {
261
+ const acct = (await rt.accounts()).find((a) => a.ref === to.account);
262
+ result = await deliver(rt, to, acct, receipt, text, procDeps, deps);
263
+ }
264
+ catch (err) {
265
+ result = {
266
+ status: 'paste-needed',
267
+ note: `sideby could not deliver it (${err.code ?? err.message}); paste the line into its tab`,
268
+ };
269
+ }
270
+ Object.assign(receipt, result);
271
+ try {
272
+ await saveReceipt(receipt);
273
+ }
274
+ catch (err) {
275
+ // The Message file is kept; only its status could not be recorded. Still hand the user what to do.
276
+ const why = err.code ?? err.message;
277
+ if (receipt.status !== 'paste-needed')
278
+ receipt.note = `sideby could not save the message status (${why})`;
279
+ else
280
+ receipt.note = `${receipt.note ?? 'paste the line into its tab'} (sideby also could not save the message status: ${why})`;
281
+ }
282
+ return publicReceipt(receipt);
283
+ }
284
+ async function deliver(rt, to, acct, r, text, procDeps, deps) {
285
+ if (to.guessed)
286
+ return {
287
+ status: 'paste-needed',
288
+ note: `sideby could not tell which ${to.accountLabel} session is running (picked the newest one). Paste the line into the right tab`,
289
+ };
290
+ if (!acct)
291
+ return {
292
+ status: 'paste-needed',
293
+ note: `account ${to.account} was not found. Paste the line into its terminal tab`,
294
+ };
295
+ const family = DELIVERERS[to.family];
296
+ if (!family || to.pid === undefined)
297
+ return {
298
+ status: 'paste-needed',
299
+ note: `${NO_CHANNEL[to.family] ?? `${rt.families.get(to.family)?.title ?? to.family} cannot receive messages directly`}; paste the line into its terminal tab`,
300
+ };
301
+ return family({
302
+ rt,
303
+ to,
304
+ pid: to.pid,
305
+ acct,
306
+ text: deliveredText(r.id, r.from, text, r.attachments),
307
+ pasteText: r.pasteText,
308
+ // A fresh look at the processes: the screenshots were copied since the listing, and the session may have ended.
309
+ procs: processView(procDeps),
310
+ deps,
311
+ });
312
+ }
313
+ function publicReceipt(s) {
314
+ const { transcript: _t, ...r } = s;
315
+ return r;
316
+ }
317
+ const receiptPath = (file) => file.replace(/\.md$/, '.json');
318
+ async function saveReceipt(r, path = receiptPath(r.file)) {
319
+ await writeFileAtomic(path, `${JSON.stringify(r, null, 2)}\n`, 0o600);
320
+ }
321
+ /** How long after sending a held Message counts as dropped: Claude Code's five minutes plus one of margin. */
322
+ export const APPROVAL_EXPIRED_MS = 6 * 60_000;
323
+ const STATUSES = ['stored', 'delivered', 'read', 'paste-needed'];
324
+ const optStr = (v) => v === undefined || typeof v === 'string';
325
+ /**
326
+ * The receipt at `path` in the Message folder `dir`, when every field has its type and its Message and screenshots
327
+ * are files of that folder named after the receipt; anything else is skipped as not sideby's.
328
+ */
329
+ function validReceipt(raw, dir, path) {
330
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
331
+ return null;
332
+ const r = raw;
333
+ const strs = ['id', 'to', 'toSessionId', 'toAccount', 'file', 'pasteText', 'sentAt'];
334
+ if (!strs.every((k) => typeof r[k] === 'string'))
335
+ return null;
336
+ if (!optStr(r.from) || !optStr(r.note) || !optStr(r.transcript))
337
+ return null;
338
+ if (r.needsApproval !== undefined && typeof r.needsApproval !== 'boolean')
339
+ return null;
340
+ if (typeof r.status !== 'string' || !STATUSES.includes(r.status))
341
+ return null;
342
+ if (!Array.isArray(r.attachments) || !r.attachments.every((a) => typeof a === 'string'))
343
+ return null;
344
+ if (!/^[0-9a-f]{8}$/.test(r.id) || Number.isNaN(Date.parse(r.sentAt)))
345
+ return null;
346
+ const stem = basename(path, '.json');
347
+ if (r.file !== join(dir, `${stem}.md`))
348
+ return null;
349
+ if (!r.attachments.every((a) => dirname(a) === dir && basename(a).startsWith(`${stem}-`)))
350
+ return null;
351
+ if (typeof r.transcript === 'string' && !r.transcript.endsWith('.jsonl'))
352
+ return null;
353
+ return r;
354
+ }
355
+ /**
356
+ * Messages sideby kept, newest first, with their current status (re-checks `delivered` for `read`). A `read` found
357
+ * is saved into the receipt unless `persist` is false (a read-only Panel only computes it).
358
+ */
359
+ export async function listMessages(rt, opts = {}) {
360
+ const stateDir = rt.readContext().stateDir;
361
+ const root = await messageFolder(stateDir, [], false);
362
+ if (!root)
363
+ return [];
364
+ const names = await readdir(root);
365
+ const all = [];
366
+ for (const d of names) {
367
+ if (!isSafeName(d))
368
+ continue;
369
+ let dir;
370
+ try {
371
+ dir = await messageFolder(stateDir, [d], false);
372
+ }
373
+ catch {
374
+ continue;
375
+ }
376
+ if (!dir)
377
+ continue;
378
+ for (const f of await readdir(dir).catch(() => [])) {
379
+ if (!f.endsWith('.json'))
380
+ continue;
381
+ const path = join(dir, f);
382
+ try {
383
+ const st = await lstat(path);
384
+ if (!st.isFile())
385
+ continue;
386
+ const r = validReceipt(JSON.parse(await readFile(path, 'utf8')), dir, path);
387
+ if (r)
388
+ all.push({ r, path });
389
+ }
390
+ catch {
391
+ // a receipt being written
392
+ }
393
+ }
394
+ }
395
+ let list = all;
396
+ if (opts.to) {
397
+ const t = opts.to;
398
+ let ref;
399
+ try {
400
+ ref = (await rt.resolve(t)).ref;
401
+ }
402
+ catch {
403
+ // a session id
404
+ }
405
+ list = all.filter(({ r }) => r.toSessionId === t || (t.length >= 8 && r.toSessionId.startsWith(t)) || r.toAccount === ref);
406
+ }
407
+ list.sort((a, b) => b.r.sentAt.localeCompare(a.r.sentAt));
408
+ list = list.slice(0, opts.limit ?? 20);
409
+ const now = rt.readContext().now.getTime();
410
+ for (const { r, path } of list) {
411
+ if ((r.status !== 'delivered' && r.status !== 'paste-needed') || !r.transcript)
412
+ continue;
413
+ const seen = await tailLinesWith(r.transcript, `sideby message ${r.id}`).catch(() => []);
414
+ let changed = false;
415
+ if (seen.length) {
416
+ r.status = 'read';
417
+ delete r.needsApproval;
418
+ changed = true;
419
+ }
420
+ else if (r.status === 'delivered' &&
421
+ r.needsApproval &&
422
+ now - Date.parse(r.sentAt) > APPROVAL_EXPIRED_MS) {
423
+ // Claude Code drops a held Message after about five minutes (ADR-0045): the user pastes it instead.
424
+ r.status = 'paste-needed';
425
+ delete r.needsApproval;
426
+ r.note = `${r.to} did not show it: nobody approved it within 5 minutes, so the session dropped it. Paste the line into its tab`;
427
+ changed = true;
428
+ }
429
+ if (changed && opts.persist !== false)
430
+ await saveReceipt(r, path).catch(() => { });
431
+ }
432
+ return list.map(({ r }) => publicReceipt(r));
433
+ }
@@ -0,0 +1,14 @@
1
+ import type { ProjectCategoriesDef } from '../types.ts';
2
+ export interface ProjectCategories {
3
+ /** What the categories are called, "Category" when the Plugin gave no name. */
4
+ label: string;
5
+ /** The Plugin that sorts them. */
6
+ owner: string;
7
+ /** The category of each Project that has one. */
8
+ of: Map<string, string>;
9
+ /** Why there are no categories this time, in plain words. */
10
+ problem?: string;
11
+ }
12
+ export declare const CATEGORY_TIMEOUT_MS = 3000;
13
+ /** Asks `def` for categories, remembering each answer for a minute. */
14
+ export declare function categoryReader(def: ProjectCategoriesDef, owner: string, now?: () => number): (projects: string[]) => Promise<ProjectCategories>;
@@ -0,0 +1,48 @@
1
+ export const CATEGORY_TIMEOUT_MS = 3_000;
2
+ const KEEP_MS = 60_000;
3
+ /** Asks `def` for categories, remembering each answer for a minute. */
4
+ export function categoryReader(def, owner, now = Date.now) {
5
+ let kept;
6
+ let pending;
7
+ const label = def.label ?? 'Category';
8
+ return (projects) => {
9
+ const list = [...new Set(projects.filter(Boolean))].sort();
10
+ if (kept && now() - kept.at < KEEP_MS && list.every((p) => kept.asked.has(p)))
11
+ return Promise.resolve({ label, owner, of: kept.of });
12
+ pending ??= ask(def, list)
13
+ .then((of) => {
14
+ kept = { at: now(), asked: new Set(list), of };
15
+ return { label, owner, of };
16
+ })
17
+ .catch((err) => ({
18
+ label,
19
+ owner,
20
+ of: new Map(),
21
+ problem: `${owner}: project categories failed (${err.message}); fix the plugin or remove it`,
22
+ }))
23
+ .finally(() => {
24
+ pending = undefined;
25
+ });
26
+ return pending;
27
+ };
28
+ }
29
+ async function ask(def, list) {
30
+ let timer;
31
+ const late = new Promise((_, reject) => {
32
+ timer = setTimeout(() => reject(new Error(`no answer within ${CATEGORY_TIMEOUT_MS / 1000} s`)), CATEGORY_TIMEOUT_MS);
33
+ });
34
+ try {
35
+ const answer = await Promise.race([Promise.resolve().then(() => def.categoriesOf(list)), late]);
36
+ if (!answer || typeof answer !== 'object' || Array.isArray(answer))
37
+ throw new Error('categoriesOf must return an object of project path to category');
38
+ const asked = new Set(list);
39
+ const of = new Map();
40
+ for (const [path, name] of Object.entries(answer))
41
+ if (asked.has(path) && typeof name === 'string' && name.trim())
42
+ of.set(path, name.trim().slice(0, 80));
43
+ return of;
44
+ }
45
+ finally {
46
+ clearTimeout(timer);
47
+ }
48
+ }
@@ -16,7 +16,7 @@ export declare function quotaCheckOff(family: string, config: {
16
16
  /** The kept answer for `account`, after asking again when `mode` and its age say so. */
17
17
  export declare function fetchedQuota(fq: QuotaFetch, account: Account, ctx: ReadContext, hostEnv: Env, mode: QuotaFetchMode): Promise<QuotaStoreEntry | null>;
18
18
  /**
19
- * What sideby shows from a Family that fetches Quota: the newer of the kept answer and the local reading; else why
20
- * there is none (`off` is why fetching is off, or null).
19
+ * What sideby shows from a Family that fetches Quota: the newer reading, or the kept answer when local events can
20
+ * replay old snapshots (`localFallbackOnly`); else why there is none (`off` is why fetching is off, or null).
21
21
  */
22
- export declare function shownQuota(local: QuotaResult | null, kept: QuotaStoreEntry | null, off: string | null): QuotaResult;
22
+ export declare function shownQuota(local: QuotaResult | null, kept: QuotaStoreEntry | null, off: string | null, localFallbackOnly?: boolean): QuotaResult;
@@ -76,20 +76,20 @@ export async function fetchedQuota(fq, account, ctx, hostEnv, mode) {
76
76
  return Promise.race([run, sleep(FIRST_WAIT_MS)]).then((e) => e ?? kept);
77
77
  }
78
78
  /**
79
- * What sideby shows from a Family that fetches Quota: the newer of the kept answer and the local reading; else why
80
- * there is none (`off` is why fetching is off, or null).
79
+ * What sideby shows from a Family that fetches Quota: the newer reading, or the kept answer when local events can
80
+ * replay old snapshots (`localFallbackOnly`); else why there is none (`off` is why fetching is off, or null).
81
81
  */
82
- export function shownQuota(local, kept, off) {
82
+ export function shownQuota(local, kept, off, localFallbackOnly = false) {
83
83
  const fetched = kept?.quota
84
84
  ? { ...kept.quota, fetched: true, ...(kept.error ? { fetchError: kept.error } : {}) }
85
85
  : null;
86
86
  const own = local?.status === 'ok' ? local : null;
87
87
  if (fetched && own)
88
- return Date.parse(own.observedAt) > Date.parse(fetched.observedAt) ? own : fetched;
88
+ return !localFallbackOnly && Date.parse(own.observedAt) > Date.parse(fetched.observedAt) ? own : fetched;
89
89
  if (fetched)
90
90
  return fetched;
91
91
  if (own)
92
- return own;
92
+ return kept?.error ? { ...own, fetchError: kept.error } : own;
93
93
  if (off)
94
94
  return { status: 'unavailable', reason: 'not-enabled', detail: off };
95
95
  if (kept?.error)
@@ -8,6 +8,11 @@ export declare const QUOTA_WARN_PERCENT = 60;
8
8
  /** Days of Usage every Family reports. */
9
9
  export declare const USAGE_DAYS = 7;
10
10
  export type QuotaLevel = 'ok' | 'warn' | 'fail';
11
+ /** Shared by the Panel and menu bar. Self-contained so the Panel can inline it without other module state. */
12
+ export declare function quotaIsStale(quota: {
13
+ observedAt: string;
14
+ fetchError?: string;
15
+ }, now: number): boolean;
11
16
  export declare function quotaLevel(usedPercent: number): QuotaLevel;
12
17
  /** True once a window's reset time has passed; an unreadable time never counts as reset. */
13
18
  export declare function windowReset(resetsAt: string, now: Date): boolean;