sideby 0.32.2 → 0.34.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 (60) hide show
  1. package/assets/brand/sai-painted-1024.png +0 -0
  2. package/assets/brand/sai-painted-128.png +0 -0
  3. package/assets/brand/sai-painted-256.png +0 -0
  4. package/assets/brand/sai-painted-64.png +0 -0
  5. package/dist/build.json +1 -1
  6. package/dist/src/cli/commands.js +76 -18
  7. package/dist/src/cli/format.js +3 -1
  8. package/dist/src/cli/json-schemas.js +34 -6
  9. package/dist/src/cli/main.js +12 -5
  10. package/dist/src/core/brand-mark.d.ts +18 -115
  11. package/dist/src/core/brand-mark.js +43 -174
  12. package/dist/src/core/live-sessions.d.ts +4 -0
  13. package/dist/src/core/live-sessions.js +17 -3
  14. package/dist/src/core/messages.d.ts +26 -5
  15. package/dist/src/core/messages.js +73 -16
  16. package/dist/src/core/quota-fetch.js +9 -2
  17. package/dist/src/core/session-status.d.ts +55 -0
  18. package/dist/src/core/session-status.js +59 -0
  19. package/dist/src/core/unattended-retry.d.ts +39 -0
  20. package/dist/src/core/unattended-retry.js +107 -0
  21. package/dist/src/core/unattended.d.ts +2 -2
  22. package/dist/src/core/unattended.js +10 -2
  23. package/dist/src/desktop/icon.d.ts +13 -1
  24. package/dist/src/desktop/icon.js +153 -285
  25. package/dist/src/families/claude/deliver.js +14 -2
  26. package/dist/src/families/claude/messaging.d.ts +14 -1
  27. package/dist/src/families/claude/messaging.js +24 -4
  28. package/dist/src/families/codex/deliver.d.ts +10 -1
  29. package/dist/src/families/codex/deliver.js +24 -2
  30. package/dist/src/families/messaging.d.ts +12 -1
  31. package/dist/src/handoff/messages.js +1 -1
  32. package/dist/src/menubar/script.d.ts +5 -0
  33. package/dist/src/menubar/script.js +111 -25
  34. package/dist/src/menubar/snapshot.d.ts +25 -5
  35. package/dist/src/menubar/snapshot.js +114 -26
  36. package/dist/src/menubar/strings.d.ts +22 -6
  37. package/dist/src/menubar/strings.js +22 -6
  38. package/dist/src/panel/handler.d.ts +2 -2
  39. package/dist/src/panel/handler.js +8 -2
  40. package/dist/src/panel/i18n.d.ts +11 -0
  41. package/dist/src/panel/i18n.js +35 -13
  42. package/dist/src/panel/page-logic.d.ts +41 -4
  43. package/dist/src/panel/page-logic.js +145 -10
  44. package/dist/src/panel/page-script.js +50 -11
  45. package/dist/src/panel/page-styles.js +5 -5
  46. package/dist/src/panel/page.js +2 -2
  47. package/dist/src/panel/theme.d.ts +4 -1
  48. package/dist/src/runtime.d.ts +3 -1
  49. package/dist/src/runtime.js +1 -1
  50. package/dist/src/unattended/hook.d.ts +4 -0
  51. package/dist/src/unattended/hook.js +86 -2
  52. package/package.json +2 -1
  53. package/schemas/menubar-snapshot.json +102 -2
  54. package/schemas/messages.json +6 -2
  55. package/schemas/send.json +6 -2
  56. package/schemas/sessions.json +22 -1
  57. package/skills/sideby/SKILL.md +1 -1
  58. package/skills/sideby/references/panel.md +1 -1
  59. package/skills/sideby/references/sessions.md +7 -4
  60. package/skills/sideby/references/unattended.md +4 -2
@@ -1,179 +1,48 @@
1
- // The sideby mark: two buddies side by side, the amber one behind on the left and the blue one in front on the right,
2
- // looking at each other (ADR-0022, the characters of the intro film). One source for the Panel header, the empty
3
- // state, the Portal icon, the favicon and the app icon.
4
- // One buddy is drawn on a 64-unit grid; the mark places two of them with a translate and a scale. Both share one
5
- // gumdrop body; what tells them apart is a pair of props each, from the brand design sheet (ADR-0022 amendment):
6
- // Sai, the blue one, wears a gold crown and a red cape; Bai, the amber one, a bent antenna and a spare battery.
7
- /** The body both buddies share, back to front: feet, arms, body; then the eyes. No forehead `>`: that belongs to Nika. */
8
- export const BUDDY = {
9
- paths: [
10
- { d: 'M17 48 Q15 58 22 57 Q27 57 27 50 M37 50 Q37 57 42 57 Q49 58 47 48', fill: 'shade' },
11
- { d: 'M14 37 C4 32 4 41 14 43 M50 37 C60 32 60 41 50 43', fill: 'body' },
12
- {
13
- d: 'M12 37 C12 27 17 23 25 23 H39 C47 23 52 27 52 37 C52 48 45 53 32 53 C19 53 12 48 12 37 Z',
14
- fill: 'body',
15
- },
16
- ],
17
- eyes: [
18
- { cx: 22, cy: 38.5, rx: 4.5, ry: 6, fill: 'ink' },
19
- { cx: 42, cy: 38.5, rx: 4.5, ry: 6, fill: 'ink' },
20
- ],
21
- };
22
- const RED = '#e0685a';
23
- const GOLD = '#ffd977';
24
- const GREEN = '#5bb06a';
25
- /** Sai (blue): a red cape behind the shoulders, a gold crown with a red jewel, a small smile. */
26
- export const SAI = {
27
- behind: [
28
- { d: 'M19 29 Q10 27 9 34 L4 53 Q13 57 22 50 L42 50 Q51 57 60 53 L55 34 Q54 27 45 29 Z', fill: RED },
29
- ],
30
- mouth: { d: 'M29 46 Q32 49 35 46', fill: 'none', width: 2.5 },
31
- above: [
32
- { d: 'M20 23 L17 10 L27 15 L32 6 L37 15 L47 10 L44 23 Z', fill: GOLD },
33
- {
34
- d: 'M35 19 C35 20.66 33.66 22 32 22 C30.34 22 29 20.66 29 19 C29 17.34 30.34 16 32 16 C33.66 16 35 17.34 35 19 Z',
35
- fill: RED,
36
- stroke: 'none',
37
- },
38
- ],
39
- };
40
- /** Bai (amber): a green spare battery on its back, a bent antenna with a ball, an open laugh. */
41
- export const BAI = {
42
- behind: [
43
- {
44
- d: 'M52 23 H56 C58.21 23 60 24.79 60 27 L60 48 C60 50.21 58.21 52 56 52 H52 C49.79 52 48 50.21 48 48 L48 27 C48 24.79 49.79 23 52 23 Z',
45
- fill: GREEN,
46
- },
47
- { d: 'M52 23 L52 19 H57 L57 23', fill: GREEN },
48
- { d: 'M51 32 H57 M54 29 L54 35', fill: 'none', stroke: 'light', width: 2 },
49
- ],
50
- mouth: { d: 'M29 46 Q32 52 35 46 Z', fill: 'ink', width: 2.5 },
51
- above: [
52
- { d: 'M31 24 C24 17 26 9 36 10', fill: 'none', stroke: GREEN, width: 4 },
53
- {
54
- d: 'M44 10 C44 12.76 41.76 15 39 15 C36.24 15 34 12.76 34 10 C34 7.24 36.24 5 39 5 C41.76 5 44 7.24 44 10 Z',
55
- fill: GREEN,
56
- },
57
- ],
58
- };
59
- /** The eye highlights sit towards where the buddy looks: `1` right, `-1` left. */
60
- export function highlights(look) {
61
- return BUDDY.eyes.map((e) => ({
62
- cx: e.cx + 1.5 * look,
63
- cy: e.cy + (look > 0 ? 0.5 : -2),
64
- rx: 1.65,
65
- ry: 2.1,
66
- fill: 'light',
67
- }));
68
- }
69
- export const MARK_COLORS = {
70
- blue: { body: '#3f8fc4', shade: '#29658e' },
71
- amber: { body: '#f2b35e', shade: '#c98a35' },
72
- ink: '#1e2a44',
73
- light: '#f6f0e5',
74
- };
75
- /** The two buddies in mark units, back first. The blue one in front is the one a Portal's `logoColor` recolours. */
76
- export const MARK = {
77
- /** Outline width of a buddy drawn alone, on its 64-unit grid. */
78
- line: 2.75,
79
- /** Outline width of a placed buddy before its scale, so the outline stays about 2.5 mark units. */
80
- placedLine: 3.6,
81
- back: { colors: MARK_COLORS.amber, props: BAI, look: 1, mirror: true, x: -2, y: 2, scale: 0.7 },
82
- front: { colors: MARK_COLORS.blue, props: SAI, look: -1, x: 22, y: 16, scale: 0.7 },
83
- };
84
- /** The square the pair is drawn in, in mark units (the Panel's 40 px tile and the app icon tile). */
85
- export const MARK_VIEWBOX = { x: -2.5, y: 3, size: 69 };
86
- /** Path data mirrored on the 64-unit grid (x → 64 − x); absolute M, L, H, Q, C, Z only. */
87
- export function mirrorPath(d) {
88
- let cmd = '';
89
- let n = 0;
90
- return d.replace(/[MLHQCZ]|-?\d*\.?\d+/g, (t) => {
91
- if (/[A-Z]/.test(t)) {
92
- cmd = t;
93
- n = 0;
94
- return t;
1
+ // The sideby mark (ADR-0064): Sai, the blue buddy with a gold crown and a red cape, painted in ink and watercolour.
2
+ // One source for the Panel header, the empty state, the Portal icon, the favicon, the Menu Bar Item and the app icon.
3
+ // The paintings are PNGs with a transparent background in assets/brand/ (shipped in the package), one per size; each
4
+ // place picks the smallest one that stays sharp at twice its size. Like the old vector mark, it sits on a light tile.
5
+ import { readFileSync } from 'node:fs';
6
+ /** The sizes painted, in pixels; `assets/brand/sai-painted-<size>.png`. */
7
+ export const MARK_SIZES = [64, 128, 256, 1024];
8
+ const cache = new Map();
9
+ /** The painting at `size` as PNG bytes, from `assets/brand/` (two levels above src/, three above dist/src/). */
10
+ export function markPng(size) {
11
+ const hit = cache.get(size);
12
+ if (hit)
13
+ return hit;
14
+ const name = `assets/brand/sai-painted-${size}.png`;
15
+ for (const rel of ['../../', '../../../']) {
16
+ try {
17
+ const png = readFileSync(new URL(rel + name, import.meta.url));
18
+ cache.set(size, png);
19
+ return png;
95
20
  }
96
- const isX = cmd === 'H' || n++ % 2 === 0;
97
- return isX ? String(Math.round((64 - Number(t)) * 1000) / 1000) : t;
98
- });
99
- }
100
- const paint = (p) => (p === 'ink' ? MARK_COLORS.ink : p === 'light' ? MARK_COLORS.light : p);
101
- /**
102
- * One buddy's shapes, back to front: the props behind, the body, the mouth, the eyes, the props above.
103
- * `bodyFill`: `undefined` keeps the buddy's body colour, `null` leaves the body unfilled so it inherits.
104
- */
105
- export function buddyShapes(b, bodyFill) {
106
- const resolve = (p) => {
107
- const fill = p.fill === 'none'
108
- ? 'none'
109
- : p.fill === 'shade'
110
- ? b.colors.shade
111
- : p.fill === 'body'
112
- ? bodyFill === null
113
- ? undefined
114
- : (bodyFill ?? b.colors.body)
115
- : paint(p.fill);
116
- const stroke = p.stroke === undefined ? MARK_COLORS.ink : p.stroke === 'none' ? 'none' : paint(p.stroke);
117
- return { d: p.d, fill, stroke, ...(p.width ? { width: p.width } : {}) };
118
- };
119
- const prop = (p) => {
120
- const s = resolve(p);
121
- return b.mirror ? { ...s, d: mirrorPath(s.d) } : s;
122
- };
123
- return {
124
- paths: [...b.props.behind.map(prop), ...BUDDY.paths.map(resolve), resolve(b.props.mouth)],
125
- dots: [...BUDDY.eyes, ...highlights(b.look)],
126
- above: b.props.above.map(prop),
127
- };
128
- }
129
- function shapeSvg(s) {
130
- const fill = s.fill === undefined ? '' : ` fill="${s.fill}"`;
131
- const stroke = s.stroke === MARK_COLORS.ink ? '' : ` stroke="${s.stroke}"`;
132
- const width = s.width ? ` stroke-width="${s.width}"` : '';
133
- return `<path d="${s.d}"${fill}${stroke}${width}/>`;
134
- }
135
- /** One placed buddy as SVG, drawn inside a group that sets the ink outline (`MARK_OUTLINE`). */
136
- export function buddySvg(b, line, bodyFill) {
137
- const { paths, dots, above } = buddyShapes(b, bodyFill);
138
- const eyes = dots
139
- .map((e) => `<ellipse cx="${e.cx}" cy="${e.cy}" rx="${e.rx}" ry="${e.ry}" fill="${e.fill === 'ink' ? MARK_COLORS.ink : MARK_COLORS.light}"/>`)
140
- .join('');
141
- const transform = b.scale === 1 && b.x === 0 && b.y === 0 ? '' : ` transform="translate(${b.x} ${b.y}) scale(${b.scale})"`;
142
- return `<g${transform} stroke-width="${line}">${paths.map(shapeSvg).join('')}<g stroke="none">${eyes}</g>${above.map(shapeSvg).join('')}</g>`;
21
+ catch {
22
+ // try the next layout
23
+ }
24
+ }
25
+ throw new Error(`sideby: ${name} is missing from the package; reinstall sideby`);
143
26
  }
144
- export const MARK_OUTLINE = `stroke="${MARK_COLORS.ink}" stroke-linecap="round" stroke-linejoin="round"`;
145
- /**
146
- * The mark as SVG children (no outer <svg>). With `front` omitted the blue buddy's body has no fill of its own, so it
147
- * takes the surrounding `fill` (the Panel's `--logo-fg`, which Portals set with `logoColor`); everything else is fixed.
148
- */
149
- export function markSvgBody(front) {
150
- return `<g ${MARK_OUTLINE}>${buddySvg(MARK.back, MARK.placedLine)}${buddySvg(MARK.front, MARK.placedLine, front ?? null)}</g>`;
27
+ /** The painting at `size` as a `data:` URI. */
28
+ export const markDataUri = (size) => `data:image/png;base64,${markPng(size).toString('base64')}`;
29
+ /** The light tile behind the mark: the Panel's `--logo-bg` default and the app icon's tile. */
30
+ export const MARK_TILE = '#e5f2fb';
31
+ /** How much of its tile the painting fills on each side: 3 of 40 px in the Panel header. */
32
+ export const MARK_INSET = 3 / 40;
33
+ /** The Panel's header logo: the painting for its 40 px tile (sharp at 3x). The page's CSP allows `data:` images. */
34
+ export const MARK_IMG = `<img src="${markDataUri(128)}" alt="" width="40" height="40" decoding="async">`;
35
+ /** The painting as a square SVG with a transparent background, the PNG inside as a `data:` image. */
36
+ function markSvg(size) {
37
+ return (`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" role="img" aria-label="sideby">` +
38
+ `<image href="${markDataUri(size)}" width="${size}" height="${size}"/></svg>`);
151
39
  }
152
- const viewBox = (v) => `${v.x} ${v.y} ${v.size} ${v.size}`;
153
- /** The Panel's header logo: the mark sized for its 40 px tile. */
154
- export const MARK_SVG = `<svg viewBox="${viewBox(MARK_VIEWBOX)}">${markSvgBody()}</svg>`;
155
- /** `<basePath>/icon.svg`: the whole mark on a transparent square, for a Portal's tab or menu (ADR-0006 amendment). */
156
- export const ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${viewBox(MARK_VIEWBOX)}" role="img" aria-label="sideby">` +
157
- `${markSvgBody(MARK_COLORS.blue.body)}</svg>`;
158
- /**
159
- * `<basePath>/favicon.svg`: the small cut for sizes below about 24 px, for a 16 pt browser tab (ADR-0022): Sai alone
160
- * on a 32 grid at half scale, his body, eyes, cape and crown; no feet, arms or mouth. The same cut as the tab icons
161
- * of the brand design sheet.
162
- */
163
- export const FAVICON_SVG = (() => {
164
- const sai = { ...MARK.front, x: 0, y: 0, scale: 1 };
165
- const { paths, dots, above } = buddyShapes(sai);
166
- const body = BUDDY.paths[2].d;
167
- const keep = paths.filter((p) => p.d === body || SAI.behind.some((q) => q.d === p.d));
168
- const eyes = dots
169
- .map((e) => `<ellipse cx="${e.cx}" cy="${e.cy}" rx="${e.rx}" ry="${e.ry}" fill="${e.fill === 'ink' ? MARK_COLORS.ink : MARK_COLORS.light}"/>`)
170
- .join('');
171
- return (`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="sideby">` +
172
- `<g transform="translate(0 -1) scale(.5)"><g ${MARK_OUTLINE} stroke-width="${MARK.line}">` +
173
- `${keep.map(shapeSvg).join('')}<g stroke="none">${eyes}</g>${above.map(shapeSvg).join('')}</g></g></svg>`);
174
- })();
40
+ /** `<basePath>/icon.svg`: the mark on a transparent square, for a Portal's tab or menu (ADR-0006 amendment). */
41
+ export const ICON_SVG = markSvg(128);
42
+ /** `<basePath>/favicon.svg`: the same painting at the size a 16 to 32 px browser tab needs. */
43
+ export const FAVICON_SVG = markSvg(64);
175
44
  /**
176
- * The Menu Bar Item's icon (spec §3.31): the favicon's small cut of Sai in colour, 18 pt square. It keeps its colours
177
- * in light and dark mode, as the brand's tab icons do; the body's dark outline keeps it visible on both.
45
+ * The Menu Bar Item's icon (spec §3.31) and its card's, as base64 PNG: Sai in colour, drawn at 18 pt and 30 pt. It
46
+ * keeps its colours in light and dark mode; the painting's dark outline keeps it visible on both.
178
47
  */
179
- export const MENUBAR_ICON_SVG = FAVICON_SVG.replace('<svg ', '<svg width="18" height="18" ');
48
+ export const MENUBAR_ICON_PNG = markPng(64).toString('base64');
@@ -3,6 +3,7 @@ import type { Runtime } from '../runtime.ts';
3
3
  import type { Account } from '../types.ts';
4
4
  import { type LiveSessionDeps } from './live-sessions-procs.ts';
5
5
  import type { SessionRun } from './run-link.ts';
6
+ import { type NeedsYouReason } from './session-status.ts';
6
7
  export type LiveSessionStatus = 'needs-you' | 'busy' | 'idle' | 'unknown';
7
8
  export interface LiveSession {
8
9
  /** The Account ref, for example `claude:002`. */
@@ -15,7 +16,10 @@ export interface LiveSession {
15
16
  title: string;
16
17
  /** `<accountLabel> · <title> · <first 8 of sessionId>`. */
17
18
  label: string;
19
+ /** The first matching row of the status table (spec §3.32 step 1, `STATUS_RULES` in session-status.ts). */
18
20
  status: LiveSessionStatus;
21
+ /** Why the Session needs the user; only with status `needs-you`. */
22
+ reason?: NeedsYouReason;
19
23
  cwd?: string;
20
24
  pid?: number;
21
25
  startedAt?: string;
@@ -5,6 +5,7 @@ import { liveSessionReader } from '../families/live-sessions.js';
5
5
  import { aliasesByAccount } from './accounts.js';
6
6
  import { aliasArgs, aliasRefs } from './config.js';
7
7
  import { processView, systemDeps } from './live-sessions-procs.js';
8
+ import { MESSAGES_LOOKED_AT, readAttention, withStatus, } from './session-status.js';
8
9
  export const shortId = (id) => id.slice(0, 8);
9
10
  /** `<accountLabel> · <title> · <first 8 of id>`; a Session without a title leaves its part out. */
10
11
  export const sessionLabel = (accountLabel, title, id) => [accountLabel, title, shortId(id)].filter(Boolean).join(' · ');
@@ -87,6 +88,13 @@ export async function listLiveSessions(rt, opts = {}, deps) {
87
88
  const readable = accounts.filter((a) => liveSessionReader(a.family));
88
89
  if (!readable.length)
89
90
  return { sessions: [], problems };
91
+ // What sideby keeps for Sessions (Pending Decisions, Messages) is read beside the Hosts' files. The Messages module
92
+ // reaches back here to pick a target, so it is loaded only when needed.
93
+ const kept = readAttention(rt.readContext().stateDir, async () => (await import('./messages.js')).listMessages(rt, { limit: MESSAGES_LOOKED_AT, persist: false }), problems);
94
+ let keptNow;
95
+ const keptRead = kept.then((k) => {
96
+ keptNow = k;
97
+ });
90
98
  const ctl = new AbortController();
91
99
  const procs = processView(deps ?? systemDeps(rt.env), ctl.signal);
92
100
  const found = [];
@@ -122,13 +130,19 @@ export async function listLiveSessions(rt, opts = {}, deps) {
122
130
  const late = new Promise((resolve) => {
123
131
  timer = setTimeout(() => resolve('late'), deadlineMs);
124
132
  });
125
- if ((await Promise.race([work.then(() => 'done'), late])) === 'late') {
133
+ const done = Promise.all([work, keptRead]).then(() => 'done');
134
+ if ((await Promise.race([done, late])) === 'late') {
126
135
  ctl.abort();
127
- problems.push(`stopped looking after ${deadlineMs / 1000} s; ${[...pending].join(', ') || 'some accounts'} may run sessions that are not shown; run \`sideby sessions\` again`);
136
+ if (pending.size || !keptNow)
137
+ problems.push(pending.size
138
+ ? `stopped looking after ${deadlineMs / 1000} s; ${[...pending].join(', ')} may run sessions that are not shown; run \`sideby sessions\` again`
139
+ : `stopped looking after ${deadlineMs / 1000} s; a session waiting on a decision or a message may not show as needing you; run \`sideby sessions\` again`);
128
140
  }
129
141
  clearTimeout(timer);
142
+ // Past the deadline, what sideby keeps counts only if it was read in time.
143
+ const sessions = withStatus(found, keptNow ?? { decisions: [], receipts: [] });
130
144
  // One unreadable process is met by every Account of its Family: say it once.
131
- return { sessions: sortSessions([...found]), problems: [...new Set(problems)] };
145
+ return { sessions: sortSessions(sessions), problems: [...new Set(problems)] };
132
146
  }
133
147
  export function referenceText(s, lang) {
134
148
  const id = shortId(s.sessionId);
@@ -1,8 +1,12 @@
1
1
  import type { Runtime } from '../runtime.ts';
2
2
  import type { LiveSession } from './live-sessions.ts';
3
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';
4
+ /**
5
+ * stored: kept as a file only; delivered: the Host's channel accepted it; read: the target Session shows it;
6
+ * paste-needed: the user must paste `pasteText` into the target; unknown: the channel was given it but never said
7
+ * whether it took it, so it may still show up (ADR-0065): check the target before sending again.
8
+ */
9
+ export type MessageStatus = 'stored' | 'delivered' | 'read' | 'paste-needed' | 'unknown';
6
10
  export interface MessageReceipt {
7
11
  /** Short id, also written into the delivered text so it can be found in the target's record. */
8
12
  id: string;
@@ -34,6 +38,8 @@ export interface SendOptions {
34
38
  images?: readonly string[];
35
39
  /** Sender Session id when known (the CLI detects it from its parent Host process). */
36
40
  fromSessionId?: string;
41
+ /** The user sends it (the Panel): no sender Session is looked for, so it carries no Reply line. */
42
+ fromUser?: boolean;
37
43
  lang?: 'en' | 'zh';
38
44
  }
39
45
  /** What sending touches on the machine; tests replace each part. */
@@ -51,7 +57,16 @@ export interface MessageDeps {
51
57
  timeoutMs?: number;
52
58
  /** How `codex <args>` runs for Codex delivery; resolves to its exit code. */
53
59
  runCodex?: (args: readonly string[], env: NodeJS.ProcessEnv, timeoutMs: number) => Promise<number>;
60
+ /** The wait between delivery tries; a real timer when left out. */
61
+ sleep?: (ms: number) => Promise<void>;
54
62
  }
63
+ /** How many times a delivery whose channel failed in a way that may pass is tried, the first time included. */
64
+ export declare const DELIVERY_TRIES = 3;
65
+ /** The wait before the second try; each next one waits twice as long, at most `DELIVERY_RETRY_MAX_MS`. */
66
+ export declare const DELIVERY_RETRY_FIRST_MS = 2000;
67
+ export declare const DELIVERY_RETRY_MAX_MS = 60000;
68
+ /** The wait before try `n` (2-based: the first try does not wait). */
69
+ export declare const deliveryRetryDelay: (n: number) => number;
55
70
  /** The largest screenshot sideby copies. */
56
71
  export declare const MAX_IMAGE_BYTES: number;
57
72
  /** The image type of a file's first bytes (`png`, `jpg`, `gif`, `webp`), or null. */
@@ -68,14 +83,20 @@ export declare function messageFolder(stateDir: string, sub: readonly string[],
68
83
  export declare function senderSession(pid: number, procs: readonly ProcessInfo[], sessions: readonly LiveSession[]): LiveSession | undefined;
69
84
  /** The line the user pastes into the target (and keeps for reference when it was delivered). */
70
85
  export declare function pasteLine(id: string, file: string, screenshots: number, lang: 'en' | 'zh'): string;
71
- /** The text a Claude session receives: who sent it, the text, then one line per screenshot so it can read them. */
72
- export declare function deliveredText(id: string, from: string | undefined, text: string, attachments: readonly string[]): string;
86
+ /** The line that tells the receiving AI how to answer a sender sideby identified: `sideby send <its full id>`. */
87
+ export declare const replyLine: (senderSessionId: string) => string;
88
+ /**
89
+ * The text a Claude session receives: who sent it, the text, one line per screenshot so it can read them, then the
90
+ * Reply line when the sender is a Session sideby identified.
91
+ */
92
+ export declare function deliveredText(id: string, from: string | undefined, text: string, attachments: readonly string[], reply?: string): string;
73
93
  /** 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). */
74
94
  export declare function sendMessage(rt: Runtime, target: string, opts: SendOptions, deps?: MessageDeps): Promise<MessageReceipt>;
75
95
  /** How long after sending a held Message counts as dropped: Claude Code's five minutes plus one of margin. */
76
96
  export declare const APPROVAL_EXPIRED_MS: number;
77
97
  /**
78
- * Messages sideby kept, newest first, with their current status (re-checks `delivered` for `read`). A `read` found
98
+ * Messages sideby kept, newest first, with their current status (re-checks `delivered`, `paste-needed` and `unknown`
99
+ * for `read`; an `unknown` one never turns into anything else by itself, ADR-0065). A `read` found
79
100
  * is saved into the receipt unless `persist` is false (a read-only Panel only computes it).
80
101
  */
81
102
  export declare function listMessages(rt: Runtime, opts?: {
@@ -11,6 +11,13 @@ import { UserError } from './errors.js';
11
11
  import { ownedFolder, UnsafeFolderError, writeFileAtomic } from './fs-safe.js';
12
12
  import { processView, systemDeps } from './live-sessions-procs.js';
13
13
  import { selectSession } from './session-select.js';
14
+ /** How many times a delivery whose channel failed in a way that may pass is tried, the first time included. */
15
+ export const DELIVERY_TRIES = 3;
16
+ /** The wait before the second try; each next one waits twice as long, at most `DELIVERY_RETRY_MAX_MS`. */
17
+ export const DELIVERY_RETRY_FIRST_MS = 2_000;
18
+ export const DELIVERY_RETRY_MAX_MS = 60_000;
19
+ /** The wait before try `n` (2-based: the first try does not wait). */
20
+ export const deliveryRetryDelay = (n) => Math.min(DELIVERY_RETRY_MAX_MS, DELIVERY_RETRY_FIRST_MS * 2 ** Math.max(0, n - 2));
14
21
  /** The largest screenshot sideby copies. */
15
22
  export const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
16
23
  const IMAGE_TYPES = [
@@ -134,12 +141,22 @@ export function pasteLine(id, file, screenshots, lang) {
134
141
  return `请读取 sideby 存好的消息 ${file}(sideby message ${id})${screenshots ? ',以及里面列出的截图' : ''}。`;
135
142
  return `Read the message sideby kept for you at ${file} (sideby message ${id})${screenshots ? ' and the screenshots it lists' : ''}.`;
136
143
  }
137
- /** The text a Claude session receives: who sent it, the text, then one line per screenshot so it can read them. */
138
- export function deliveredText(id, from, text, attachments) {
144
+ /** The line that tells the receiving AI how to answer a sender sideby identified: `sideby send <its full id>`. */
145
+ export const replyLine = (senderSessionId) => `Reply: sideby send ${senderSessionId} "<text>"`;
146
+ /**
147
+ * The text a Claude session receives: who sent it, the text, one line per screenshot so it can read them, then the
148
+ * Reply line when the sender is a Session sideby identified.
149
+ */
150
+ export function deliveredText(id, from, text, attachments, reply) {
139
151
  const head = `sideby message ${id} ${from ? `from ${from}` : 'from the user via sideby'}`;
140
- return [head, ...(text ? [text] : []), ...attachments.map((a) => `Screenshot: ${a}`)].join('\n');
152
+ return [
153
+ head,
154
+ ...(text ? [text] : []),
155
+ ...attachments.map((a) => `Screenshot: ${a}`),
156
+ ...(reply ? [reply] : []),
157
+ ].join('\n');
141
158
  }
142
- function messageFile(r, text) {
159
+ function messageFile(r, text, reply) {
143
160
  const lines = [
144
161
  `# sideby message ${r.id}`,
145
162
  '',
@@ -151,6 +168,8 @@ function messageFile(r, text) {
151
168
  ];
152
169
  if (r.attachments.length)
153
170
  lines.push('', 'Screenshots:', ...r.attachments.map((a) => `- ${a}`));
171
+ if (reply)
172
+ lines.push('', reply);
154
173
  return `${lines.join('\n')}\n`;
155
174
  }
156
175
  const NO_CHANNEL = {
@@ -168,7 +187,7 @@ export async function sendMessage(rt, target, opts, deps = {}) {
168
187
  const lang = opts.lang ?? 'en';
169
188
  const images = await openImages(paths);
170
189
  try {
171
- return await sendOpened(rt, target, { text, lang, images, fromSessionId: opts.fromSessionId }, deps);
190
+ return await sendOpened(rt, target, { text, lang, images, fromSessionId: opts.fromSessionId, fromUser: opts.fromUser === true }, deps);
172
191
  }
173
192
  finally {
174
193
  await Promise.all(images.map((i) => i.fh.close().catch(() => { })));
@@ -182,7 +201,9 @@ async function sendOpened(rt, target, opts, deps) {
182
201
  deps: procDeps,
183
202
  });
184
203
  let from;
185
- if (opts.fromSessionId)
204
+ if (opts.fromUser)
205
+ from = undefined;
206
+ else if (opts.fromSessionId)
186
207
  from = listed.sessions.find((s) => s.sessionId === opts.fromSessionId);
187
208
  else {
188
209
  const all = await processView(procDeps)
@@ -223,7 +244,9 @@ async function sendOpened(rt, target, opts, deps) {
223
244
  sentAt,
224
245
  ...(to.transcript ? { transcript: to.transcript } : {}),
225
246
  };
226
- await writeFileAtomic(file, messageFile(receipt, text), 0o600);
247
+ // Only a sender sideby knows exactly gets a way to answer: a guessed one may be the wrong session.
248
+ const reply = from && !from.guessed ? replyLine(from.sessionId) : undefined;
249
+ await writeFileAtomic(file, messageFile(receipt, text, reply), 0o600);
227
250
  // From here on the Message is safe: whatever goes wrong, the user gets the line to paste.
228
251
  try {
229
252
  await saveReceipt(receipt);
@@ -237,7 +260,7 @@ async function sendOpened(rt, target, opts, deps) {
237
260
  let result;
238
261
  try {
239
262
  const acct = (await rt.accounts()).find((a) => a.ref === to.account);
240
- result = await deliver(rt, to, acct, receipt, text, procDeps, deps);
263
+ result = await deliverWithRetry(() => deliver(rt, to, acct, receipt, text, reply, procDeps, deps), to, procDeps, deps);
241
264
  }
242
265
  catch (err) {
243
266
  result = {
@@ -245,21 +268,48 @@ async function sendOpened(rt, target, opts, deps) {
245
268
  note: `sideby could not deliver it (${err.code ?? err.message}); paste the line into its tab`,
246
269
  };
247
270
  }
248
- Object.assign(receipt, result);
271
+ const { retry: _retry, ...outcome } = result;
272
+ Object.assign(receipt, outcome);
249
273
  try {
250
274
  await saveReceipt(receipt);
251
275
  }
252
276
  catch (err) {
253
277
  // The Message file is kept; only its status could not be recorded. Still hand the user what to do.
254
278
  const why = err.code ?? err.message;
255
- if (receipt.status !== 'paste-needed')
279
+ if (receipt.status === 'delivered')
256
280
  receipt.note = `sideby could not save the message status (${why})`;
257
281
  else
258
282
  receipt.note = `${receipt.note ?? 'paste the line into its tab'} (sideby also could not save the message status: ${why})`;
259
283
  }
260
284
  return { ...publicReceipt(receipt), ...(handedOverFrom ? { handedOverFrom } : {}) };
261
285
  }
262
- async function deliver(rt, to, acct, r, text, procDeps, deps) {
286
+ /**
287
+ * Delivers, and tries again while the channel failed in a way that may pass and took nothing (`retry`, never after a
288
+ * write that may have reached the session, ADR-0065): up to `DELIVERY_TRIES` times, 2 s, then 4 s apart, and not once
289
+ * the target's process is gone. Every try runs every check again (settings, session record, socket owner and folder).
290
+ * The last failure is the result, its note saying how many tries were made.
291
+ */
292
+ async function deliverWithRetry(once, to, procDeps, deps) {
293
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
294
+ let result = await once();
295
+ let tries = 1;
296
+ while (result.retry && result.status === 'paste-needed' && tries < DELIVERY_TRIES) {
297
+ if (to.pid === undefined)
298
+ break;
299
+ const gone = await processView(procDeps)
300
+ .get(to.pid)
301
+ .then((p) => !p, () => false);
302
+ if (gone)
303
+ break;
304
+ tries++;
305
+ await sleep(deliveryRetryDelay(tries));
306
+ result = await once();
307
+ }
308
+ if (result.retry && result.status === 'paste-needed' && tries > 1 && result.note)
309
+ result = { ...result, note: result.note.replace(/\); paste /, `; tried ${tries} times); paste `) };
310
+ return result;
311
+ }
312
+ async function deliver(rt, to, acct, r, text, reply, procDeps, deps) {
263
313
  if (to.guessed)
264
314
  return {
265
315
  status: 'paste-needed',
@@ -276,15 +326,19 @@ async function deliver(rt, to, acct, r, text, procDeps, deps) {
276
326
  status: 'paste-needed',
277
327
  note: `${NO_CHANNEL[to.family] ?? `${rt.families.get(to.family)?.title ?? to.family} cannot receive messages directly`}; paste the line into its terminal tab`,
278
328
  };
329
+ const pid = to.pid;
279
330
  return family({
280
331
  rt,
281
332
  to,
282
- pid: to.pid,
333
+ pid,
283
334
  acct,
284
- text: deliveredText(r.id, r.from, text, r.attachments),
335
+ text: deliveredText(r.id, r.from, text, r.attachments, reply),
285
336
  pasteText: r.pasteText,
286
337
  // A fresh look at the processes: the screenshots were copied since the listing, and the session may have ended.
287
338
  procs: processView(procDeps),
339
+ ended: () => processView(procDeps)
340
+ .get(pid)
341
+ .then((p) => !p, () => false),
288
342
  deps,
289
343
  });
290
344
  }
@@ -296,9 +350,11 @@ const receiptPath = (file) => file.replace(/\.md$/, '.json');
296
350
  async function saveReceipt(r, path = receiptPath(r.file)) {
297
351
  await writeFileAtomic(path, `${JSON.stringify(r, null, 2)}\n`, 0o600);
298
352
  }
353
+ /** The statuses whose Message may still show in the target's record, so it is looked for there. */
354
+ const READ_CHECKED = new Set(['delivered', 'paste-needed', 'unknown']);
299
355
  /** How long after sending a held Message counts as dropped: Claude Code's five minutes plus one of margin. */
300
356
  export const APPROVAL_EXPIRED_MS = 6 * 60_000;
301
- const STATUSES = ['stored', 'delivered', 'read', 'paste-needed'];
357
+ const STATUSES = ['stored', 'delivered', 'read', 'paste-needed', 'unknown'];
302
358
  const optStr = (v) => v === undefined || typeof v === 'string';
303
359
  /**
304
360
  * The receipt at `path` in the Message folder `dir`, when every field has its type and its Message and screenshots
@@ -331,7 +387,8 @@ function validReceipt(raw, dir, path) {
331
387
  return r;
332
388
  }
333
389
  /**
334
- * Messages sideby kept, newest first, with their current status (re-checks `delivered` for `read`). A `read` found
390
+ * Messages sideby kept, newest first, with their current status (re-checks `delivered`, `paste-needed` and `unknown`
391
+ * for `read`; an `unknown` one never turns into anything else by itself, ADR-0065). A `read` found
335
392
  * is saved into the receipt unless `persist` is false (a read-only Panel only computes it).
336
393
  */
337
394
  export async function listMessages(rt, opts = {}) {
@@ -386,7 +443,7 @@ export async function listMessages(rt, opts = {}) {
386
443
  list = list.slice(0, opts.limit ?? 20);
387
444
  const now = rt.readContext().now.getTime();
388
445
  for (const { r, path } of list) {
389
- if ((r.status !== 'delivered' && r.status !== 'paste-needed') || !r.transcript)
446
+ if (!READ_CHECKED.has(r.status) || !r.transcript)
390
447
  continue;
391
448
  const seen = await tailLinesWith(r.transcript, `sideby message ${r.id}`).catch(() => []);
392
449
  let changed = false;
@@ -84,8 +84,15 @@ export function shownQuota(local, kept, off, localFallbackOnly = false) {
84
84
  ? { ...kept.quota, fetched: true, ...(kept.error ? { fetchError: kept.error } : {}) }
85
85
  : null;
86
86
  const own = local?.status === 'ok' ? local : null;
87
- if (fetched && own)
88
- return !localFallbackOnly && Date.parse(own.observedAt) > Date.parse(fetched.observedAt) ? own : fetched;
87
+ if (fetched && own) {
88
+ if (localFallbackOnly || Date.parse(own.observedAt) <= Date.parse(fetched.observedAt))
89
+ return fetched;
90
+ // A local reading (Claude's status line) sees only the plan-wide windows. Keep the fetched model-group windows it
91
+ // cannot see, so a group's line (such as Fable) does not come and go with whichever reading is newer.
92
+ const seen = new Set(own.windows.map((w) => `${w.name ?? ''}\0${w.label}`));
93
+ const groups = fetched.windows.filter((w) => w.name && !seen.has(`${w.name}\0${w.label}`));
94
+ return groups.length ? { ...own, windows: [...own.windows, ...groups] } : own;
95
+ }
89
96
  if (fetched)
90
97
  return fetched;
91
98
  if (own)
@@ -0,0 +1,55 @@
1
+ import type { LiveSessionStatus } from './live-sessions.ts';
2
+ import type { MessageReceipt } from './messages.ts';
3
+ import { type PendingDecision } from './unattended-pending.ts';
4
+ /** Why a Session needs the user: the row of `STATUS_RULES` that matched. Set only with status `needs-you`. */
5
+ export type NeedsYouReason = 'host-waits' | 'pending-decision' | 'message-to-approve' | 'message-to-paste';
6
+ /** What the table looks at for one Session. */
7
+ export interface StatusSignals {
8
+ /** What the Host's own files say (a Family reader's status). */
9
+ host: LiveSessionStatus;
10
+ /** Open Pending Decisions kept for this Session. */
11
+ pendingDecisions: number;
12
+ /** Messages delivered to it that it shows only once the user approves them in its terminal (ADR-0045). */
13
+ messagesToApprove: number;
14
+ /** Messages to it that wait for the user to paste them (`paste-needed`) and its record does not show yet. */
15
+ messagesToPaste: number;
16
+ }
17
+ export interface StatusRule {
18
+ status: LiveSessionStatus;
19
+ reason?: NeedsYouReason;
20
+ when: (s: StatusSignals) => boolean;
21
+ }
22
+ /** The table of spec §3.32 step 1, in order; the first row whose `when` holds gives the status. */
23
+ export declare const STATUS_RULES: readonly StatusRule[];
24
+ /** The status the first matching row of `STATUS_RULES` gives, and its reason when it is `needs-you`. */
25
+ export declare function sessionStatus(s: StatusSignals): {
26
+ status: LiveSessionStatus;
27
+ reason?: NeedsYouReason;
28
+ };
29
+ /** The fields of a Live Session the table needs. */
30
+ export interface StatusTarget {
31
+ account: string;
32
+ family: string;
33
+ sessionId: string;
34
+ status: LiveSessionStatus;
35
+ transcript?: string;
36
+ }
37
+ /** What sideby keeps for Sessions, read once per listing. */
38
+ export interface SessionAttention {
39
+ decisions: readonly PendingDecision[];
40
+ receipts: readonly MessageReceipt[];
41
+ }
42
+ /** The signals of one Session, from its Host status and what sideby keeps for it. */
43
+ export declare function signalsOf(s: StatusTarget, kept: SessionAttention): StatusSignals;
44
+ /** Each Session with the status the table gives it; `reason` is set only on `needs-you`, and dropped otherwise. */
45
+ export declare function withStatus<T extends StatusTarget & {
46
+ reason?: NeedsYouReason;
47
+ }>(sessions: readonly T[], kept: SessionAttention): T[];
48
+ /** How many of the newest Messages are looked at: each may read the end of its target's record. */
49
+ export declare const MESSAGES_LOOKED_AT = 50;
50
+ /**
51
+ * Reads what sideby keeps for Sessions: open Pending Decisions and the newest Messages, both without writing (an old
52
+ * done Decision is not deleted, a Message found read is not saved). A store that cannot be read adds a problem line
53
+ * and counts as empty.
54
+ */
55
+ export declare function readAttention(stateDir: string, messages: () => Promise<readonly MessageReceipt[]>, problems: string[]): Promise<SessionAttention>;