sideby 0.42.2 → 0.44.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 (66) hide show
  1. package/ai-tasks.json +10 -0
  2. package/dist/build.json +1 -1
  3. package/dist/src/cli/commands.js +54 -13
  4. package/dist/src/cli/json-schemas.js +65 -1
  5. package/dist/src/cli/main.js +11 -4
  6. package/dist/src/core/ask.d.ts +8 -14
  7. package/dist/src/core/ask.js +66 -30
  8. package/dist/src/core/egress.d.ts +5 -0
  9. package/dist/src/core/egress.js +32 -2
  10. package/dist/src/core/file-memo.d.ts +2 -0
  11. package/dist/src/core/file-memo.js +20 -0
  12. package/dist/src/core/handoff-run.js +41 -8
  13. package/dist/src/core/handoff-select.d.ts +5 -0
  14. package/dist/src/core/handoff-select.js +1 -1
  15. package/dist/src/core/handoff.d.ts +78 -1
  16. package/dist/src/core/handoff.js +100 -9
  17. package/dist/src/core/history-index.d.ts +4 -0
  18. package/dist/src/core/history-index.js +1 -1
  19. package/dist/src/core/live-sessions.d.ts +5 -0
  20. package/dist/src/core/live-sessions.js +12 -1
  21. package/dist/src/core/memo-store.js +32 -8
  22. package/dist/src/core/network.d.ts +37 -0
  23. package/dist/src/core/network.js +65 -1
  24. package/dist/src/core/pick-commands.d.ts +7 -1
  25. package/dist/src/core/pick-commands.js +15 -3
  26. package/dist/src/core/pick-records.d.ts +26 -0
  27. package/dist/src/core/pick-records.js +81 -0
  28. package/dist/src/families/agy/history.d.ts +2 -0
  29. package/dist/src/families/agy/history.js +118 -0
  30. package/dist/src/families/agy/index.js +5 -0
  31. package/dist/src/families/agy/quota.d.ts +5 -1
  32. package/dist/src/families/agy/quota.js +111 -10
  33. package/dist/src/families/history.js +2 -1
  34. package/dist/src/families/quota-watch.d.ts +12 -0
  35. package/dist/src/families/quota-watch.js +24 -0
  36. package/dist/src/network/hook.js +4 -4
  37. package/dist/src/network/page-script.d.ts +40 -0
  38. package/dist/src/network/page-script.js +270 -0
  39. package/dist/src/network/page.d.ts +11 -0
  40. package/dist/src/network/page.js +189 -0
  41. package/dist/src/network/panel.d.ts +5 -0
  42. package/dist/src/network/panel.js +7 -0
  43. package/dist/src/panel/changes.d.ts +57 -0
  44. package/dist/src/panel/changes.js +178 -0
  45. package/dist/src/panel/handler.d.ts +59 -1
  46. package/dist/src/panel/handler.js +374 -99
  47. package/dist/src/panel/i18n.d.ts +49 -0
  48. package/dist/src/panel/i18n.js +100 -2
  49. package/dist/src/panel/page-logic.d.ts +37 -3
  50. package/dist/src/panel/page-logic.js +106 -12
  51. package/dist/src/panel/page-script.js +194 -27
  52. package/dist/src/panel/page-styles.js +18 -8
  53. package/dist/src/panel/page.js +3 -1
  54. package/dist/src/runtime.d.ts +55 -5
  55. package/dist/src/runtime.js +105 -12
  56. package/dist/src/types.d.ts +3 -2
  57. package/package.json +1 -1
  58. package/schemas/network-diagnose.json +196 -0
  59. package/schemas/next.json +67 -2
  60. package/skills/sideby/SKILL.md +3 -2
  61. package/skills/sideby/references/accounts.md +1 -1
  62. package/skills/sideby/references/ai-tasks.md +1 -1
  63. package/skills/sideby/references/handoff.md +6 -2
  64. package/skills/sideby/references/network.md +6 -1
  65. package/skills/sideby/references/quota.md +1 -1
  66. package/skills/sideby/references/sessions.md +1 -1
@@ -147,12 +147,19 @@ function limitUntil(ready, now = new Date()) {
147
147
  ? new Date(at).toISOString()
148
148
  : new Date(now.getTime() + LIMIT_WAIT_FALLBACK_MS).toISOString();
149
149
  }
150
- /** The decision, or `none` with the reason when sideby cannot tell (an account removed mid-chain, say). */
151
- async function decide(rt, account, used, to, manual = false) {
150
+ /**
151
+ * The decision, or `none` with the reason when sideby cannot tell (an account removed mid-chain, say). Counts the Live
152
+ * Sessions into the ranking (ADR-0083); `record` when the handoff starts its pick, so a Pick Record is written.
153
+ */
154
+ async function decide(rt, account, used, to, manual = false,
155
+ /** Set when the handoff starts its pick: a Pick Record is written and given here. */
156
+ recorded) {
152
157
  try {
153
158
  return await rt.handoffDecision(account, used, {
154
159
  ...(to !== undefined ? { to } : {}),
155
160
  ...(manual ? { manual: true } : {}),
161
+ picks: recorded ? 'record' : 'read',
162
+ ...(recorded ? { recorded } : {}),
156
163
  });
157
164
  }
158
165
  catch (err) {
@@ -202,13 +209,30 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
202
209
  let hop = { ref, args: [...aliasArgs(own), ...userArgs] };
203
210
  let n = 1;
204
211
  const chainSettings = join(rt.paths.stateDir, 'handoff', 'chains', `${chain}-claude.json`);
212
+ // The Pick Record of the hop about to start (ADR-0083): taken back unless that Host really starts.
213
+ let picked;
214
+ const dropPicked = async () => {
215
+ const rec = picked;
216
+ picked = undefined;
217
+ if (rec)
218
+ await rt.cancelPick(rec);
219
+ };
220
+ // The record is kept once the Host process exists; a Host that cannot start (ENOENT) leaves it to `dropPicked`.
221
+ const started = (p) => {
222
+ const host = spawnHost(p);
223
+ host.child.once('spawn', () => {
224
+ picked = undefined;
225
+ });
226
+ return host;
227
+ };
205
228
  try {
206
229
  for (;;) {
207
230
  const launch = n === 1 ? firstLaunch : await rt.prepareLaunch(hop.ref, hop.args, 'run', launchOpts);
208
231
  const account = launch.account;
209
232
  const h = launch.family.handoff;
210
- if (!h)
211
- return await runHost(launch);
233
+ if (!h) {
234
+ return await started(launch).exited;
235
+ }
212
236
  const elig = n === 1 ? firstElig : await h.eligibility(withoutNetwork(launch), account, launch.env);
213
237
  const canStart = h.starts.length > 0 && elig.start && HOOK_FAMILIES.includes(account.family);
214
238
  if (!canStart && elig.reason)
@@ -249,8 +273,9 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
249
273
  await writeJsonFile(join(dir, FILES.chain), hops);
250
274
  if (launch.notice)
251
275
  io.err(launch.notice);
252
- if (!canStart)
253
- return await runHost({ ...launch, args, env });
276
+ if (!canStart) {
277
+ return await started({ ...launch, args, env }).exited;
278
+ }
254
279
  // Plan writes run one after another, and none lands after this hop is over: a late one would carry this
255
280
  // run's id into the next hop's plan.json and silence its hook.
256
281
  let stopped = false;
@@ -285,7 +310,7 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
285
310
  };
286
311
  await writePlan();
287
312
  const refresh = setInterval(() => void writePlan(), PLAN_REFRESH_MS);
288
- const host = spawnHost({ ...launch, args, env });
313
+ const host = started({ ...launch, args, env });
289
314
  const exited = host.exited.then((code) => ({ kind: 'exit', code }));
290
315
  // Nothing to move on to (or better to wait): leave the session alone, keep listening (the user may still ask to
291
316
  // move on while it waits, ADR-0018), and say why once it ends.
@@ -302,7 +327,9 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
302
327
  outcome = got;
303
328
  break;
304
329
  }
305
- const d = await decide(rt, account, hops.hops, got.ready.to, got.ready.trigger === 'manual');
330
+ const d = await decide(rt, account, hops.hops, got.ready.to, got.ready.trigger === 'manual', (r) => {
331
+ picked = r;
332
+ });
306
333
  if (d.kind === 'pick') {
307
334
  outcome = { ...got, decision: d };
308
335
  break;
@@ -340,6 +367,8 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
340
367
  new Promise((r) => setTimeout(() => r(null), grace).unref()),
341
368
  ]);
342
369
  if (!ended) {
370
+ // Nothing starts, so the pick's record is taken back (ADR-0083).
371
+ await dropPicked();
343
372
  io.err(`sideby: ${account.ref} did not exit within ${grace / 1000}s, so nothing was handed over; exit it yourself, then start the next account with \`sideby run ${decision.ref}\``);
344
373
  return await host.exited;
345
374
  }
@@ -370,6 +399,7 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
370
399
  if (settings.countdownSeconds > 0 &&
371
400
  (await countdown(io, settings.countdownSeconds, decision.ref, account.ref))) {
372
401
  io.err(`sideby: staying in ${account.ref}`);
402
+ await dropPicked();
373
403
  if (!ready.sessionId) {
374
404
  io.err(`sideby: the session id is unknown, so start ${account.ref} yourself; the Brief is at ${done.path}`);
375
405
  return ended.code;
@@ -385,6 +415,7 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
385
415
  next = await rt.resolve(decision.ref);
386
416
  }
387
417
  catch (err) {
418
+ await dropPicked();
388
419
  io.err(`sideby: cannot start ${decision.ref}: ${err.message}; the Brief is at ${done.path}`);
389
420
  return ended.code;
390
421
  }
@@ -398,6 +429,8 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
398
429
  }
399
430
  }
400
431
  finally {
432
+ // A pick whose Host never started (its launch failed, say) does not count for the next pick.
433
+ await dropPicked();
401
434
  // Read by Claude Code while a session runs, so it goes only once the chain's last Host is over.
402
435
  await rm(chainSettings, { force: true });
403
436
  }
@@ -1,5 +1,6 @@
1
1
  import type { Account, AccountIdentity, LoginProblem, LoginState, QuotaResult } from '../types.ts';
2
2
  import type { HandoffSettings } from './config.ts';
3
+ import { type PickRecord } from './handoff.ts';
3
4
  export interface SelectCandidate {
4
5
  ref: string;
5
6
  family: string;
@@ -19,6 +20,8 @@ export interface SelectCandidate {
19
20
  receive: boolean;
20
21
  /** A session stopped at the limit continues by itself at the reset (`FamilyHandoff.resumesAtReset`); set for the origin. */
21
22
  resumesAtReset?: boolean;
23
+ /** Its own Live Sessions now; a Family's ranking sums them over each Same Login (ADR-0083). */
24
+ liveSessions?: number;
22
25
  }
23
26
  /** An Account the Handoff Order lists that was left out, and why (spec §3.21). */
24
27
  export interface SkippedAccount {
@@ -98,4 +101,6 @@ export declare function selectNext(input: {
98
101
  to?: string;
99
102
  /** The user asked to hand over (`sideby handoff ready`): never wait for a reset (ADR-0018). */
100
103
  manual?: boolean;
104
+ /** Pick Records: the unexpired ones count as Live Sessions of their login when ranking (ADR-0083). */
105
+ picks?: readonly PickRecord[];
101
106
  }): HandoffDecision;
@@ -86,7 +86,7 @@ export function selectNext(input) {
86
86
  const used = stillUsed(origin.ref, input.used, now);
87
87
  const family = s.families[origin.family];
88
88
  const limits = takeoverLimits(s.threshold);
89
- const rank = (fam) => planHandoff(fam, input.candidates.filter((c) => c.family === fam), now, { includeApi: true, limits }).accounts.map((e) => byRef.get(e.ref));
89
+ const rank = (fam) => planHandoff(fam, input.candidates.filter((c) => c.family === fam), now, { includeApi: true, limits, ...(input.picks ? { picks: input.picks } : {}) }).accounts.map((e) => byRef.get(e.ref));
90
90
  let list;
91
91
  if (family?.policy === 'order') {
92
92
  list = family.order.map(refOf).flatMap((r) => (byRef.has(r) ? [byRef.get(r)] : []));
@@ -12,7 +12,28 @@ export interface HandoffCandidate {
12
12
  quota: QuotaResult;
13
13
  /** The other Accounts of its Same Login (spec §3.21). */
14
14
  sameLogin?: readonly string[];
15
+ /** Its own Live Sessions now (ADR-0083); the ranking sums them over its Same Login. Left out: none. */
16
+ liveSessions?: number;
15
17
  }
18
+ /**
19
+ * A Pick Record (ADR-0083): a pick that just started `ref`, with the Live Sessions its login had then. Until the
20
+ * login's Live Sessions rise above `liveAtPick` or `PICK_RECORD_MS` pass, it counts as one Live Session of that login.
21
+ */
22
+ export interface PickRecord {
23
+ ref: string;
24
+ /** ISO timestamp of the pick. */
25
+ at: string;
26
+ liveAtPick: number;
27
+ }
28
+ /** How long a Pick Record counts at most: the time a new Session takes to show up as a Live Session. */
29
+ export declare const PICK_RECORD_MS = 120000;
30
+ /** A counted Long Window that resets within this many hours puts a `ready` Account first (ADR-0083). Fixed. */
31
+ export declare const EXPIRING_HOURS = 24;
32
+ /**
33
+ * Points every open window must still have under its own Takeover Limit for the expiring tier: with less, a new
34
+ * Session soon reaches the limit and hands over again, so the Account ranks by Room per Session instead. Fixed.
35
+ */
36
+ export declare const EXPIRING_MIN_ROOM = 10;
16
37
  /** Why an Account that could otherwise be picked is left out, and the command that fixes it (ADR-0071). */
17
38
  export interface HandoffSkip {
18
39
  reason: 'login-expired';
@@ -27,7 +48,8 @@ export interface HandoffEntry {
27
48
  pressure: number | null;
28
49
  /**
29
50
  * Limit Use: the percent of its own Takeover Limit that the closest window has used (a weekly window at 87% under
30
- * 95 is 91.6), null when the Account has no Quota. Ready Accounts rank by it, lowest first.
51
+ * 95 is 91.6), null when the Account has no Quota. Ready Accounts rank by the room it leaves per Live Session
52
+ * (`liveSessions`), Last Resorts by it, lowest first.
31
53
  */
32
54
  limitUse: number | null;
33
55
  /** That window: its label (`5h`, `7d`), used percent and own Takeover Limit; absent when no window is open. */
@@ -36,6 +58,15 @@ export interface HandoffEntry {
36
58
  usedPercent: number;
37
59
  limit: number;
38
60
  };
61
+ /**
62
+ * Every counted window (no model `name`) that has not reset, so a caller can show what the pick has left (spec
63
+ * §3.45); absent when none is open.
64
+ */
65
+ windows?: {
66
+ label: string;
67
+ usedPercent: number;
68
+ resetsAt: string;
69
+ }[];
39
70
  /**
40
71
  * For `full`: when the last window at or over its own Takeover Limit resets, so the Account is usable again. In a
41
72
  * plan for a start the user asks for (`lastResort`), an Account with a window used up is usable again once those
@@ -53,6 +84,20 @@ export interface HandoffEntry {
53
84
  sameLoginAs?: string;
54
85
  /** Set when the Account is never picked for a reason its state does not show: its login expired (ADR-0071). */
55
86
  skip?: HandoffSkip;
87
+ /**
88
+ * The Live Sessions of its Same Login group, its unexpired Pick Records included (ADR-0083). A `ready` Account
89
+ * ranks by its Room per Session: (100 − `limitUse`) / (`liveSessions` + 1).
90
+ */
91
+ liveSessions: number;
92
+ /**
93
+ * For `ready`: its counted Long Window that resets within 24 hours (the soonest), whose room would be lost at the
94
+ * reset, so the Account goes before every other `ready` one (ADR-0083).
95
+ */
96
+ expiring?: {
97
+ label: string;
98
+ usedPercent: number;
99
+ resetsAt: string;
100
+ };
56
101
  }
57
102
  export interface HandoffPlan {
58
103
  family: string;
@@ -82,9 +127,37 @@ export interface HandoffPlan {
82
127
  ref: string;
83
128
  at: string;
84
129
  };
130
+ /**
131
+ * Why a `ready` pick goes first (ADR-0083): `expiring`, its weekly room resets within 24 hours; `room`, it has the
132
+ * most Room per Session.
133
+ */
134
+ reason?: 'expiring' | 'room';
85
135
  }
86
136
  /** An entry that can never be picked whatever its state: the current Account's Same Login, or an Expired Login. */
87
137
  export declare const blocked: (e: HandoffEntry) => boolean;
138
+ /**
139
+ * Live Sessions per Account, also of Accounts that are not candidates (a Same Login partner the Panel is still
140
+ * reading); without it, each candidate's own `liveSessions`.
141
+ */
142
+ export type LiveCounts = ReadonlyMap<string, number>;
143
+ /**
144
+ * Whether a record's time still counts: younger than `PICK_RECORD_MS`. A time a little after `now` counts too: a pick
145
+ * that waited for the lock reads its clock after a peer that wrote one, and the Panel ranks with a time read earlier.
146
+ */
147
+ export declare const pickRecordFresh: (at: string, now: Date) => boolean;
148
+ /**
149
+ * The Pick Records that still count (ADR-0083): fresh, and the login's Live Sessions have not risen above
150
+ * `liveAtPick`. A record of an Account that is not a candidate is kept as it is.
151
+ */
152
+ export declare function activePicks(records: readonly PickRecord[], candidates: readonly HandoffCandidate[], now: Date, counts?: LiveCounts): PickRecord[];
153
+ /**
154
+ * The load of each candidate's login (ADR-0083): the Live Sessions of its Same Login group plus its Pick Records that
155
+ * still count. A new Pick Record keeps its pick's load as `liveAtPick`, so of two picks of one login that have not
156
+ * arrived yet, the first Session to show up ends only the first record.
157
+ */
158
+ export declare function loginLoad(candidates: readonly HandoffCandidate[], picks: readonly PickRecord[], now: Date, counts?: LiveCounts): Map<string, number>;
159
+ /** Room per Session (ADR-0083): the room under the Takeover Limits shared by the login's Live Sessions and one more. */
160
+ export declare const roomPerSession: (e: HandoffEntry) => number;
88
161
  export declare function planHandoff(family: string, candidates: readonly HandoffCandidate[], now: Date,
89
162
  /**
90
163
  * `limits`: the Takeover Limits, at or above which a window makes an Account full (default 85 for Short Windows and
@@ -92,10 +165,14 @@ export declare function planHandoff(family: string, candidates: readonly Handoff
92
165
  * `lastResort`: a start the user asks for; when no Subscription Account is `ready` or `unknown`, pick the full one
93
166
  * with the lowest Limit Use and no window used up, before any API Account (`tight` says so). Auto Handoff leaves it
94
167
  * off.
168
+ * `picks`: Pick Records; the unexpired ones count as Live Sessions of their login (ADR-0083).
169
+ * `live`: Live Sessions per Account, also of Accounts left out of `candidates`, for the Same Login sums.
95
170
  */
96
171
  opts?: {
97
172
  includeApi?: boolean;
98
173
  from?: string;
99
174
  limits?: TakeoverLimits;
100
175
  lastResort?: boolean;
176
+ picks?: readonly PickRecord[];
177
+ live?: LiveCounts;
101
178
  }): HandoffPlan;
@@ -1,4 +1,13 @@
1
- import { DEFAULT_TAKEOVER_LIMITS, limitOf, limitUse, openWindows, quotaPressure, windowReset, } from './quota-levels.js';
1
+ import { DEFAULT_TAKEOVER_LIMITS, isLongWindow, limitOf, limitUse, openWindows, quotaPressure, windowReset, } from './quota-levels.js';
2
+ /** How long a Pick Record counts at most: the time a new Session takes to show up as a Live Session. */
3
+ export const PICK_RECORD_MS = 120_000;
4
+ /** A counted Long Window that resets within this many hours puts a `ready` Account first (ADR-0083). Fixed. */
5
+ export const EXPIRING_HOURS = 24;
6
+ /**
7
+ * Points every open window must still have under its own Takeover Limit for the expiring tier: with less, a new
8
+ * Session soon reaches the limit and hands over again, so the Account ranks by Room per Session instead. Fixed.
9
+ */
10
+ export const EXPIRING_MIN_ROOM = 10;
2
11
  const ORDER = { ready: 0, unknown: 1, api: 2, full: 3, 'logged-out': 4 };
3
12
  /** A full Account without a readable reset time sorts after every one that has one. */
4
13
  const resetTime = (e) => (e.resetsAt ? Date.parse(e.resetsAt) : Number.POSITIVE_INFINITY);
@@ -20,14 +29,16 @@ function lastReset(quota, now, level) {
20
29
  const lastResortOk = (e) => e.state === 'full' && !blocked(e) && e.pressure !== null && e.pressure < 100;
21
30
  /** An entry that can never be picked whatever its state: the current Account's Same Login, or an Expired Login. */
22
31
  export const blocked = (e) => Boolean(e.sameLoginAs || e.skip);
23
- function entry(c, now, limits, lastResort) {
32
+ function entry(c, now, limits, lastResort, liveSessions) {
24
33
  const pressure = quotaPressure(c.quota, now);
25
34
  const use = limitUse(c.quota, now, limits);
35
+ const open = openWindows(c.quota, now);
26
36
  const base = {
27
37
  ref: c.ref,
28
38
  kind: c.kind,
29
39
  pressure,
30
40
  limitUse: use?.percent ?? null,
41
+ liveSessions,
31
42
  ...(use?.window
32
43
  ? {
33
44
  window: {
@@ -37,6 +48,15 @@ function entry(c, now, limits, lastResort) {
37
48
  },
38
49
  }
39
50
  : {}),
51
+ ...(open?.length
52
+ ? {
53
+ windows: open.map((w) => ({
54
+ label: w.label,
55
+ usedPercent: Math.round(w.usedPercent),
56
+ resetsAt: w.resetsAt,
57
+ })),
58
+ }
59
+ : {}),
40
60
  ...(c.quota.status === 'ok' ? { observedAt: c.quota.observedAt } : {}),
41
61
  ...(c.quota.status === 'ok' && c.quota.from ? { quotaFrom: c.quota.from } : {}),
42
62
  };
@@ -56,13 +76,74 @@ function stateOfQuota(c, base, pressure, now, limits, lastResort) {
56
76
  return { ...base, state: 'unknown' };
57
77
  // Full once any window reaches its own Takeover Limit: 85 for a Short Window, 95 for a Long one by default.
58
78
  const level = (w) => limitOf(w, limits);
59
- if (!openWindows(c.quota, now)?.some((w) => w.usedPercent >= level(w)))
60
- return { ...base, state: 'ready' };
79
+ const open = openWindows(c.quota, now);
80
+ if (!open?.some((w) => w.usedPercent >= level(w))) {
81
+ const roomy = open?.every((w) => level(w) - w.usedPercent >= EXPIRING_MIN_ROOM) ?? false;
82
+ const soon = roomy ? open?.filter((w) => isLongWindow(w) && expiresSoon(w.resetsAt, now)) : [];
83
+ const w = soon?.sort((a, b) => Date.parse(a.resetsAt) - Date.parse(b.resetsAt))[0];
84
+ return {
85
+ ...base,
86
+ state: 'ready',
87
+ ...(w
88
+ ? { expiring: { label: w.label, usedPercent: Math.round(w.usedPercent), resetsAt: w.resetsAt } }
89
+ : {}),
90
+ };
91
+ }
61
92
  // Usable again only when every full window has reset: the latest of their reset times. For a Last Resort a window
62
93
  // used up is what stops an Account, so its reset is when it can start again.
63
94
  const last = lastReset(c.quota, now, lastResort && pressure >= 100 ? () => 100 : level);
64
95
  return { ...base, state: 'full', ...(last === undefined ? {} : { resetsAt: new Date(last).toISOString() }) };
65
96
  }
97
+ /** Whether a reset time falls within `EXPIRING_HOURS` from now; an unreadable one never does. */
98
+ function expiresSoon(resetsAt, now) {
99
+ const t = Date.parse(resetsAt);
100
+ return Number.isFinite(t) && t - now.getTime() <= EXPIRING_HOURS * 3_600_000;
101
+ }
102
+ /** An Account and the other Accounts of its Same Login. */
103
+ const groupOf = (c, ref) => [ref, ...(c?.sameLogin ?? [])];
104
+ /** The Live Sessions of each candidate's Same Login group, without Pick Records: what tells that a pick has arrived. */
105
+ function groupLiveSessions(candidates, counts) {
106
+ const own = counts ?? new Map(candidates.map((c) => [c.ref, c.liveSessions ?? 0]));
107
+ return new Map(candidates.map((c) => [c.ref, groupOf(c, c.ref).reduce((n, r) => n + (own.get(r) ?? 0), 0)]));
108
+ }
109
+ /**
110
+ * Whether a record's time still counts: younger than `PICK_RECORD_MS`. A time a little after `now` counts too: a pick
111
+ * that waited for the lock reads its clock after a peer that wrote one, and the Panel ranks with a time read earlier.
112
+ */
113
+ export const pickRecordFresh = (at, now) => {
114
+ const age = now.getTime() - Date.parse(at);
115
+ return age > -PICK_RECORD_MS && age < PICK_RECORD_MS;
116
+ };
117
+ /**
118
+ * The Pick Records that still count (ADR-0083): fresh, and the login's Live Sessions have not risen above
119
+ * `liveAtPick`. A record of an Account that is not a candidate is kept as it is.
120
+ */
121
+ export function activePicks(records, candidates, now, counts) {
122
+ const live = groupLiveSessions(candidates, counts);
123
+ return records.filter((r) => {
124
+ if (!pickRecordFresh(r.at, now))
125
+ return false;
126
+ const n = live.get(r.ref);
127
+ return n === undefined || n <= r.liveAtPick;
128
+ });
129
+ }
130
+ /**
131
+ * The load of each candidate's login (ADR-0083): the Live Sessions of its Same Login group plus its Pick Records that
132
+ * still count. A new Pick Record keeps its pick's load as `liveAtPick`, so of two picks of one login that have not
133
+ * arrived yet, the first Session to show up ends only the first record.
134
+ */
135
+ export function loginLoad(candidates, picks, now, counts) {
136
+ const live = groupLiveSessions(candidates, counts);
137
+ const picked = new Map();
138
+ for (const r of activePicks(picks, candidates, now, counts))
139
+ picked.set(r.ref, (picked.get(r.ref) ?? 0) + 1);
140
+ return new Map(candidates.map((c) => [
141
+ c.ref,
142
+ (live.get(c.ref) ?? 0) + groupOf(c, c.ref).reduce((n, r) => n + (picked.get(r) ?? 0), 0),
143
+ ]));
144
+ }
145
+ /** Room per Session (ADR-0083): the room under the Takeover Limits shared by the login's Live Sessions and one more. */
146
+ export const roomPerSession = (e) => (100 - (e.limitUse ?? 0)) / (e.liveSessions + 1);
66
147
  export function planHandoff(family, candidates, now,
67
148
  /**
68
149
  * `limits`: the Takeover Limits, at or above which a window makes an Account full (default 85 for Short Windows and
@@ -70,11 +151,16 @@ export function planHandoff(family, candidates, now,
70
151
  * `lastResort`: a start the user asks for; when no Subscription Account is `ready` or `unknown`, pick the full one
71
152
  * with the lowest Limit Use and no window used up, before any API Account (`tight` says so). Auto Handoff leaves it
72
153
  * off.
154
+ * `picks`: Pick Records; the unexpired ones count as Live Sessions of their login (ADR-0083).
155
+ * `live`: Live Sessions per Account, also of Accounts left out of `candidates`, for the Same Login sums.
73
156
  */
74
157
  opts = {}) {
75
158
  const limits = opts.limits ?? DEFAULT_TAKEOVER_LIMITS;
76
159
  const current = opts.from ? candidates.find((c) => c.ref === opts.from) : undefined;
77
160
  const byRef = new Map(candidates.map((c) => [c.ref, c]));
161
+ // A Live Session counts for the whole login, and so does a Pick Record that has not arrived yet.
162
+ const loads = loginLoad(candidates, opts.picks ?? [], now, opts.live);
163
+ const load = (c) => loads.get(c.ref) ?? 0;
78
164
  const tie = (a, b) => {
79
165
  const x = byRef.get(a.ref);
80
166
  const y = byRef.get(b.ref);
@@ -85,7 +171,7 @@ opts = {}) {
85
171
  const rank = (e) => (opts.lastResort && lastResortOk(e) ? 1.5 : ORDER[e.state]);
86
172
  const accounts = candidates
87
173
  .map((c) => {
88
- const e = entry(c, now, limits, Boolean(opts.lastResort));
174
+ const e = entry(c, now, limits, Boolean(opts.lastResort), load(c));
89
175
  return current?.sameLogin?.includes(c.ref) ? { ...e, sameLoginAs: current.ref } : e;
90
176
  })
91
177
  .sort((a, b) =>
@@ -93,7 +179,10 @@ opts = {}) {
93
179
  // others that cannot.
94
180
  Number(blocked(a)) - Number(blocked(b)) ||
95
181
  rank(a) - rank(b) ||
96
- (a.state === 'ready' || rank(a) === 1.5 ? a.limitUse - b.limitUse : 0) ||
182
+ // Ready: weekly room about to be lost at its reset first, then the most Room per Session (ADR-0083).
183
+ (a.state === 'ready' ? Number(Boolean(b.expiring)) - Number(Boolean(a.expiring)) : 0) ||
184
+ (a.state === 'ready' ? roomPerSession(b) - roomPerSession(a) : 0) ||
185
+ (rank(a) === 1.5 ? a.limitUse - b.limitUse : 0) ||
97
186
  (a.state === 'full' ? resetTime(a) - resetTime(b) || 0 : 0) ||
98
187
  tie(a, b));
99
188
  const usable = (e) => !blocked(e) &&
@@ -101,12 +190,14 @@ opts = {}) {
101
190
  e.state === 'unknown' ||
102
191
  (opts.lastResort && lastResortOk(e)) ||
103
192
  (e.state === 'api' && Boolean(opts.includeApi)));
104
- const picked = accounts.find(usable);
105
- const pick = picked?.ref ?? null;
193
+ const chosen = accounts.find(usable);
194
+ const pick = chosen?.ref ?? null;
106
195
  const hasQuota = accounts.some((e) => e.state === 'ready' || e.state === 'full');
107
196
  const plan = { family, ...(current ? { from: current.ref } : {}), pick, accounts, hasQuota };
108
- if (picked?.state === 'full')
197
+ if (chosen?.state === 'full')
109
198
  plan.tight = { limit: limits.short, longLimit: limits.long };
199
+ if (chosen?.state === 'ready')
200
+ plan.reason = chosen.expiring ? 'expiring' : 'room';
110
201
  if (pick === null) {
111
202
  const first = accounts.find((e) => e.state === 'full' && e.resetsAt && !e.skip);
112
203
  if (first?.resetsAt)
@@ -1,5 +1,8 @@
1
1
  import type { DatabaseSync } from 'node:sqlite';
2
2
  import type { ParsedSession, TitleSource } from '../families/history.ts';
3
+ type Sqlite = typeof import('node:sqlite');
4
+ /** `node:sqlite` without its experimental warning (ADR-0042); undefined when this Node has none. */
5
+ export declare function loadSqlite(): Promise<Sqlite | undefined>;
3
6
  export interface SessionRow {
4
7
  id: number;
5
8
  account: string;
@@ -147,3 +150,4 @@ export declare class HistoryIndex {
147
150
  failed: number;
148
151
  }>;
149
152
  }
153
+ export {};
@@ -10,7 +10,7 @@ import { UserError } from './errors.js';
10
10
  const SCHEMA = 4;
11
11
  let sqlite;
12
12
  /** `node:sqlite` without its experimental warning (ADR-0042); undefined when this Node has none. */
13
- function loadSqlite() {
13
+ export function loadSqlite() {
14
14
  sqlite ??= (async () => {
15
15
  const emit = process.emitWarning;
16
16
  process.emitWarning = ((w, ...rest) => {
@@ -46,6 +46,11 @@ export interface LiveSessionsResult {
46
46
  sessions: LiveSession[];
47
47
  /** One line per Account or Family that could not be read; never aborts the listing. */
48
48
  problems: string[];
49
+ /**
50
+ * Set when the running programs could not be listed or the deadline left Accounts unread: a count from it may be
51
+ * short. A problem with one Account's files alone does not set it.
52
+ */
53
+ partial?: boolean;
49
54
  }
50
55
  export type SessionCopyAs = 'reference' | 'id' | 'resume';
51
56
  export declare const shortId: (id: string) => string;
@@ -26,6 +26,9 @@ export function hostResumeArgs(family, id) {
26
26
  return `resume ${id}`;
27
27
  if (family === 'claude' || family === 'grok')
28
28
  return `--resume ${id}`;
29
+ // agy 1.5.14 `--help`: `--conversation` resumes a previous conversation by id (2026-11-23).
30
+ if (family === 'agy')
31
+ return `--conversation ${id}`;
29
32
  return `--session ${id}`;
30
33
  }
31
34
  /** The command that resumes `id` (Resume Routing, spec §3.15, starts the Account that holds it). */
@@ -109,6 +112,7 @@ export async function listLiveSessions(rt, opts = {}, deps) {
109
112
  const procs = processView(deps ?? systemDeps(rt.env), ctl.signal);
110
113
  const found = [];
111
114
  const pending = new Set(readable.map((a) => a.ref));
115
+ let partial = false;
112
116
  const work = (async () => {
113
117
  try {
114
118
  await procs.list();
@@ -118,6 +122,7 @@ export async function listLiveSessions(rt, opts = {}, deps) {
118
122
  return;
119
123
  problems.push(`could not list running programs (${err.message}); sideby needs \`ps\` on PATH to tell which sessions still run`);
120
124
  pending.clear();
125
+ partial = true;
121
126
  return;
122
127
  }
123
128
  await Promise.all(readable.map(async (account) => {
@@ -143,6 +148,8 @@ export async function listLiveSessions(rt, opts = {}, deps) {
143
148
  const done = Promise.all([work, keptRead]).then(() => 'done');
144
149
  if ((await Promise.race([done, late])) === 'late') {
145
150
  ctl.abort();
151
+ if (pending.size)
152
+ partial = true;
146
153
  if (pending.size || !keptNow)
147
154
  problems.push(pending.size
148
155
  ? `stopped looking after ${deadlineMs / 1000} s; ${[...pending].join(', ')} may run sessions that are not shown; run \`sideby sessions\` again`
@@ -152,7 +159,11 @@ export async function listLiveSessions(rt, opts = {}, deps) {
152
159
  // Past the deadline, what sideby keeps counts only if it was read in time.
153
160
  const sessions = withStatus(found, keptNow ?? { decisions: [], receipts: [] });
154
161
  // One unreadable process is met by every Account of its Family: say it once.
155
- return { sessions: sortSessions(sessions), problems: [...new Set(problems)] };
162
+ return {
163
+ sessions: sortSessions(sessions),
164
+ problems: [...new Set(problems)],
165
+ ...(partial ? { partial: true } : {}),
166
+ };
156
167
  }
157
168
  export function referenceText(s, lang) {
158
169
  const id = shortId(s.sessionId);
@@ -1,7 +1,12 @@
1
- // Keeps the persisted FileMemos (core/file-memo.ts) in `<stateDir>/cache/file-memo.json`, so a new process does not
1
+ // Keeps the persisted FileMemos (core/file-memo.ts) in `<stateDir>/cache/file-memo-2.json`, so a new process does not
2
2
  // parse every session log again: the Panel worker starts cold after each restart, reinstall or language switch,
3
3
  // and parsing the logs of a busy HOME takes seconds, while reading this file back takes milliseconds.
4
4
  //
5
+ // Several sideby processes share a state directory (a Panel worker, a background Panel, launchers that wait for hours).
6
+ // Each one writes only the scopes it read itself since its last write, into what the file holds at that moment, so a
7
+ // process that loaded the file long ago never puts its old parses back over newer ones. An older sideby that is still
8
+ // running writes the whole of `cache/file-memo.json`; this file has another name, so it cannot undo these merges.
9
+ //
5
10
  // The file holds token counts, session ids and log paths, never a credential; it is written atomically with mode
6
11
  // 600. Anything unexpected in it (another format, a parse error, a memo version that changed) is ignored and the
7
12
  // logs are parsed again, which gives the same results.
@@ -15,7 +20,7 @@ export const SAVE_INTERVAL_MS = 60_000;
15
20
  /** A write waits this long after the last read, so one Panel refresh over every Account is written as a whole. */
16
21
  export const SAVE_DELAY_MS = 2_000;
17
22
  export function memoCachePath(stateDir) {
18
- return join(stateDir, 'cache', 'file-memo.json');
23
+ return join(stateDir, 'cache', 'file-memo-2.json');
19
24
  }
20
25
  const stores = new Map();
21
26
  /** One store per state directory and process. */
@@ -28,13 +33,23 @@ export function memoStore(stateDir, now = Date.now, delayMs = SAVE_DELAY_MS) {
28
33
  let writing;
29
34
  let lastWrite = Number.NEGATIVE_INFINITY;
30
35
  let timer;
31
- const load = async () => {
36
+ /** The cache file's memos, or null when it is missing or not one this sideby can read. */
37
+ const readCache = async () => {
32
38
  try {
33
39
  const data = JSON.parse(await readFile(file, 'utf8'));
34
- if (data?.format !== FORMAT || !data.memos || typeof data.memos !== 'object')
40
+ return data?.format === FORMAT && data.memos && typeof data.memos === 'object' ? data.memos : null;
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ };
46
+ const load = async () => {
47
+ try {
48
+ const memos = await readCache();
49
+ if (!memos)
35
50
  return;
36
51
  for (const [name, memo] of persistedMemos) {
37
- const saved = data.memos[name];
52
+ const saved = memos[name];
38
53
  if (saved && saved.version === memo.persist?.version && saved.data && typeof saved.data === 'object')
39
54
  memo.restore(saved.data);
40
55
  }
@@ -47,9 +62,18 @@ export function memoStore(stateDir, now = Date.now, delayMs = SAVE_DELAY_MS) {
47
62
  if (![...persistedMemos.values()].some((m) => m.dirty))
48
63
  return;
49
64
  lastWrite = now();
50
- const out = { format: FORMAT, memos: {} };
51
- for (const [name, memo] of persistedMemos)
52
- out.memos[name] = { version: memo.persist?.version ?? 0, data: memo.dump() };
65
+ // Taken before the file is read again, so a pass that ends meanwhile counts toward the next write.
66
+ const fresh = [...persistedMemos].map(([name, memo]) => [name, memo, memo.takeFresh()]);
67
+ // Memos this process does not know (another sideby's) are kept as they are.
68
+ const out = { format: FORMAT, memos: { ...(await readCache()) } };
69
+ for (const [name, memo, scopes] of fresh) {
70
+ const version = memo.persist?.version ?? 0;
71
+ const saved = out.memos[name];
72
+ // A memo of another version is dropped whole, as `load` would.
73
+ const data = saved?.version === version && saved.data && typeof saved.data === 'object' ? { ...saved.data } : {};
74
+ Object.assign(data, scopes);
75
+ out.memos[name] = { version, data };
76
+ }
53
77
  try {
54
78
  await mkdir(join(stateDir, 'cache'), { recursive: true, mode: 0o700 });
55
79
  await writeFileAtomic(file, JSON.stringify(out));