sideby 0.28.3 → 0.29.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.
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261029T042753-69f9e3"}
1
+ {"id":"20261029T062926-04866c"}
@@ -130,6 +130,8 @@ export declare function cmdConfig(a: ParsedArgs, io: Io): Promise<number>;
130
130
  * `sideby sessions open-run <account|session-id>` opens the Run Board of one (spec §3.32 step 2b).
131
131
  */
132
132
  export declare function cmdSessions(a: ParsedArgs, io: Io, runtime?: Runtime): Promise<number>;
133
+ /** The line that says a session id was followed along its Handoff chain (ADR-0057). */
134
+ export declare function handedOverLine(from: string, label: string, doing: string): string;
133
135
  export declare function cmdHistory(a: ParsedArgs, io: Io): Promise<number>;
134
136
  export interface SendArgs extends ParsedArgs {
135
137
  /** Every `--image` given, in order (main.ts collects them; parseArgs keeps only the last). */
@@ -2991,8 +2991,11 @@ export async function cmdSessions(a, io, runtime) {
2991
2991
  const rt = runtime ?? (await createRuntime());
2992
2992
  const { listLiveSessions, sessionLabel } = await import('../core/live-sessions.js');
2993
2993
  const { withRuns } = await import('../core/run-link.js');
2994
+ const { readHandoffChains, withHandoffs } = await import('../core/session-handoffs.js');
2994
2995
  const r = await listLiveSessions(rt, first ? { only: first } : {});
2995
- const sessions = await withRuns(rt.env, rt.paths.home, r.sessions);
2996
+ // Where an Auto Handoff chain led to a Session, its earlier ids; the Run Link falls back to them (ADR-0057).
2997
+ const handed = withHandoffs(await readHandoffChains(rt.paths.stateDir), r.sessions);
2998
+ const sessions = await withRuns(rt.env, rt.paths.home, handed);
2996
2999
  if (a.flags.has('json')) {
2997
3000
  json(io, { sessions, problems: r.problems });
2998
3001
  return 0;
@@ -3034,6 +3037,10 @@ export async function cmdSessions(a, io, runtime) {
3034
3037
  io.out(c.dim('Copy one for another AI: sideby sessions copy <account|session-id>'));
3035
3038
  return 0;
3036
3039
  }
3040
+ /** The line that says a session id was followed along its Handoff chain (ADR-0057). */
3041
+ export function handedOverLine(from, label, doing) {
3042
+ return c.dim(`${from.slice(0, 8)} was handed over to ${label}; ${doing}`);
3043
+ }
3037
3044
  /** Prints the listing's problems to stderr unless the output is JSON. */
3038
3045
  const listedProblems = (a, io) => (l) => {
3039
3046
  if (!a.flags.has('json'))
@@ -3047,7 +3054,7 @@ async function sessionsOpenRun(a, args, io, runtime) {
3047
3054
  const rt = runtime ?? (await createRuntime());
3048
3055
  const { selectSession } = await import('../core/session-select.js');
3049
3056
  const { openRunBoard } = await import('../core/run-link.js');
3050
- const { session: s } = await selectSession(rt, target, {
3057
+ const { session: s, handedOverFrom } = await selectSession(rt, target, {
3051
3058
  next: { verb: 'open the run report of', command: (id) => `sideby sessions open-run ${id}` },
3052
3059
  onListed: listedProblems(a, io),
3053
3060
  });
@@ -3055,9 +3062,17 @@ async function sessionsOpenRun(a, args, io, runtime) {
3055
3062
  const r = await openRunBoard(rt, s.sessionId);
3056
3063
  const board = tildify(r.board, rt.paths.home);
3057
3064
  if (a.flags.has('json')) {
3058
- json(io, { opened: true, board, sessionId: s.sessionId, label: s.label });
3065
+ json(io, {
3066
+ opened: true,
3067
+ board,
3068
+ sessionId: s.sessionId,
3069
+ label: s.label,
3070
+ ...(handedOverFrom ? { handedOverFrom } : {}),
3071
+ });
3059
3072
  return 0;
3060
3073
  }
3074
+ if (handedOverFrom)
3075
+ io.out(handedOverLine(handedOverFrom, s.label, 'opening its run report'));
3061
3076
  io.out(`${c.green('✓')} opened the run report of ${c.bold(s.label)}`);
3062
3077
  io.out(c.dim(` ${board}`));
3063
3078
  return 0;
@@ -3074,13 +3089,22 @@ async function sessionsCopy(a, args, io, runtime) {
3074
3089
  const { sessionCopyText } = await import('../core/live-sessions.js');
3075
3090
  const { copyToClipboard } = await import('../core/live-sessions-copy.js');
3076
3091
  const { selectSession } = await import('../core/session-select.js');
3077
- const { session: s } = await selectSession(rt, target, { onListed: listedProblems(a, io) });
3092
+ const { session: s, handedOverFrom } = await selectSession(rt, target, { onListed: listedProblems(a, io) });
3078
3093
  const text = sessionCopyText(s, as, lang);
3079
3094
  const program = await copyToClipboard(text, rt.env);
3080
3095
  if (a.flags.has('json')) {
3081
- json(io, { copied: program !== null, as, text, sessionId: s.sessionId, label: s.label });
3096
+ json(io, {
3097
+ copied: program !== null,
3098
+ as,
3099
+ text,
3100
+ sessionId: s.sessionId,
3101
+ label: s.label,
3102
+ ...(handedOverFrom ? { handedOverFrom } : {}),
3103
+ });
3082
3104
  return 0;
3083
3105
  }
3106
+ if (handedOverFrom)
3107
+ io.out(handedOverLine(handedOverFrom, s.label, 'copying that one'));
3084
3108
  const what = as === 'reference' ? 'a reference to' : as === 'id' ? 'the id of' : 'the resume command of';
3085
3109
  if (program) {
3086
3110
  io.out(`${c.green('✓')} copied ${what} ${c.bold(s.label)}; paste it into the other AI`);
@@ -3443,6 +3467,8 @@ export async function cmdSend(a, io) {
3443
3467
  return 0;
3444
3468
  }
3445
3469
  const home = rt.paths.home;
3470
+ if (r.handedOverFrom)
3471
+ io.out(handedOverLine(r.handedOverFrom, r.to, 'sending there'));
3446
3472
  if (r.status === 'delivered') {
3447
3473
  io.out(`${c.green('✓')} delivered to ${c.bold(r.to)} (message ${r.id})`);
3448
3474
  if (r.note)
@@ -436,6 +436,9 @@ const MessageReceipt = Type.Object({
436
436
  description: 'true while a delivered Message waits for the user to approve it in the target terminal (ADR-0045); dropped once it is read, and after 6 minutes unread the status becomes paste-needed.',
437
437
  })),
438
438
  sentAt: Str,
439
+ handedOverFrom: Type.Optional(Type.String({
440
+ description: 'The session id that was named, when an Auto Handoff chain led from it to this target (ADR-0057).',
441
+ })),
439
442
  });
440
443
  const IndexState = Type.Union(['building', 'ready', 'off', 'unavailable'].map((k) => Type.Literal(k)), {
441
444
  description: '`building`: the History Index is still reading files (what is built answers already); `off`: config `history.index` is false or the index file could not be opened, so only titles and folders are searched; `unavailable`: this Node has no `node:sqlite`.',
@@ -906,6 +909,9 @@ export const OUTPUT_SCHEMAS = {
906
909
  }),
907
910
  family: Str,
908
911
  sessionId: Type.String({ description: "The host's own session id." }),
912
+ handedOverFrom: Type.Optional(Type.Array(Str, {
913
+ description: "When an Auto Handoff chain led to this session: the earlier hops' session ids, oldest first (ADR-0057).",
914
+ })),
909
915
  title: Type.String({
910
916
  description: "The host's own title for the session, or its working directory name when the host gives none; may be empty.",
911
917
  }),
@@ -963,6 +969,9 @@ export const OUTPUT_SCHEMAS = {
963
969
  board: Type.String({ description: 'The Run Board file opened, with the home folder as ~.' }),
964
970
  sessionId: Str,
965
971
  label: Type.String({ description: 'The Session Label of the session whose run report was opened.' }),
972
+ handedOverFrom: Type.Optional(Type.String({
973
+ description: 'The session id that was named, when an Auto Handoff chain led from it to this session (ADR-0057).',
974
+ })),
966
975
  }, { title: 'sideby sessions open-run --json' }),
967
976
  'sessions-copy': Type.Object({
968
977
  schemaVersion: Version,
@@ -973,6 +982,9 @@ export const OUTPUT_SCHEMAS = {
973
982
  text: Type.String({ description: 'The text copied, also when it could not be.' }),
974
983
  sessionId: Str,
975
984
  label: Type.String({ description: 'The Session Label of the session copied.' }),
985
+ handedOverFrom: Type.Optional(Type.String({
986
+ description: 'The session id that was named, when an Auto Handoff chain led from it to this session (ADR-0057).',
987
+ })),
976
988
  }, { title: 'sideby sessions copy --json' }),
977
989
  history: Type.Object({
978
990
  schemaVersion: Version,
@@ -30,6 +30,8 @@ export interface LiveSession {
30
30
  reference: string;
31
31
  /** The Run of a local orchestrator the Session works for (spec §3.32 step 2b); set by `withRuns`, not the readers. */
32
32
  run?: SessionRun;
33
+ /** Earlier hops' session ids, oldest first, when an Auto Handoff chain led to this Session (ADR-0057); set by `withHandoffs`. */
34
+ handedOverFrom?: string[];
33
35
  }
34
36
  export interface LiveSessionsResult {
35
37
  sessions: LiveSession[];
@@ -25,6 +25,8 @@ export interface MessageReceipt {
25
25
  /** Delivered, but the target shows it only once the user approves it in its terminal (ADR-0045). */
26
26
  needsApproval?: boolean;
27
27
  sentAt: string;
28
+ /** The session id the sender named, when an Auto Handoff chain led from it to this target (ADR-0057). */
29
+ handedOverFrom?: string;
28
30
  }
29
31
  export interface SendOptions {
30
32
  text: string;
@@ -199,7 +199,7 @@ export async function sendMessage(rt, target, opts, deps = {}) {
199
199
  async function sendOpened(rt, target, opts, deps) {
200
200
  const { text, lang } = opts;
201
201
  const procDeps = deps.procs ?? systemDeps(rt.env);
202
- const { session: to, listed } = await selectSession(rt, target, {
202
+ const { session: to, listed, handedOverFrom, } = await selectSession(rt, target, {
203
203
  next: { verb: 'send to', command: (id) => `sideby send ${id} "<text>"` },
204
204
  deps: procDeps,
205
205
  });
@@ -254,7 +254,7 @@ async function sendOpened(rt, target, opts, deps) {
254
254
  // Without a receipt sideby could not follow it later, so it does not deliver it; the Message file is kept.
255
255
  receipt.status = 'paste-needed';
256
256
  receipt.note = `sideby saved the message file, but could not save its status (${err.code ?? err.message}). Paste the line into the session's tab`;
257
- return publicReceipt(receipt);
257
+ return { ...publicReceipt(receipt), ...(handedOverFrom ? { handedOverFrom } : {}) };
258
258
  }
259
259
  let result;
260
260
  try {
@@ -279,7 +279,7 @@ async function sendOpened(rt, target, opts, deps) {
279
279
  else
280
280
  receipt.note = `${receipt.note ?? 'paste the line into its tab'} (sideby also could not save the message status: ${why})`;
281
281
  }
282
- return publicReceipt(receipt);
282
+ return { ...publicReceipt(receipt), ...(handedOverFrom ? { handedOverFrom } : {}) };
283
283
  }
284
284
  async function deliver(rt, to, acct, r, text, procDeps, deps) {
285
285
  if (to.guessed)
@@ -59,9 +59,14 @@ export declare function stillTheBoard(board: string, check: BoardCheck, id: Boar
59
59
  export declare function byRole(list: readonly RunEntry[]): RunEntry[];
60
60
  /** The Run each of `sessionIds` works for; an empty map when there is no index, no boards folder or no match. */
61
61
  export declare function runsForSessions(env: Env, home: string, sessionIds: readonly string[], uid?: number): Promise<Map<string, SessionRun>>;
62
- /** The same Sessions, each with `run` where the Session Index ties it to a Run. */
62
+ /**
63
+ * The same Sessions, each with `run` where the Session Index ties it to a Run: by its own id, else by the ids it was
64
+ * handed over from, newest first, so a Run Board stays linked after its coordinator moves to another Account. An id
65
+ * whose boards all fail the checks is passed over, as `openRunBoard` passes it over.
66
+ */
63
67
  export declare function withRuns<T extends {
64
68
  sessionId: string;
69
+ handedOverFrom?: readonly string[];
65
70
  }>(env: Env, home: string, sessions: T[], uid?: number): Promise<(T & {
66
71
  run?: SessionRun;
67
72
  })[]>;
@@ -8,6 +8,7 @@ import { basename, dirname, isAbsolute, join } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { openWithDefault } from './edit-settings.js';
10
10
  import { UserError } from './errors.js';
11
+ import { earlierHops, readHandoffChains } from './session-handoffs.js';
11
12
  /** The largest Session Index sideby reads; a bigger one is ignored. */
12
13
  export const INDEX_MAX_BYTES = 256 * 1024;
13
14
  const MAX_TEXT = 120;
@@ -202,26 +203,64 @@ export async function runsForSessions(env, home, sessionIds, uid) {
202
203
  if (!check)
203
204
  return out;
204
205
  for (const id of wanted) {
205
- const [first, ...rest] = await checkedRuns(index.get(id), check);
206
- if (!first)
207
- continue;
208
- const others = rest.map((e) => ({
209
- title: e.title,
210
- ...(e.laneTitle ? { laneTitle: e.laneTitle } : {}),
211
- ...(e.role ? { role: e.role } : {}),
212
- board: e.board,
213
- }));
214
- out.set(id, { ...first, ...(others.length ? { others } : {}) });
206
+ const run = sessionRun(await checkedRuns(index.get(id), check));
207
+ if (run)
208
+ out.set(id, run);
215
209
  }
216
210
  return out;
217
211
  }
218
- /** The same Sessions, each with `run` where the Session Index ties it to a Run. */
212
+ /** The first checked entry as the Session's Run, the rest as its `others`; undefined when none checked out. */
213
+ function sessionRun([first, ...rest]) {
214
+ if (!first)
215
+ return undefined;
216
+ const others = rest.map((e) => ({
217
+ title: e.title,
218
+ ...(e.laneTitle ? { laneTitle: e.laneTitle } : {}),
219
+ ...(e.role ? { role: e.role } : {}),
220
+ board: e.board,
221
+ }));
222
+ return { ...first, ...(others.length ? { others } : {}) };
223
+ }
224
+ /** A Session's own id, then the ids an Auto Handoff chain passed it from, newest first (ADR-0057). */
225
+ const linkIds = (s) => [
226
+ s.sessionId,
227
+ ...[...(s.handedOverFrom ?? [])].reverse(),
228
+ ];
229
+ /**
230
+ * The one rule a Run Link follows, for listing and opening alike: the entries of the first id in `ids` that has an
231
+ * entry whose board checks out, those that check out ordered by role, each with its board's identity at the check.
232
+ */
233
+ async function linkedEntries(index, check, ids) {
234
+ for (const sessionId of ids) {
235
+ const entries = index.get(sessionId);
236
+ if (!entries)
237
+ continue;
238
+ const ok = (await Promise.all(entries.map((e) => inspectEntry(e, check)))).filter((x) => x !== undefined);
239
+ if (!ok.length)
240
+ continue;
241
+ const order = byRole(ok.map((x) => x.entry));
242
+ return order.map((entry) => ok.find((x) => x.entry === entry));
243
+ }
244
+ return [];
245
+ }
246
+ /**
247
+ * The same Sessions, each with `run` where the Session Index ties it to a Run: by its own id, else by the ids it was
248
+ * handed over from, newest first, so a Run Board stays linked after its coordinator moves to another Account. An id
249
+ * whose boards all fail the checks is passed over, as `openRunBoard` passes it over.
250
+ */
219
251
  export async function withRuns(env, home, sessions, uid) {
220
- const runs = await runsForSessions(env, home, sessions.map((s) => s.sessionId), uid);
221
- return sessions.map((s) => {
222
- const run = runs.get(s.sessionId);
252
+ if (!sessions.length)
253
+ return sessions;
254
+ const index = await readSessionIndex(sessionIndexPath(env, home));
255
+ const check = index && sessions.some((s) => linkIds(s).some((id) => index.has(id)))
256
+ ? await boardsCheck(env, home, uid)
257
+ : undefined;
258
+ if (!index || !check)
259
+ return sessions;
260
+ return Promise.all(sessions.map(async (s) => {
261
+ const run = sessionRun((await linkedEntries(index, check, linkIds(s))).map((x) => x.entry));
223
262
  return run ? { ...s, run } : s;
224
- });
263
+ }));
225
264
  }
226
265
  /**
227
266
  * Opens the Run Board of `sessionId` with the system's default program. The path comes only from the Session Index,
@@ -230,15 +269,16 @@ export async function withRuns(env, home, sessions, uid) {
230
269
  */
231
270
  export async function openRunBoard(rt, sessionId) {
232
271
  const gone = () => new UserError('This session is not part of a run any more, or its board file is gone; ask the coordinating AI to show the board again', { code: 'no-run' });
233
- const entries = (await readSessionIndex(sessionIndexPath(rt.env, rt.paths.home)))?.get(sessionId);
234
- const check = entries && (await boardsCheck(rt.env, rt.paths.home));
235
- if (!entries || !check)
272
+ const index = await readSessionIndex(sessionIndexPath(rt.env, rt.paths.home));
273
+ const check = index && (await boardsCheck(rt.env, rt.paths.home));
274
+ if (!index || !check)
236
275
  throw gone();
237
- const ok = (await Promise.all(entries.map((e) => inspectEntry(e, check)))).filter((x) => x !== undefined);
238
- const first = byRole(ok.map((x) => x.entry))[0];
239
- const id = ok.find((x) => x.entry === first)?.id;
240
- if (!first || !id)
276
+ // The same rule as the listing: its own id, then the ids it was handed over from, newest first (ADR-0057).
277
+ const earlier = earlierHops(await readHandoffChains(rt.paths.stateDir), sessionId) ?? [];
278
+ const [picked] = await linkedEntries(index, check, linkIds({ sessionId, handedOverFrom: earlier }));
279
+ if (!picked)
241
280
  throw gone();
281
+ const { entry: first, id } = picked;
242
282
  if (!(await stillTheBoard(first.board, check, id)))
243
283
  throw new UserError('The board file changed while sideby checked it; ask the coordinating AI to show the board again', { code: 'board-changed' });
244
284
  return { board: first.board, command: await openWithDefault(rt, first.board, { text: false }) };
@@ -0,0 +1,22 @@
1
+ /** One hop of a chain: its session, and when the hop started (the time its run id starts with). */
2
+ export interface HandoffHop {
3
+ sessionId: string;
4
+ /** Milliseconds since the epoch, from the run id's base36 time; 0 when it has none. */
5
+ at: number;
6
+ }
7
+ /** The hops of one chain, oldest first. A resumed session handed over again starts a new chain. */
8
+ export type HandoffChain = readonly HandoffHop[];
9
+ /** Every Handoff chain under `<stateDir>/handoffs`, each its hops in run-id order; links are not followed. */
10
+ export declare function readHandoffChains(stateDir: string): Promise<HandoffHop[][]>;
11
+ /** The session ids the task passed through before `sessionId`, oldest first; undefined when no chain led to it. */
12
+ export declare function earlierHops(chains: readonly HandoffChain[], sessionId: string): string[] | undefined;
13
+ /** The same Sessions, each with `handedOverFrom` where a Handoff chain led to it. */
14
+ export declare function withHandoffs<T extends {
15
+ sessionId: string;
16
+ }>(chains: readonly HandoffChain[], sessions: readonly T[]): (T & {
17
+ handedOverFrom?: string[];
18
+ })[];
19
+ /** The full session ids in any chain that `target` names: the id itself, or its first 8 or more characters. */
20
+ export declare function chainIdsMatching(chains: readonly HandoffChain[], target: string): string[];
21
+ /** The sessions the task passed to after `sessionId`, across every chain, the newest hop first. */
22
+ export declare function laterHops(chains: readonly HandoffChain[], sessionId: string): string[];
@@ -0,0 +1,110 @@
1
+ // Which Sessions an Auto Handoff chain passed a task through (spec §3.32 step 2, ADR-0057): each hop of a chain
2
+ // writes `run-<runId>.json` under `<state>/handoffs/<chain>/`, and run ids start with the time, so sorting them sorts
3
+ // the hops. Read-only and best effort: only the `sessionId` of run files is read (never a Brief or another chain
4
+ // file), a file that cannot be read or parsed is skipped, and nothing is written. Imports Node built-ins only.
5
+ import { lstat, readdir, readFile } from 'node:fs/promises';
6
+ import { join } from 'node:path';
7
+ /** A run file bigger than this is not a hop sideby wrote; it is skipped. */
8
+ const RUN_MAX_BYTES = 256 * 1024;
9
+ const RUN_FILE = /^run-.+\.json$/;
10
+ async function names(dir) {
11
+ try {
12
+ return await readdir(dir);
13
+ }
14
+ catch {
15
+ return [];
16
+ }
17
+ }
18
+ async function hopSession(file) {
19
+ try {
20
+ const st = await lstat(file);
21
+ if (!st.isFile() || st.size > RUN_MAX_BYTES)
22
+ return undefined;
23
+ const raw = JSON.parse(await readFile(file, 'utf8'));
24
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
25
+ return undefined;
26
+ const id = raw.sessionId;
27
+ return typeof id === 'string' && id ? id : undefined;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ /** The time a run id starts with (`<base36 ms>-<hex>`, `newId` in handoff-chain.ts); 0 when it has none. */
34
+ function runTime(name) {
35
+ const t = Number.parseInt(name.slice('run-'.length).split('-')[0] ?? '', 36);
36
+ return Number.isFinite(t) ? t : 0;
37
+ }
38
+ /** Every Handoff chain under `<stateDir>/handoffs`, each its hops in run-id order; links are not followed. */
39
+ export async function readHandoffChains(stateDir) {
40
+ const root = join(stateDir, 'handoffs');
41
+ const chains = [];
42
+ for (const name of (await names(root)).sort()) {
43
+ const dir = join(root, name);
44
+ const st = await lstat(dir).catch(() => undefined);
45
+ if (!st?.isDirectory())
46
+ continue;
47
+ const runs = (await names(dir)).filter((n) => RUN_FILE.test(n)).sort();
48
+ const hops = [];
49
+ for (const run of runs) {
50
+ const sessionId = await hopSession(join(dir, run));
51
+ // A session that keeps its hop over two run files (a resumed wait) is one hop.
52
+ if (sessionId && sessionId !== hops[hops.length - 1]?.sessionId)
53
+ hops.push({ sessionId, at: runTime(run) });
54
+ }
55
+ if (hops.length)
56
+ chains.push(hops);
57
+ }
58
+ return chains;
59
+ }
60
+ /**
61
+ * The hops on one side of `sessionId`, following every chain that holds it and, through them, the chains of those
62
+ * hops (a session resumed and handed over again starts a new chain). Each session once, at its latest hop time.
63
+ */
64
+ function reach(chains, sessionId, side) {
65
+ const found = new Map();
66
+ const todo = [sessionId];
67
+ for (let id = todo.pop(); id !== undefined; id = todo.pop())
68
+ for (const chain of chains) {
69
+ const i = chain.map((h) => h.sessionId).lastIndexOf(id);
70
+ if (i === -1)
71
+ continue;
72
+ for (const hop of side === 'before' ? chain.slice(0, i) : chain.slice(i + 1)) {
73
+ if (hop.sessionId === sessionId)
74
+ continue;
75
+ const seen = found.get(hop.sessionId);
76
+ if (seen === undefined)
77
+ todo.push(hop.sessionId);
78
+ if (seen === undefined || hop.at > seen)
79
+ found.set(hop.sessionId, hop.at);
80
+ }
81
+ }
82
+ return [...found].map(([id, at]) => ({ sessionId: id, at }));
83
+ }
84
+ /** The session ids the task passed through before `sessionId`, oldest first; undefined when no chain led to it. */
85
+ export function earlierHops(chains, sessionId) {
86
+ const hops = reach(chains, sessionId, 'before').sort((a, b) => a.at - b.at);
87
+ return hops.length ? hops.map((h) => h.sessionId) : undefined;
88
+ }
89
+ /** The same Sessions, each with `handedOverFrom` where a Handoff chain led to it. */
90
+ export function withHandoffs(chains, sessions) {
91
+ return sessions.map((s) => {
92
+ const from = earlierHops(chains, s.sessionId);
93
+ return from ? { ...s, handedOverFrom: from } : s;
94
+ });
95
+ }
96
+ /** The full session ids in any chain that `target` names: the id itself, or its first 8 or more characters. */
97
+ export function chainIdsMatching(chains, target) {
98
+ const out = new Set();
99
+ for (const chain of chains)
100
+ for (const { sessionId: id } of chain)
101
+ if (id === target || (target.length >= 8 && id.startsWith(target)))
102
+ out.add(id);
103
+ return [...out];
104
+ }
105
+ /** The sessions the task passed to after `sessionId`, across every chain, the newest hop first. */
106
+ export function laterHops(chains, sessionId) {
107
+ return reach(chains, sessionId, 'after')
108
+ .sort((a, b) => b.at - a.at)
109
+ .map((h) => h.sessionId);
110
+ }
@@ -1,11 +1,22 @@
1
1
  import type { Runtime } from '../runtime.ts';
2
2
  import { type LiveSession, type LiveSessionsResult } from './live-sessions.ts';
3
3
  import type { LiveSessionDeps } from './live-sessions-procs.ts';
4
+ import { type HandoffChain } from './session-handoffs.ts';
4
5
  /** How the candidates are offered when a target names several Sessions. */
5
6
  export interface SessionNext {
6
7
  verb: string;
7
8
  command: (id: string) => string;
8
9
  }
10
+ /** The Session picked, and the original id when an Auto Handoff chain led from it to this Session (ADR-0057). */
11
+ export interface PickedSession {
12
+ session: LiveSession;
13
+ handedOverFrom?: string;
14
+ }
15
+ export interface Handoffs {
16
+ chains: readonly HandoffChain[];
17
+ /** The Account label of a session id that no longer runs, when the Host still has its record. */
18
+ accountOf?: (sessionId: string) => string | undefined;
19
+ }
9
20
  /**
10
21
  * The one Session `target` names: a session id (or its first 8 or more characters), else an Account whose single
11
22
  * Live Session it is. Several Sessions, or none, are a UserError that says what to run next.
@@ -15,11 +26,14 @@ export declare function pickSession(target: string, sessions: readonly LiveSessi
15
26
  label: string;
16
27
  } | undefined,
17
28
  /** How the candidates are offered; `sessions copy` when left out. */
18
- next?: SessionNext): LiveSession;
29
+ next?: SessionNext,
30
+ /** The Handoff chains, and the Account label of a session id whose record the Host still has. */
31
+ handoffs?: Handoffs): PickedSession;
19
32
  /**
20
33
  * Lists the Live Sessions and picks the one `target` names, reading `target` as an Account (ref or alias) when it is
21
- * one. `onListed` sees the listing before the pick, so its problems can be shown also when the pick fails; the
22
- * listing is returned too, for callers that look for the sending Session in it.
34
+ * one, and following a Handoff chain when it is a session id that no longer runs (ADR-0057). `onListed` sees the
35
+ * listing before the pick, so its problems can be shown also when the pick fails; the listing is returned too, for
36
+ * callers that look for the sending Session in it. Its Sessions carry `handedOverFrom` where a chain led to them.
23
37
  */
24
38
  export declare function selectSession(rt: Runtime, target: string, opts?: {
25
39
  next?: SessionNext;
@@ -28,4 +42,5 @@ export declare function selectSession(rt: Runtime, target: string, opts?: {
28
42
  }): Promise<{
29
43
  session: LiveSession;
30
44
  listed: LiveSessionsResult;
45
+ handedOverFrom?: string;
31
46
  }>;
@@ -1,20 +1,56 @@
1
1
  import { UserError } from './errors.js';
2
- import { listLiveSessions, shortId } from './live-sessions.js';
2
+ import { accountLabels, listLiveSessions, shortId, } from './live-sessions.js';
3
+ import { chainIdsMatching, laterHops, readHandoffChains, withHandoffs, } from './session-handoffs.js';
3
4
  const COPY = { verb: 'copy', command: (id) => `sideby sessions copy ${id}` };
5
+ /** The one session id of a Handoff chain `target` names, when it names exactly one and a later hop exists. */
6
+ function handedOverId(target, chains, next) {
7
+ const ids = chainIdsMatching(chains, target);
8
+ if (ids.length > 1) {
9
+ const rows = ids.map((id) => ` ${next.command(id)}`).join('\n');
10
+ throw new UserError(`${target} matches ${ids.length} sessions that were handed over; ${next.verb} one by its full id:\n${rows}`, { code: 'several-sessions' });
11
+ }
12
+ const id = ids[0];
13
+ return id && laterHops(chains, id).length ? id : undefined;
14
+ }
15
+ /**
16
+ * Follows a session id an Auto Handoff chain passed on: the newest later hop that is a Live Session. Undefined when
17
+ * the id is in no chain or is its last hop; a UserError naming the last hop when no later hop still runs.
18
+ */
19
+ function followHandoff(target, sessions, next, handoffs) {
20
+ const from = handedOverId(target, handoffs.chains, next);
21
+ if (!from)
22
+ return undefined;
23
+ const later = laterHops(handoffs.chains, from);
24
+ for (const id of later) {
25
+ const live = sessions.find((s) => s.sessionId === id);
26
+ if (live)
27
+ return { session: live, handedOverFrom: from };
28
+ }
29
+ const last = later[0];
30
+ const account = handoffs.accountOf?.(last);
31
+ throw new UserError(`${shortId(from)} was handed over to session ${last}${account ? ` of ${account}` : ''}, which is not running now; run \`sideby sessions\` to see the running sessions`, { code: 'no-session' });
32
+ }
4
33
  /**
5
34
  * The one Session `target` names: a session id (or its first 8 or more characters), else an Account whose single
6
35
  * Live Session it is. Several Sessions, or none, are a UserError that says what to run next.
7
36
  */
8
37
  export function pickSession(target, sessions, account,
9
38
  /** How the candidates are offered; `sessions copy` when left out. */
10
- next = COPY) {
39
+ next = COPY,
40
+ /** The Handoff chains, and the Account label of a session id whose record the Host still has. */
41
+ handoffs = { chains: [] }) {
11
42
  const byId = sessions.filter((s) => s.sessionId === target || (target.length >= 8 && s.sessionId.startsWith(target)));
12
43
  if (byId.length === 1)
13
- return byId[0];
44
+ return { session: byId[0] };
14
45
  const list = byId.length ? byId : account ? sessions.filter((s) => s.account === account.ref) : [];
15
46
  if (list.length === 1)
16
- return list[0];
47
+ return { session: list[0] };
17
48
  if (!list.length) {
49
+ if (!account) {
50
+ const followed = followHandoff(target, sessions, next, handoffs);
51
+ if (followed)
52
+ return followed;
53
+ }
18
54
  if (account)
19
55
  throw new UserError(`${account.label} has no running session now; start one with \`sideby run ${account.label}\`, or run \`sideby sessions\` to see the others`, { code: 'no-session' });
20
56
  throw new UserError(`no running session or account named ${target}; run \`sideby sessions\` to see the running sessions`, { code: 'no-session' });
@@ -27,11 +63,14 @@ next = COPY) {
27
63
  }
28
64
  /**
29
65
  * Lists the Live Sessions and picks the one `target` names, reading `target` as an Account (ref or alias) when it is
30
- * one. `onListed` sees the listing before the pick, so its problems can be shown also when the pick fails; the
31
- * listing is returned too, for callers that look for the sending Session in it.
66
+ * one, and following a Handoff chain when it is a session id that no longer runs (ADR-0057). `onListed` sees the
67
+ * listing before the pick, so its problems can be shown also when the pick fails; the listing is returned too, for
68
+ * callers that look for the sending Session in it. Its Sessions carry `handedOverFrom` where a chain led to them.
32
69
  */
33
70
  export async function selectSession(rt, target, opts = {}) {
34
- const listed = await listLiveSessions(rt, {}, opts.deps);
71
+ const raw = await listLiveSessions(rt, {}, opts.deps);
72
+ const chains = await readHandoffChains(rt.paths.stateDir);
73
+ const listed = { ...raw, sessions: withHandoffs(chains, raw.sessions) };
35
74
  opts.onListed?.(listed);
36
75
  let account;
37
76
  try {
@@ -40,5 +79,40 @@ export async function selectSession(rt, target, opts = {}) {
40
79
  catch {
41
80
  // not an Account: a session id
42
81
  }
43
- return { session: pickSession(target, listed.sessions, account, opts.next), listed };
82
+ const handoffs = { chains };
83
+ if (!account) {
84
+ // Only when the pick would end at a chain whose later hops all ended: which Account still has the last one.
85
+ const last = endedLastHop(target, listed.sessions, chains);
86
+ if (last) {
87
+ const label = await recordAccount(rt, last);
88
+ handoffs.accountOf = (id) => (id === last ? label : undefined);
89
+ }
90
+ }
91
+ const picked = pickSession(target, listed.sessions, account, opts.next, handoffs);
92
+ return { ...picked, listed };
93
+ }
94
+ /** The last hop of the chain `target` names, when neither `target` nor any later hop is a Live Session. */
95
+ function endedLastHop(target, sessions, chains) {
96
+ if (sessions.some((s) => s.sessionId === target || (target.length >= 8 && s.sessionId.startsWith(target))))
97
+ return undefined;
98
+ const ids = chainIdsMatching(chains, target);
99
+ if (ids.length !== 1)
100
+ return undefined;
101
+ const later = laterHops(chains, ids[0]);
102
+ if (!later.length || later.some((id) => sessions.some((s) => s.sessionId === id)))
103
+ return undefined;
104
+ return later[0];
105
+ }
106
+ /** The label of the Account whose Host last wrote (else last started) session `id`; undefined when none did. */
107
+ async function recordAccount(rt, id) {
108
+ const accounts = await rt.accounts();
109
+ let best;
110
+ for (const a of accounts) {
111
+ const family = rt.families.get(a.family);
112
+ const at = (await family?.sessionWrittenAt?.(a, id).catch(() => undefined)) ??
113
+ (await family?.sessionStartedAt?.(a, id).catch(() => undefined));
114
+ if (at !== undefined && (!best || at > best.at))
115
+ best = { ref: a.ref, at };
116
+ }
117
+ return best && (accountLabels(rt, accounts).get(best.ref) ?? best.ref);
44
118
  }
@@ -25,6 +25,7 @@ import { tildify } from '../core/paths.js';
25
25
  import { remoteControlTodo } from '../core/remote-control.js';
26
26
  import { openRunBoard, withRuns } from '../core/run-link.js';
27
27
  import { SECRET_VAR_NAME, secretVarFor, setSecret } from '../core/secret-file.js';
28
+ import { readHandoffChains, withHandoffs } from '../core/session-handoffs.js';
28
29
  import { SKILL_INSTALL } from '../core/skill-check.js';
29
30
  import { launchArgs, TERMINALS } from '../core/terminal.js';
30
31
  import { checkThemeData, listThemes, NO_THEME, previewColors, removeThemeFile, resolveColors, saveThemeFile, undoTheme, useTheme, } from '../core/themes.js';
@@ -1330,7 +1331,8 @@ export function createPanelHandler(opts) {
1330
1331
  const home = rt.paths.home;
1331
1332
  // The Run each Session works for, only where the Session Index and its board file check out (ADR-0041).
1332
1333
  const [sessions, tabs] = await Promise.all([
1333
- withRuns(rt.env, home, listed.sessions),
1334
+ // A Session an Auto Handoff chain led to stays linked to its Run under the earlier ids (ADR-0057).
1335
+ readHandoffChains(rt.paths.stateDir).then((chains) => withRuns(rt.env, home, withHandoffs(chains, listed.sessions))),
1334
1336
  orcaTabs(orcaOf(rt), listed.sessions),
1335
1337
  ]);
1336
1338
  const problems = listed.problems;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sideby",
3
- "version": "0.28.3",
3
+ "version": "0.29.0",
4
4
  "description": "Run work, personal and API-key accounts at the same time, without their configs drifting apart.",
5
5
  "license": "MIT",
6
6
  "author": "Adonis0123 (https://github.com/Adonis0123)",
@@ -92,6 +92,10 @@
92
92
  },
93
93
  "sentAt": {
94
94
  "type": "string"
95
+ },
96
+ "handedOverFrom": {
97
+ "type": "string",
98
+ "description": "The session id that was named, when an Auto Handoff chain led from it to this target (ADR-0057)."
95
99
  }
96
100
  }
97
101
  },
package/schemas/send.json CHANGED
@@ -91,6 +91,10 @@
91
91
  },
92
92
  "sentAt": {
93
93
  "type": "string"
94
+ },
95
+ "handedOverFrom": {
96
+ "type": "string",
97
+ "description": "The session id that was named, when an Auto Handoff chain led from it to this target (ADR-0057)."
94
98
  }
95
99
  }
96
100
  },
@@ -46,6 +46,10 @@
46
46
  "type": "string",
47
47
  "description": "The Session Label of the session copied."
48
48
  },
49
+ "handedOverFrom": {
50
+ "type": "string",
51
+ "description": "The session id that was named, when an Auto Handoff chain led from it to this session (ADR-0057)."
52
+ },
49
53
  "_notice": {
50
54
  "type": "object",
51
55
  "properties": {
@@ -30,6 +30,10 @@
30
30
  "type": "string",
31
31
  "description": "The Session Label of the session whose run report was opened."
32
32
  },
33
+ "handedOverFrom": {
34
+ "type": "string",
35
+ "description": "The session id that was named, when an Auto Handoff chain led from it to this session (ADR-0057)."
36
+ },
33
37
  "_notice": {
34
38
  "type": "object",
35
39
  "properties": {
@@ -44,6 +44,13 @@
44
44
  "type": "string",
45
45
  "description": "The host's own session id."
46
46
  },
47
+ "handedOverFrom": {
48
+ "type": "array",
49
+ "items": {
50
+ "type": "string"
51
+ },
52
+ "description": "When an Auto Handoff chain led to this session: the earlier hops' session ids, oldest first (ADR-0057)."
53
+ },
47
54
  "title": {
48
55
  "type": "string",
49
56
  "description": "The host's own title for the session, or its working directory name when the host gives none; may be empty."
@@ -1,8 +1,8 @@
1
1
  ---
2
2
  name: sideby
3
- description: Use when the user runs, or wants to run, several AI coding accounts (Claude Code, Codex, Grok Build, pi) side by side. Covers installing sideby and setting up a new account ("install sideby", "set up another Claude account", "add cc008", "配置一个 cc00x", "再加一个 Codex 账号"), explaining what accounts share and what stays separate ("what do my accounts share?", "这些账号共享了什么"), showing which account a session is ("show [cc001] in the status line", "加上账号标识"), finding a past session of any account ("找一下我上周改登录页的那个会话"), seeing accounts, quota and usage, moving on when one hits its 5-hour or weekly limit, moving the current task to another account ("用 cc008 继续", "交回 cc008"), adding a short command (alias) or a pick command that starts whichever account has the most quota ("加个 cc"), adding an API account from a vendor's docs ("加一个 DeepSeek API 账号"), supporting a new tool, and repairing drifted account directories (skills, hooks, rules or settings not shared, wrong symlinks, credential file permissions). Drives the `sideby` CLI with `--json`; the agent does every step except browser sign-in, filling in secrets and starting interactive sessions, which it hands to the user as one command (inside an Auto Handoff session, `sideby handoff ready --to` moves the task itself).
3
+ description: Use when the user runs, or wants to run, several AI coding accounts (Claude Code, Codex, Grok Build, pi) side by side. Covers installing sideby and setting up a new account ("install sideby", "set up another Claude account", "add cc008", "配置一个 cc00x", "再加一个 Codex 账号"), explaining what accounts share and what stays separate ("what do my accounts share?", "这些账号共享了什么"), showing which account a session is ("show [cc001] in the status line", "加上账号标识"), finding a past session of any account ("找一下我上周改登录页的那个会话"), telling another running session something, in any account ("告诉 cc002 ……", "给跑构建的那个会话发消息"; Claude Code's own SendMessage reaches only sessions of the same account), seeing accounts, quota and usage, moving on when one hits its 5-hour or weekly limit, moving the current task to another account ("用 cc008 继续", "交回 cc008"), adding a short command (alias) or a pick command that starts whichever account has the most quota ("加个 cc"), adding an API account from a vendor's docs ("加一个 DeepSeek API 账号"), supporting a new tool, and repairing drifted account directories (skills, hooks, rules or settings not shared, wrong symlinks, credential file permissions). Drives the `sideby` CLI with `--json`; the agent does every step except browser sign-in, filling in secrets and starting interactive sessions, which it hands to the user as one command (inside an Auto Handoff session, `sideby handoff ready --to` moves the task itself).
4
4
  metadata:
5
- version: "0.28.3"
5
+ version: "0.29.0"
6
6
  requires:
7
7
  bins: [sideby, node]
8
8
  cliHelp: sideby --help
@@ -30,7 +30,7 @@ When you are the other AI and get a Session Reference, read the record it names
30
30
 
31
31
  ## Tell a session something (Messages)
32
32
 
33
- When the user asks you to tell another session something ("告诉 cc002 测试过了,可以发版", "send this screenshot to cc003"), run `sideby send <account|session> "<text>" --json` yourself; add `--image <path>` once per screenshot (PNG, JPEG, GIF or WebP, up to 20 MB); a screenshot alone, without text, is fine. `<account>` works when that account runs one session now; otherwise use the session id or its first 8 characters from `sideby sessions --json`. Write the text the way the user meant it, addressed to the other AI; do not paste your whole conversation, point at files by path.
33
+ When the user asks you to tell another session something ("告诉 cc002 测试过了,可以发版", "send this screenshot to cc003"), run `sideby send <account|session> "<text>" --json` yourself; add `--image <path>` once per screenshot (PNG, JPEG, GIF or WebP, up to 20 MB); a screenshot alone, without text, is fine. `<account>` works when that account runs one session now; otherwise use the session id or its first 8 characters from `sideby sessions --json`. Use `sideby send` also when Claude Code's own `ListAgents` / `SendMessage` do not list the session: they see only sessions of the same account, `sideby send` reaches every account. A session id recorded before an Auto Handoff (in a Run ledger or a Brief) still works: sideby follows the handoff to the session that carries the task now and says so (`handedOverFrom` in `--json`). Never guess a recipient by its folder or repository name; when you cannot tell which session it is, list `sideby sessions --json` and ask. Write the text the way the user meant it, addressed to the other AI; do not paste your whole conversation, point at files by path.
34
34
 
35
35
  sideby keeps the Message first as a file (`message.file`, mode 600, screenshots copied next to it), then:
36
36