sideby 0.42.1 → 0.43.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 (58) hide show
  1. package/ai-tasks.json +10 -0
  2. package/dist/build.json +1 -1
  3. package/dist/src/cli/commands.js +63 -13
  4. package/dist/src/cli/json-schemas.js +58 -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/handoff-run.js +41 -8
  11. package/dist/src/core/handoff-select.d.ts +5 -0
  12. package/dist/src/core/handoff-select.js +1 -1
  13. package/dist/src/core/handoff.d.ts +69 -1
  14. package/dist/src/core/handoff.js +90 -9
  15. package/dist/src/core/history-index.d.ts +4 -0
  16. package/dist/src/core/history-index.js +1 -1
  17. package/dist/src/core/live-sessions.d.ts +5 -0
  18. package/dist/src/core/live-sessions.js +12 -1
  19. package/dist/src/core/network.d.ts +37 -0
  20. package/dist/src/core/network.js +65 -1
  21. package/dist/src/core/pick-commands.d.ts +7 -1
  22. package/dist/src/core/pick-commands.js +15 -3
  23. package/dist/src/core/pick-records.d.ts +26 -0
  24. package/dist/src/core/pick-records.js +81 -0
  25. package/dist/src/families/agy/history.d.ts +2 -0
  26. package/dist/src/families/agy/history.js +118 -0
  27. package/dist/src/families/agy/index.js +5 -0
  28. package/dist/src/families/agy/quota.d.ts +5 -1
  29. package/dist/src/families/agy/quota.js +111 -10
  30. package/dist/src/families/history.js +2 -1
  31. package/dist/src/network/hook.js +4 -4
  32. package/dist/src/network/page-script.d.ts +40 -0
  33. package/dist/src/network/page-script.js +270 -0
  34. package/dist/src/network/page.d.ts +11 -0
  35. package/dist/src/network/page.js +189 -0
  36. package/dist/src/network/panel.d.ts +5 -0
  37. package/dist/src/network/panel.js +7 -0
  38. package/dist/src/panel/handler.d.ts +21 -1
  39. package/dist/src/panel/handler.js +174 -37
  40. package/dist/src/panel/i18n.d.ts +26 -0
  41. package/dist/src/panel/i18n.js +54 -2
  42. package/dist/src/panel/page-logic.d.ts +26 -3
  43. package/dist/src/panel/page-logic.js +95 -12
  44. package/dist/src/panel/page-script.js +86 -17
  45. package/dist/src/panel/page-styles.js +1 -0
  46. package/dist/src/runtime.d.ts +58 -5
  47. package/dist/src/runtime.js +121 -13
  48. package/dist/src/types.d.ts +3 -2
  49. package/package.json +1 -1
  50. package/schemas/network-diagnose.json +196 -0
  51. package/schemas/next.json +42 -2
  52. package/skills/sideby/SKILL.md +3 -2
  53. package/skills/sideby/references/accounts.md +1 -1
  54. package/skills/sideby/references/ai-tasks.md +1 -1
  55. package/skills/sideby/references/handoff.md +4 -2
  56. package/skills/sideby/references/network.md +6 -1
  57. package/skills/sideby/references/quota.md +1 -1
  58. 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. */
@@ -53,6 +75,20 @@ export interface HandoffEntry {
53
75
  sameLoginAs?: string;
54
76
  /** Set when the Account is never picked for a reason its state does not show: its login expired (ADR-0071). */
55
77
  skip?: HandoffSkip;
78
+ /**
79
+ * The Live Sessions of its Same Login group, its unexpired Pick Records included (ADR-0083). A `ready` Account
80
+ * ranks by its Room per Session: (100 − `limitUse`) / (`liveSessions` + 1).
81
+ */
82
+ liveSessions: number;
83
+ /**
84
+ * For `ready`: its counted Long Window that resets within 24 hours (the soonest), whose room would be lost at the
85
+ * reset, so the Account goes before every other `ready` one (ADR-0083).
86
+ */
87
+ expiring?: {
88
+ label: string;
89
+ usedPercent: number;
90
+ resetsAt: string;
91
+ };
56
92
  }
57
93
  export interface HandoffPlan {
58
94
  family: string;
@@ -82,9 +118,37 @@ export interface HandoffPlan {
82
118
  ref: string;
83
119
  at: string;
84
120
  };
121
+ /**
122
+ * Why a `ready` pick goes first (ADR-0083): `expiring`, its weekly room resets within 24 hours; `room`, it has the
123
+ * most Room per Session.
124
+ */
125
+ reason?: 'expiring' | 'room';
85
126
  }
86
127
  /** An entry that can never be picked whatever its state: the current Account's Same Login, or an Expired Login. */
87
128
  export declare const blocked: (e: HandoffEntry) => boolean;
129
+ /**
130
+ * Live Sessions per Account, also of Accounts that are not candidates (a Same Login partner the Panel is still
131
+ * reading); without it, each candidate's own `liveSessions`.
132
+ */
133
+ export type LiveCounts = ReadonlyMap<string, number>;
134
+ /**
135
+ * Whether a record's time still counts: younger than `PICK_RECORD_MS`. A time a little after `now` counts too: a pick
136
+ * that waited for the lock reads its clock after a peer that wrote one, and the Panel ranks with a time read earlier.
137
+ */
138
+ export declare const pickRecordFresh: (at: string, now: Date) => boolean;
139
+ /**
140
+ * The Pick Records that still count (ADR-0083): fresh, and the login's Live Sessions have not risen above
141
+ * `liveAtPick`. A record of an Account that is not a candidate is kept as it is.
142
+ */
143
+ export declare function activePicks(records: readonly PickRecord[], candidates: readonly HandoffCandidate[], now: Date, counts?: LiveCounts): PickRecord[];
144
+ /**
145
+ * The load of each candidate's login (ADR-0083): the Live Sessions of its Same Login group plus its Pick Records that
146
+ * still count. A new Pick Record keeps its pick's load as `liveAtPick`, so of two picks of one login that have not
147
+ * arrived yet, the first Session to show up ends only the first record.
148
+ */
149
+ export declare function loginLoad(candidates: readonly HandoffCandidate[], picks: readonly PickRecord[], now: Date, counts?: LiveCounts): Map<string, number>;
150
+ /** Room per Session (ADR-0083): the room under the Takeover Limits shared by the login's Live Sessions and one more. */
151
+ export declare const roomPerSession: (e: HandoffEntry) => number;
88
152
  export declare function planHandoff(family: string, candidates: readonly HandoffCandidate[], now: Date,
89
153
  /**
90
154
  * `limits`: the Takeover Limits, at or above which a window makes an Account full (default 85 for Short Windows and
@@ -92,10 +156,14 @@ export declare function planHandoff(family: string, candidates: readonly Handoff
92
156
  * `lastResort`: a start the user asks for; when no Subscription Account is `ready` or `unknown`, pick the full one
93
157
  * with the lowest Limit Use and no window used up, before any API Account (`tight` says so). Auto Handoff leaves it
94
158
  * off.
159
+ * `picks`: Pick Records; the unexpired ones count as Live Sessions of their login (ADR-0083).
160
+ * `live`: Live Sessions per Account, also of Accounts left out of `candidates`, for the Same Login sums.
95
161
  */
96
162
  opts?: {
97
163
  includeApi?: boolean;
98
164
  from?: string;
99
165
  limits?: TakeoverLimits;
100
166
  lastResort?: boolean;
167
+ picks?: readonly PickRecord[];
168
+ live?: LiveCounts;
101
169
  }): 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,7 +29,7 @@ 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);
26
35
  const base = {
@@ -28,6 +37,7 @@ function entry(c, now, limits, lastResort) {
28
37
  kind: c.kind,
29
38
  pressure,
30
39
  limitUse: use?.percent ?? null,
40
+ liveSessions,
31
41
  ...(use?.window
32
42
  ? {
33
43
  window: {
@@ -56,13 +66,74 @@ function stateOfQuota(c, base, pressure, now, limits, lastResort) {
56
66
  return { ...base, state: 'unknown' };
57
67
  // Full once any window reaches its own Takeover Limit: 85 for a Short Window, 95 for a Long one by default.
58
68
  const level = (w) => limitOf(w, limits);
59
- if (!openWindows(c.quota, now)?.some((w) => w.usedPercent >= level(w)))
60
- return { ...base, state: 'ready' };
69
+ const open = openWindows(c.quota, now);
70
+ if (!open?.some((w) => w.usedPercent >= level(w))) {
71
+ const roomy = open?.every((w) => level(w) - w.usedPercent >= EXPIRING_MIN_ROOM) ?? false;
72
+ const soon = roomy ? open?.filter((w) => isLongWindow(w) && expiresSoon(w.resetsAt, now)) : [];
73
+ const w = soon?.sort((a, b) => Date.parse(a.resetsAt) - Date.parse(b.resetsAt))[0];
74
+ return {
75
+ ...base,
76
+ state: 'ready',
77
+ ...(w
78
+ ? { expiring: { label: w.label, usedPercent: Math.round(w.usedPercent), resetsAt: w.resetsAt } }
79
+ : {}),
80
+ };
81
+ }
61
82
  // Usable again only when every full window has reset: the latest of their reset times. For a Last Resort a window
62
83
  // used up is what stops an Account, so its reset is when it can start again.
63
84
  const last = lastReset(c.quota, now, lastResort && pressure >= 100 ? () => 100 : level);
64
85
  return { ...base, state: 'full', ...(last === undefined ? {} : { resetsAt: new Date(last).toISOString() }) };
65
86
  }
87
+ /** Whether a reset time falls within `EXPIRING_HOURS` from now; an unreadable one never does. */
88
+ function expiresSoon(resetsAt, now) {
89
+ const t = Date.parse(resetsAt);
90
+ return Number.isFinite(t) && t - now.getTime() <= EXPIRING_HOURS * 3_600_000;
91
+ }
92
+ /** An Account and the other Accounts of its Same Login. */
93
+ const groupOf = (c, ref) => [ref, ...(c?.sameLogin ?? [])];
94
+ /** The Live Sessions of each candidate's Same Login group, without Pick Records: what tells that a pick has arrived. */
95
+ function groupLiveSessions(candidates, counts) {
96
+ const own = counts ?? new Map(candidates.map((c) => [c.ref, c.liveSessions ?? 0]));
97
+ return new Map(candidates.map((c) => [c.ref, groupOf(c, c.ref).reduce((n, r) => n + (own.get(r) ?? 0), 0)]));
98
+ }
99
+ /**
100
+ * Whether a record's time still counts: younger than `PICK_RECORD_MS`. A time a little after `now` counts too: a pick
101
+ * that waited for the lock reads its clock after a peer that wrote one, and the Panel ranks with a time read earlier.
102
+ */
103
+ export const pickRecordFresh = (at, now) => {
104
+ const age = now.getTime() - Date.parse(at);
105
+ return age > -PICK_RECORD_MS && age < PICK_RECORD_MS;
106
+ };
107
+ /**
108
+ * The Pick Records that still count (ADR-0083): fresh, and the login's Live Sessions have not risen above
109
+ * `liveAtPick`. A record of an Account that is not a candidate is kept as it is.
110
+ */
111
+ export function activePicks(records, candidates, now, counts) {
112
+ const live = groupLiveSessions(candidates, counts);
113
+ return records.filter((r) => {
114
+ if (!pickRecordFresh(r.at, now))
115
+ return false;
116
+ const n = live.get(r.ref);
117
+ return n === undefined || n <= r.liveAtPick;
118
+ });
119
+ }
120
+ /**
121
+ * The load of each candidate's login (ADR-0083): the Live Sessions of its Same Login group plus its Pick Records that
122
+ * still count. A new Pick Record keeps its pick's load as `liveAtPick`, so of two picks of one login that have not
123
+ * arrived yet, the first Session to show up ends only the first record.
124
+ */
125
+ export function loginLoad(candidates, picks, now, counts) {
126
+ const live = groupLiveSessions(candidates, counts);
127
+ const picked = new Map();
128
+ for (const r of activePicks(picks, candidates, now, counts))
129
+ picked.set(r.ref, (picked.get(r.ref) ?? 0) + 1);
130
+ return new Map(candidates.map((c) => [
131
+ c.ref,
132
+ (live.get(c.ref) ?? 0) + groupOf(c, c.ref).reduce((n, r) => n + (picked.get(r) ?? 0), 0),
133
+ ]));
134
+ }
135
+ /** Room per Session (ADR-0083): the room under the Takeover Limits shared by the login's Live Sessions and one more. */
136
+ export const roomPerSession = (e) => (100 - (e.limitUse ?? 0)) / (e.liveSessions + 1);
66
137
  export function planHandoff(family, candidates, now,
67
138
  /**
68
139
  * `limits`: the Takeover Limits, at or above which a window makes an Account full (default 85 for Short Windows and
@@ -70,11 +141,16 @@ export function planHandoff(family, candidates, now,
70
141
  * `lastResort`: a start the user asks for; when no Subscription Account is `ready` or `unknown`, pick the full one
71
142
  * with the lowest Limit Use and no window used up, before any API Account (`tight` says so). Auto Handoff leaves it
72
143
  * off.
144
+ * `picks`: Pick Records; the unexpired ones count as Live Sessions of their login (ADR-0083).
145
+ * `live`: Live Sessions per Account, also of Accounts left out of `candidates`, for the Same Login sums.
73
146
  */
74
147
  opts = {}) {
75
148
  const limits = opts.limits ?? DEFAULT_TAKEOVER_LIMITS;
76
149
  const current = opts.from ? candidates.find((c) => c.ref === opts.from) : undefined;
77
150
  const byRef = new Map(candidates.map((c) => [c.ref, c]));
151
+ // A Live Session counts for the whole login, and so does a Pick Record that has not arrived yet.
152
+ const loads = loginLoad(candidates, opts.picks ?? [], now, opts.live);
153
+ const load = (c) => loads.get(c.ref) ?? 0;
78
154
  const tie = (a, b) => {
79
155
  const x = byRef.get(a.ref);
80
156
  const y = byRef.get(b.ref);
@@ -85,7 +161,7 @@ opts = {}) {
85
161
  const rank = (e) => (opts.lastResort && lastResortOk(e) ? 1.5 : ORDER[e.state]);
86
162
  const accounts = candidates
87
163
  .map((c) => {
88
- const e = entry(c, now, limits, Boolean(opts.lastResort));
164
+ const e = entry(c, now, limits, Boolean(opts.lastResort), load(c));
89
165
  return current?.sameLogin?.includes(c.ref) ? { ...e, sameLoginAs: current.ref } : e;
90
166
  })
91
167
  .sort((a, b) =>
@@ -93,7 +169,10 @@ opts = {}) {
93
169
  // others that cannot.
94
170
  Number(blocked(a)) - Number(blocked(b)) ||
95
171
  rank(a) - rank(b) ||
96
- (a.state === 'ready' || rank(a) === 1.5 ? a.limitUse - b.limitUse : 0) ||
172
+ // Ready: weekly room about to be lost at its reset first, then the most Room per Session (ADR-0083).
173
+ (a.state === 'ready' ? Number(Boolean(b.expiring)) - Number(Boolean(a.expiring)) : 0) ||
174
+ (a.state === 'ready' ? roomPerSession(b) - roomPerSession(a) : 0) ||
175
+ (rank(a) === 1.5 ? a.limitUse - b.limitUse : 0) ||
97
176
  (a.state === 'full' ? resetTime(a) - resetTime(b) || 0 : 0) ||
98
177
  tie(a, b));
99
178
  const usable = (e) => !blocked(e) &&
@@ -101,12 +180,14 @@ opts = {}) {
101
180
  e.state === 'unknown' ||
102
181
  (opts.lastResort && lastResortOk(e)) ||
103
182
  (e.state === 'api' && Boolean(opts.includeApi)));
104
- const picked = accounts.find(usable);
105
- const pick = picked?.ref ?? null;
183
+ const chosen = accounts.find(usable);
184
+ const pick = chosen?.ref ?? null;
106
185
  const hasQuota = accounts.some((e) => e.state === 'ready' || e.state === 'full');
107
186
  const plan = { family, ...(current ? { from: current.ref } : {}), pick, accounts, hasQuota };
108
- if (picked?.state === 'full')
187
+ if (chosen?.state === 'full')
109
188
  plan.tight = { limit: limits.short, longLimit: limits.long };
189
+ if (chosen?.state === 'ready')
190
+ plan.reason = chosen.expiring ? 'expiring' : 'room';
110
191
  if (pick === null) {
111
192
  const first = accounts.find((e) => e.state === 'full' && e.resetsAt && !e.skip);
112
193
  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);
@@ -125,6 +125,43 @@ export declare function networkOverview(opts: {
125
125
  accounts: NetworkAccountRow[];
126
126
  }>;
127
127
  export type NetworkOverview = Awaited<ReturnType<typeof networkOverview>>;
128
+ export type ListenerProbe = (host: string, port: number, timeoutMs: number) => Promise<{
129
+ reachable: boolean;
130
+ error?: string;
131
+ }>;
132
+ /** A local TCP connection attempt; its result says nothing about the proxy protocol or upstream connectivity. */
133
+ export declare const probeListener: ListenerProbe;
134
+ export interface NetworkDiagnosis {
135
+ /** When this offline diagnosis was made (ISO), not when the cached Guard entries were checked. */
136
+ checkedAt: string;
137
+ targets: {
138
+ url: string;
139
+ /** The current process's selected proxy with credentials/path removed, or `direct`. */
140
+ proxy: string;
141
+ /** Whether Network Guard can use this route: HTTP CONNECT only; direct needs no proxy protocol. */
142
+ guardSupport: 'direct' | 'http-connect' | 'unsupported' | 'invalid';
143
+ /** Null for direct, a remote proxy, an unreadable address, or a non-HTTP proxy without an explicit port. */
144
+ listener: null | {
145
+ host: string;
146
+ port: number;
147
+ reachable: boolean;
148
+ error?: string;
149
+ };
150
+ guard: {
151
+ status: NetworkTargetStatus['status'];
152
+ loc?: string;
153
+ checkedAt?: string;
154
+ error?: string;
155
+ };
156
+ }[];
157
+ }
158
+ /**
159
+ * Offline, read-only diagnosis: cached Guard state plus the route visible to this sideby process and a local TCP probe.
160
+ * Unlike `networkOverview({check:true})`, it never calls a trace fetcher, resolves a remote proxy, or writes a cache entry.
161
+ */
162
+ export declare function networkDiagnose(opts: Parameters<typeof networkOverview>[0] & {
163
+ probe?: ListenerProbe;
164
+ }): Promise<NetworkDiagnosis>;
128
165
  export interface NetworkChange {
129
166
  guard?: boolean;
130
167
  allow?: string[];
@@ -1,8 +1,9 @@
1
1
  // Network Guard (spec §3.35, ADR-0053): which address each Account's Egress is checked at, the check before a
2
2
  // Launch, and the hooks that keep checking inside a session sideby starts. The check itself is core/egress.ts.
3
3
  import { mkdir, readFile } from 'node:fs/promises';
4
+ import { createConnection } from 'node:net';
4
5
  import { join } from 'node:path';
5
- import { blockMessage, cacheKey, judge, NETWORK_ENV, prefersChinese, readEntry, refresh, verdict, } from './egress.js';
6
+ import { blockMessage, cacheKey, judge, NETWORK_ENV, prefersChinese, proxyFor, readEntry, refresh, routeLabel, verdict, } from './egress.js';
6
7
  import { UserError } from './errors.js';
7
8
  import { writeFileAtomic } from './fs-safe.js';
8
9
  import { sessionHookArgs, sidebyHookCommand, withClaudeHooks } from './session-hooks.js';
@@ -73,6 +74,7 @@ export async function guardLaunch(opts) {
73
74
  ref: opts.label || opts.account.ref,
74
75
  at: 'launch',
75
76
  zh: prefersChinese(opts.env),
77
+ proxy: routeLabel(target.url, opts.env),
76
78
  }), { code: v.status === 'blocked' ? 'network-blocked' : 'network-unknown' });
77
79
  return {
78
80
  env: { [NETWORK_ENV.url]: target.url, [NETWORK_ENV.allow]: allow.join(','), [NETWORK_ENV.dir]: dir },
@@ -264,6 +266,68 @@ export async function networkOverview(opts) {
264
266
  accounts,
265
267
  };
266
268
  }
269
+ /** A local TCP connection attempt; its result says nothing about the proxy protocol or upstream connectivity. */
270
+ export const probeListener = (host, port, timeoutMs) => new Promise((resolve) => {
271
+ const socket = createConnection({ host, port });
272
+ let done = false;
273
+ const finish = (reachable, error) => {
274
+ if (done)
275
+ return;
276
+ done = true;
277
+ socket.destroy();
278
+ resolve({ reachable, ...(error ? { error } : {}) });
279
+ };
280
+ socket.setTimeout(timeoutMs);
281
+ socket.once('connect', () => finish(true));
282
+ socket.once('timeout', () => finish(false, 'timeout'));
283
+ socket.once('error', (e) => finish(false, e.code || 'failed'));
284
+ });
285
+ /**
286
+ * Offline, read-only diagnosis: cached Guard state plus the route visible to this sideby process and a local TCP probe.
287
+ * Unlike `networkOverview({check:true})`, it never calls a trace fetcher, resolves a remote proxy, or writes a cache entry.
288
+ */
289
+ export async function networkDiagnose(opts) {
290
+ const overview = await networkOverview({ ...opts, check: false });
291
+ const targets = [];
292
+ for (const target of overview.targets) {
293
+ const raw = proxyFor(target.url, opts.env);
294
+ const proxy = routeLabel(target.url, opts.env);
295
+ let guardSupport = raw ? 'invalid' : 'direct';
296
+ let listener = null;
297
+ if (raw && proxy !== 'invalid') {
298
+ // `proxy` is already redacted; parse this rather than the raw environment value at the output boundary.
299
+ const parsed = new URL(proxy.includes('://') ? proxy : `http://${proxy}`);
300
+ guardSupport = parsed.protocol === 'http:' ? 'http-connect' : 'unsupported';
301
+ // Offline diagnosis never resolves or connects to a remote proxy. URL keeps IPv6 brackets in `hostname`;
302
+ // `createConnection` needs the bare address. Only HTTP has a defined default port for this check.
303
+ const host = parsed.hostname.startsWith('[') ? parsed.hostname.slice(1, -1) : parsed.hostname;
304
+ const local = host === 'localhost' || host === '::1' || /^127(?:\.\d{1,3}){3}$/.test(host);
305
+ const port = parsed.port ? Number(parsed.port) : parsed.protocol === 'http:' ? 80 : null;
306
+ if (local && port !== null)
307
+ listener = {
308
+ host,
309
+ port,
310
+ ...(await (opts.probe ?? probeListener)(host, port, 1000).catch(() => ({
311
+ reachable: false,
312
+ error: 'failed',
313
+ }))),
314
+ };
315
+ }
316
+ targets.push({
317
+ url: target.url,
318
+ proxy,
319
+ guardSupport,
320
+ listener,
321
+ guard: {
322
+ status: target.status,
323
+ ...(target.loc ? { loc: target.loc } : {}),
324
+ ...(target.checkedAt ? { checkedAt: target.checkedAt } : {}),
325
+ ...(target.error ? { error: target.error } : {}),
326
+ },
327
+ });
328
+ }
329
+ return { checkedAt: (opts.now?.() ?? new Date()).toISOString(), targets };
330
+ }
267
331
  /** Country codes as config keeps them: upper case, two letters, each once, in the order given. */
268
332
  export function normalizeAllow(codes) {
269
333
  const out = [];