sideby 0.39.0 → 0.40.1

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 (41) hide show
  1. package/README.md +2 -2
  2. package/dist/build.json +1 -1
  3. package/dist/src/cli/commands.js +34 -3
  4. package/dist/src/cli/json-schemas.js +9 -2
  5. package/dist/src/cli/main.js +10 -2
  6. package/dist/src/core/cli-commands.js +12 -0
  7. package/dist/src/core/config.d.ts +1 -0
  8. package/dist/src/core/config.js +3 -0
  9. package/dist/src/core/handoff-run.js +192 -175
  10. package/dist/src/core/progress-state.d.ts +21 -7
  11. package/dist/src/core/progress-state.js +32 -8
  12. package/dist/src/core/search-catalog.js +18 -0
  13. package/dist/src/core/session-hooks.d.ts +7 -0
  14. package/dist/src/core/session-hooks.js +27 -0
  15. package/dist/src/core/unattended-pending.d.ts +14 -2
  16. package/dist/src/core/unattended-pending.js +27 -3
  17. package/dist/src/core/unattended-state.d.ts +19 -1
  18. package/dist/src/core/unattended-state.js +31 -5
  19. package/dist/src/core/unattended-wait.d.ts +86 -0
  20. package/dist/src/core/unattended-wait.js +125 -0
  21. package/dist/src/core/unattended.d.ts +19 -0
  22. package/dist/src/core/unattended.js +37 -4
  23. package/dist/src/families/claude/handoff.js +3 -1
  24. package/dist/src/panel/handler.js +16 -1
  25. package/dist/src/panel/i18n.d.ts +9 -0
  26. package/dist/src/panel/i18n.js +26 -8
  27. package/dist/src/panel/page-script.js +51 -2
  28. package/dist/src/panel/page-styles.js +7 -0
  29. package/dist/src/progress/hook.d.ts +7 -0
  30. package/dist/src/progress/hook.js +18 -11
  31. package/dist/src/types.d.ts +5 -0
  32. package/dist/src/unattended/hook.d.ts +21 -6
  33. package/dist/src/unattended/hook.js +261 -19
  34. package/package.json +2 -2
  35. package/schemas/config.json +14 -0
  36. package/schemas/unattended-defer.json +5 -0
  37. package/schemas/unattended-pending.json +5 -0
  38. package/schemas/unattended.json +16 -2
  39. package/skills/sideby/SKILL.md +3 -2
  40. package/skills/sideby/references/progress.md +3 -3
  41. package/skills/sideby/references/unattended.md +16 -2
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  <p align="center">
6
6
  <b>Run work, personal and API-key accounts at the same time, without their configs drifting apart.</b><br>
7
- Each account is its own directory and its own terminal. Skills, hooks and settings stay linked to your main account. Claude Code, Codex, Grok Build and pi.
7
+ Each account is its own directory and its own terminal. Skills, hooks and settings stay linked to your main account. Claude Code, Codex, Grok Build, pi and Antigravity CLI.
8
8
  </p>
9
9
 
10
10
  <p align="center">
@@ -18,7 +18,7 @@
18
18
 
19
19
  ## Quick start
20
20
 
21
- Requires Node 22.18+ and at least one Host CLI (Claude Code, Codex, Grok Build or pi) installed. AI agents: follow the setup steps in [`llms.txt`](llms.txt) ("Set up sideby for a user") instead.
21
+ Requires Node 22.18+ and at least one Host CLI (Claude Code, Codex, Grok Build, pi or Antigravity CLI) installed. AI agents: follow the setup steps in [`llms.txt`](llms.txt) ("Set up sideby for a user") instead.
22
22
 
23
23
  ```sh
24
24
  npm i -g sideby
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261116T070722-38c598"}
1
+ {"id":"20261117T092443-8d4a3b"}
@@ -4700,6 +4700,12 @@ function deferFamily(env) {
4700
4700
  return 'codex';
4701
4701
  return 'unknown';
4702
4702
  }
4703
+ /** What happens to a question nobody answers (Answer Wait, ADR-0077), and how to change it. */
4704
+ function answerWaitLine(minutes) {
4705
+ return minutes === null
4706
+ ? `If nobody answers: questions shown in a Claude session wait for you, however long. ${c.dim('Change it with `sideby unattended wait <minutes>`.')}`
4707
+ : `If nobody answers: after ${minutes} minute${minutes === 1 ? '' : 's'} with Unattended Mode on, the session goes on (the recommended choice; a step needing your OK is skipped). ${c.dim('Change it with `sideby unattended wait <minutes>|off`.')}`;
4708
+ }
4703
4709
  /** One line for where Unattended Mode stands now. */
4704
4710
  function unattendedLine(s, now) {
4705
4711
  const at = (iso) => clock2(iso, now);
@@ -4740,6 +4746,7 @@ function printUnattended(io, s, now, opts = {}) {
4740
4746
  }
4741
4747
  else if (s.on && s.configured)
4742
4748
  io.out(c.dim('Type in a session and it asks you as usual for 30 minutes; the others stay unattended.'));
4749
+ io.out(answerWaitLine(s.answerWait));
4743
4750
  if (!s.configured)
4744
4751
  io.out(c.cyan('Not set up yet: `sideby unattended on` or `sideby unattended schedule preset weeknights` sets it up, and Claude and Codex sessions sideby starts after that are covered.'));
4745
4752
  else
@@ -4763,9 +4770,9 @@ export async function cmdProgress(a, io) {
4763
4770
  const rt = await createRuntime();
4764
4771
  const notes = (every) => [
4765
4772
  every === undefined
4766
- ? `Off. While a Claude session sideby started waits on background work (subagents, long commands), it can tell you what it waits for every few minutes: \`sideby progress on\` (every ${PROGRESS_DEFAULT} minutes; --every <minutes> for another interval).`
4773
+ ? `Off. While a Claude session sideby started waits on background work (subagents, long commands), it can tell you what it waits for: \`sideby progress on\` (every ${PROGRESS_DEFAULT} minutes; --every <minutes> for another interval).`
4767
4774
  : `On: while a Claude session sideby started waits on background work (subagents, long commands), it tells you every ${every} minutes what it waits for, how long, and whether there is new output.`,
4768
- 'Each reminder is one model turn, which reads the whole conversation: it uses quota.',
4775
+ 'Each reminder is one model turn, which reads the whole conversation: it uses quota, and a longer interval uses less.',
4769
4776
  'Turning it on reaches Claude sessions sideby starts from now on; turning it off or changing the interval also reaches running ones. No reminders while a session is unattended.',
4770
4777
  'Codex is not covered: it has no way for sideby to wake a waiting session.',
4771
4778
  ];
@@ -4963,6 +4970,29 @@ export async function cmdUnattended(a, io) {
4963
4970
  }
4964
4971
  throw new UsageError('usage: sideby unattended schedule [add --days … --from … --to … [--name …] | remove <number> | preset weeknights]');
4965
4972
  }
4973
+ if (sub === 'wait') {
4974
+ allow();
4975
+ const usage = 'usage: sideby unattended wait [<minutes>|off]: minutes from 1 to 120 (for example 10), or off to wait for you however long';
4976
+ if (rest.length > 1)
4977
+ throw new UsageError(usage);
4978
+ const raw = rest[0];
4979
+ if (raw === undefined) {
4980
+ const s = await rt.unattendedStatus();
4981
+ if (asJson)
4982
+ json(io, s);
4983
+ else
4984
+ io.out(answerWaitLine(s.answerWait));
4985
+ return 0;
4986
+ }
4987
+ const minutes = raw === 'off' || raw === 'never' ? null : /^\d{1,3}$/.test(raw) ? Number(raw) : Number.NaN;
4988
+ if (minutes !== null && !(minutes >= 1 && minutes <= 120))
4989
+ throw new UsageError(usage);
4990
+ const change = await u.setAnswerWait({ paths, families, minutes, now: now() });
4991
+ const said = minutes === null
4992
+ ? 'Questions shown in Claude sessions now wait for you, however long.'
4993
+ : `Questions shown in Claude sessions now wait ${minutes} minute${minutes === 1 ? '' : 's'}; then, with Unattended Mode on, the session goes on.`;
4994
+ return show(change, change.changed ? said : `It was already set. ${said}`);
4995
+ }
4966
4996
  if (sub === 'pending') {
4967
4997
  const { listPendingDecisions, markPendingDone } = await import('../core/unattended-pending.js');
4968
4998
  const [action, ...args] = rest;
@@ -5001,6 +5031,7 @@ export async function cmdUnattended(a, io) {
5001
5031
  const where = [
5002
5032
  d.account ?? d.family,
5003
5033
  d.kind === 'question' ? 'question' : d.kind === 'permission' ? 'needed your OK' : 'left undone',
5034
+ d.waited ? `no answer for ${d.waited} min` : '',
5004
5035
  d.agentType ? `subagent ${d.agentType}` : '',
5005
5036
  d.doneAt ? 'done' : '',
5006
5037
  ]
@@ -5037,7 +5068,7 @@ export async function cmdUnattended(a, io) {
5037
5068
  io.out(`${c.green('✓')} kept for the user (${decision.id}); they see it with \`sideby unattended pending\`. Go on with the rest of the task.`);
5038
5069
  return 0;
5039
5070
  }
5040
- throw new UsageError('usage: sideby unattended [status|on|off|schedule|pending|defer]; run `sideby unattended --help`');
5071
+ throw new UsageError('usage: sideby unattended [status|on|off|schedule|wait|pending|defer]; run `sideby unattended --help`');
5041
5072
  }
5042
5073
  /**
5043
5074
  * `sideby commands <words>` (spec §3.36, ADR-0054): the Search Catalog the Panel's Command Palette searches, read-only.
@@ -24,6 +24,10 @@ const PendingDecision = Type.Object({
24
24
  text: Type.String({
25
25
  description: 'The question and its options, the tool and what it was to do, or the deferred text; at most 4000 characters.',
26
26
  }),
27
+ waited: Type.Optional(Type.Integer({
28
+ minimum: 1,
29
+ description: 'Minutes the question or permission prompt was on screen with nobody answering before the session went on without an answer (Answer Wait, ADR-0077). Absent when it was never shown.',
30
+ })),
27
31
  doneAt: Type.Optional(Type.String({ description: 'When it was marked done; ISO.' })),
28
32
  });
29
33
  /** The menu bar shortcut (`sideby menubar hotkey`, spec §3.31). */
@@ -1464,6 +1468,9 @@ export const OUTPUT_SCHEMAS = {
1464
1468
  schedule: Type.Array(UnattendedSlotSchema, {
1465
1469
  description: 'Config `unattended.schedule`, numbered from 1.',
1466
1470
  }),
1471
+ answerWait: Type.Union([Type.Integer({ minimum: 1, maximum: 120 }), Type.Null()], {
1472
+ description: 'Answer Wait (ADR-0077): minutes a question or permission prompt shown in a Claude session sideby started waits for a person before, with Unattended Mode on, the session goes on without an answer. null: never. 10 when config `unattended.answerWait` is not set. Change it with `sideby unattended wait <minutes>|off`.',
1473
+ }),
1467
1474
  pending: Type.Integer({ description: 'Open Pending Decisions (`sideby unattended pending`).' }),
1468
1475
  attended: Type.Array(Type.Object({
1469
1476
  sessionId: Str,
@@ -1497,9 +1504,9 @@ export const OUTPUT_SCHEMAS = {
1497
1504
  problem: Type.Optional(Type.String({
1498
1505
  description: 'Why sideby cannot keep its state: `<state>/unattended` is a link, someone else’s, or writable by others. Says what to do.',
1499
1506
  })),
1500
- changed: Type.Optional(Type.Boolean({ description: 'Set by on, off and schedule changes: whether anything changed.' })),
1507
+ changed: Type.Optional(Type.Boolean({ description: 'Set by on, off, schedule and wait changes: whether anything changed.' })),
1501
1508
  undo: Type.Optional(Type.String({ description: 'The command that puts back what the change replaced.' })),
1502
- }, { title: 'sideby unattended [on|off|schedule …] --json' }),
1509
+ }, { title: 'sideby unattended [on|off|schedule …|wait …] --json' }),
1503
1510
  'unattended-pending': Type.Object({
1504
1511
  schemaVersion: Version,
1505
1512
  pending: Type.Array(PendingDecision, {
@@ -345,6 +345,7 @@ no country allowed; 2 malformed command line.`,
345
345
  sideby unattended off [--json]
346
346
  sideby unattended schedule [add --days <days> --from HH:MM --to HH:MM [--name <name>] [--at <n>]] [--json]
347
347
  sideby unattended schedule remove <n> | preset weeknights [--json]
348
+ sideby unattended wait [<minutes>|off] [--json]
348
349
  sideby unattended pending [--all] [--json]
349
350
  sideby unattended pending done <id> | --all [--json]
350
351
  sideby unattended defer "<text>" [--json]
@@ -359,6 +360,12 @@ that failed for a passing reason (an overloaded server, a dropped connection, a
359
360
  Quota) is started again after 1, 2, then 4 minutes; after three it is kept as a Pending Decision. Codex's own
360
361
  approval prompts are not covered.
361
362
 
363
+ If nobody answers (\`wait\`): a question or permission prompt that a Claude session shows while you are there (you
364
+ typed in it within 30 minutes, or Unattended Mode is off) waits for you. Once it has waited 10 minutes (\`wait
365
+ <minutes>\`, 1 to 120) and Unattended Mode is on, the session goes on as above: the recommended choice where it can
366
+ be undone, the prompt answered "no", never "yes". A turn that ended on a question in plain text goes on the same way.
367
+ Each is kept as a Pending Decision with how long it waited. \`wait off\`: questions wait for you however long.
368
+
362
369
  When it is on: during a Slot of the Schedule (local days and times; an end before the start is the next day), from
363
370
  \`on\` until the time you choose (at most 72 hours; without an option, until the current or next Slot ends, else 12
364
371
  hours), or for one session started with \`--unattended\` (\`sideby run <account> --unattended\`, also next, resume,
@@ -375,6 +382,7 @@ Examples:
375
382
  sideby unattended on --until 07:30
376
383
  sideby unattended schedule preset weeknights
377
384
  sideby unattended schedule add --days sat,sun --from 01:00 --to 09:00 --name "Weekend nights"
385
+ sideby unattended wait 30
378
386
  sideby unattended pending
379
387
  sideby unattended defer "deleting the old branch is left for the user"
380
388
  Exit: 0 shown or done; 1 no such Slot or Pending Decision; 2 a time or option it does not take (the message says
@@ -384,11 +392,11 @@ which to use).`,
384
392
  sideby progress off [--json]
385
393
 
386
394
  Progress reminders: while a Claude session sideby started waits on background work (subagents, long commands),
387
- sideby wakes it every few minutes so it tells you in one or two sentences what it waits for, how long, and whether
395
+ sideby wakes it now and then so it tells you in one or two sentences what it waits for, how long, and whether
388
396
  there is new output. Off by default: each reminder is one model turn, which reads the whole conversation, so it uses
389
397
  quota. No reminders while the session is unattended, or while a turn is running.
390
398
 
391
- \`on\` turns them on (every 10 minutes, or --every <minutes>, 1 to 240); \`off\` turns them off. Turning them on reaches
399
+ \`on\` turns them on (every 30 minutes, or --every <minutes>, 1 to 240); \`off\` turns them off. Turning them on reaches
392
400
  Claude sessions sideby starts from now on; turning them off or changing the interval also reaches running ones. Only
393
401
  sideby's config is written, so there is no preview; each change prints its undo. Codex is not covered: it has no
394
402
  way for sideby to wake a waiting session. Grok, pi and sessions started without sideby are not covered either.
@@ -579,6 +579,18 @@ export const CLI_COMMANDS = [
579
579
  example: 'sideby unattended on --until 07:30',
580
580
  feature: 'page.unattended',
581
581
  },
582
+ {
583
+ id: 'unattended.wait',
584
+ group: 'health',
585
+ usage: 'sideby unattended wait [<minutes>|off]',
586
+ help: 'how long a question shown in a Claude session waits for you before, with Unattended Mode on, the session goes on without an answer (1 to 120 minutes, 10 by default; off: wait however long)',
587
+ summary: {
588
+ en: 'Choose how long a question waits for you before the session goes on',
589
+ zh: '设置提问等你多久,之后会话自己继续',
590
+ },
591
+ example: 'sideby unattended wait 30',
592
+ feature: 'action.unattended-wait',
593
+ },
582
594
  // ---------- Panel and app ----------
583
595
  {
584
596
  id: 'ui',
@@ -131,6 +131,7 @@ export declare const ConfigSchema: Type.TObject<{
131
131
  start: Type.TString;
132
132
  end: Type.TString;
133
133
  }>>>;
134
+ answerWait: Type.TOptional<Type.TUnion<[Type.TInteger, Type.TLiteral<false>]>>;
134
135
  }>>;
135
136
  progress: Type.TOptional<Type.TObject<{
136
137
  every: Type.TOptional<Type.TInteger>;
@@ -255,6 +255,9 @@ export const ConfigSchema = Type.Object({
255
255
  schedule: Type.Optional(Type.Array(UnattendedSlotSchema, {
256
256
  description: "Slots that turn Unattended Mode on and off by themselves, in this computer's time zone. Empty by default.",
257
257
  })),
258
+ answerWait: Type.Optional(Type.Union([Type.Integer({ minimum: 1, maximum: 120 }), Type.Literal(false)], {
259
+ description: 'Answer Wait (ADR-0077): how many minutes a question or a permission prompt shown in a Claude session sideby started waits for a person. Once it has waited this long with nobody answering and Unattended Mode is on, the session goes on as Unattended Mode would: the question with the recommended choice where it can be undone, the permission prompt refused (never allowed); each is kept as a Pending Decision. A turn that ended on a question written as text goes on the same way. `false`: never, questions wait for you. Not set: 10 minutes.',
260
+ })),
258
261
  }, {
259
262
  additionalProperties: false,
260
263
  description: 'Unattended Mode (spec §3.37, ADR-0058): while it is on, sessions sideby starts never stop to wait for a person. Present once the feature is used; from then on sideby adds its hook to every Claude and Codex session it starts, so turning it on later covers sessions already running. `sideby config unset unattended` stops adding it.',
@@ -14,7 +14,7 @@ import { briefPath, chainDir, ensureChainDir, FILES, HANDOFF_ENV, newId, readJso
14
14
  import { beforeDashes, runHost, sidebyBinProblem, spawnHost } from './launch.js';
15
15
  import { withoutArgs } from './network.js';
16
16
  import { quotaPressure } from './quota-levels.js';
17
- import { withClaudeSessionHooks } from './session-hooks.js';
17
+ import { withClaudeDirs, withClaudeSessionHooks } from './session-hooks.js';
18
18
  /** How long the Host gets to exit after SIGTERM (time for its SessionEnd hooks) before sideby gives up. */
19
19
  export const EXIT_GRACE_MS = 10_000;
20
20
  const PLAN_REFRESH_MS = 60_000;
@@ -201,188 +201,205 @@ export async function runWithHandoff(rt, ref, userArgs, io, opts = {}) {
201
201
  const own = rt.config.aliases?.[ref];
202
202
  let hop = { ref, args: [...aliasArgs(own), ...userArgs] };
203
203
  let n = 1;
204
- for (;;) {
205
- const launch = n === 1 ? firstLaunch : await rt.prepareLaunch(hop.ref, hop.args, 'run', launchOpts);
206
- const account = launch.account;
207
- const h = launch.family.handoff;
208
- if (!h)
209
- return runHost(launch);
210
- const elig = n === 1 ? firstElig : await h.eligibility(withoutNetwork(launch), account, launch.env);
211
- const canStart = h.starts.length > 0 && elig.start && HOOK_FAMILIES.includes(account.family);
212
- if (!canStart && elig.reason)
213
- io.err(`sideby: ${account.ref} will not hand over: ${elig.reason}`);
214
- const runId = newId();
215
- const brief = briefPath(dir, n, account.ref);
216
- const extra = [...(elig.args ?? [])];
217
- const env = { ...launch.env };
218
- // Claude takes one `--settings`: sideby's session hooks (Network Guard §3.35, Unattended Mode §3.37) go into Auto
219
- // Handoff's file.
220
- const sessionArgs = launch.sessionHookArgs ?? launch.networkArgs ?? [];
221
- const mergeNet = canStart && account.family === 'claude' && sessionArgs.length > 0;
222
- if (canStart) {
223
- const hookArgs = (await h.hookArgs?.(hookCommand(account.family), rt.paths.stateDir)) ?? [];
224
- extra.push(...(mergeNet ? await withClaudeSessionHooks(hookArgs, sessionArgs) : hookArgs));
225
- env[HANDOFF_ENV.run] = runId;
226
- env[HANDOFF_ENV.family] = account.family;
227
- env[HANDOFF_ENV.dir] = dir;
228
- if (account.family === 'codex')
229
- await codexTrustNotice(rt, account, io);
230
- }
231
- extra.push(...(h.dirArgs?.(dir) ?? []));
232
- const args = beforeDashes(mergeNet ? withoutNetwork(launch) : launch.args, extra);
233
- // Later hops carry no `--` of their own (continueArgs drops it), so the prompt goes after a fresh one.
234
- if (hop.prompt)
235
- args.push(...h.promptArgs(hop.prompt));
236
- hops.hops.push({ ref: account.ref, startedAt: new Date().toISOString() });
237
- await writeJsonFile(join(dir, FILES.chain), hops);
238
- if (launch.notice)
239
- io.err(launch.notice);
240
- if (!canStart)
241
- return runHost({ ...launch, args, env });
242
- // Plan writes run one after another, and none lands after this hop is over: a late one would carry this
243
- // run's id into the next hop's plan.json and silence its hook.
244
- let stopped = false;
245
- let pending = Promise.resolve();
246
- const writePlan = () => {
247
- pending = pending.then(async () => {
248
- try {
249
- // Read by the hook once the threshold is crossed, so it answers for that moment (spec §3.17 "选号" 1).
250
- const d = await rt.handoffDecision(account, hops.hops, { ahead: true });
251
- if (stopped)
252
- return;
253
- const plan = {
254
- runId,
255
- brief,
256
- at: new Date().toISOString(),
257
- decision: d.kind,
258
- ...(d.kind === 'pick' ? { pick: d.ref } : {}),
259
- ...(d.kind === 'wait' ? { until: d.until } : {}),
260
- prepareAt: settings.prepareAt,
261
- threshold: settings.threshold,
262
- adaptive: settings.adaptive,
263
- ...(elig.agentBrief === false ? { agentBrief: false } : {}),
264
- acceptsTo: true,
265
- };
266
- await writeJsonFile(join(dir, FILES.plan), plan);
204
+ const chainSettings = join(rt.paths.stateDir, 'handoff', 'chains', `${chain}-claude.json`);
205
+ try {
206
+ for (;;) {
207
+ const launch = n === 1 ? firstLaunch : await rt.prepareLaunch(hop.ref, hop.args, 'run', launchOpts);
208
+ const account = launch.account;
209
+ const h = launch.family.handoff;
210
+ if (!h)
211
+ return await runHost(launch);
212
+ const elig = n === 1 ? firstElig : await h.eligibility(withoutNetwork(launch), account, launch.env);
213
+ const canStart = h.starts.length > 0 && elig.start && HOOK_FAMILIES.includes(account.family);
214
+ if (!canStart && elig.reason)
215
+ io.err(`sideby: ${account.ref} will not hand over: ${elig.reason}`);
216
+ const runId = newId();
217
+ const brief = briefPath(dir, n, account.ref);
218
+ const extra = [...(elig.args ?? [])];
219
+ const env = { ...launch.env };
220
+ // Claude takes one `--settings`: sideby's session hooks (Network Guard §3.35, Unattended Mode §3.37) go into Auto
221
+ // Handoff's file.
222
+ const sessionArgs = launch.sessionHookArgs ?? launch.networkArgs ?? [];
223
+ const mergeNet = canStart && account.family === 'claude' && sessionArgs.length > 0;
224
+ let dirInSettings = false;
225
+ if (canStart) {
226
+ const hookArgs = (await h.hookArgs?.(hookCommand(account.family), rt.paths.stateDir)) ?? [];
227
+ let settingsArgs = mergeNet ? await withClaudeSessionHooks(hookArgs, sessionArgs) : hookArgs;
228
+ // Claude Code 2.1.326 asks to trust a folder given by `--add-dir`; one in sideby's `--settings` file needs no
229
+ // question. The file is the chain's own, outside the chain directory the session may write to.
230
+ if (account.family === 'claude' && settingsArgs.includes('--settings')) {
231
+ settingsArgs = await withClaudeDirs(settingsArgs, [dir], chainSettings);
232
+ dirInSettings = true;
267
233
  }
268
- catch {
269
- // the hook treats a missing plan as "do not interrupt"
234
+ extra.push(...settingsArgs);
235
+ env[HANDOFF_ENV.run] = runId;
236
+ env[HANDOFF_ENV.family] = account.family;
237
+ env[HANDOFF_ENV.dir] = dir;
238
+ if (account.family === 'codex')
239
+ await codexTrustNotice(rt, account, io);
240
+ }
241
+ // Where sideby cannot add to `--settings` (the user gave their own), Claude Code asks to trust the folder.
242
+ if (!dirInSettings)
243
+ extra.push(...(h.dirArgs?.(dir) ?? []));
244
+ const args = beforeDashes(mergeNet ? withoutNetwork(launch) : launch.args, extra);
245
+ // Later hops carry no `--` of their own (continueArgs drops it), so the prompt goes after a fresh one.
246
+ if (hop.prompt)
247
+ args.push(...h.promptArgs(hop.prompt));
248
+ hops.hops.push({ ref: account.ref, startedAt: new Date().toISOString() });
249
+ await writeJsonFile(join(dir, FILES.chain), hops);
250
+ if (launch.notice)
251
+ io.err(launch.notice);
252
+ if (!canStart)
253
+ return await runHost({ ...launch, args, env });
254
+ // Plan writes run one after another, and none lands after this hop is over: a late one would carry this
255
+ // run's id into the next hop's plan.json and silence its hook.
256
+ let stopped = false;
257
+ let pending = Promise.resolve();
258
+ const writePlan = () => {
259
+ pending = pending.then(async () => {
260
+ try {
261
+ // Read by the hook once the threshold is crossed, so it answers for that moment (spec §3.17 "选号" 1).
262
+ const d = await rt.handoffDecision(account, hops.hops, { ahead: true });
263
+ if (stopped)
264
+ return;
265
+ const plan = {
266
+ runId,
267
+ brief,
268
+ at: new Date().toISOString(),
269
+ decision: d.kind,
270
+ ...(d.kind === 'pick' ? { pick: d.ref } : {}),
271
+ ...(d.kind === 'wait' ? { until: d.until } : {}),
272
+ prepareAt: settings.prepareAt,
273
+ threshold: settings.threshold,
274
+ adaptive: settings.adaptive,
275
+ ...(elig.agentBrief === false ? { agentBrief: false } : {}),
276
+ acceptsTo: true,
277
+ };
278
+ await writeJsonFile(join(dir, FILES.plan), plan);
279
+ }
280
+ catch {
281
+ // the hook treats a missing plan as "do not interrupt"
282
+ }
283
+ });
284
+ return pending;
285
+ };
286
+ await writePlan();
287
+ const refresh = setInterval(() => void writePlan(), PLAN_REFRESH_MS);
288
+ const host = spawnHost({ ...launch, args, env });
289
+ const exited = host.exited.then((code) => ({ kind: 'exit', code }));
290
+ // Nothing to move on to (or better to wait): leave the session alone, keep listening (the user may still ask to
291
+ // move on while it waits, ADR-0018), and say why once it ends.
292
+ let kept;
293
+ let outcome;
294
+ for (;;) {
295
+ const watcher = watchReady(dir, runId);
296
+ const got = await Promise.race([
297
+ exited,
298
+ watcher.ready.then((ready) => ({ kind: 'ready', ready })),
299
+ ]);
300
+ watcher.stop();
301
+ if (got.kind === 'exit') {
302
+ outcome = got;
303
+ break;
270
304
  }
271
- });
272
- return pending;
273
- };
274
- await writePlan();
275
- const refresh = setInterval(() => void writePlan(), PLAN_REFRESH_MS);
276
- const host = spawnHost({ ...launch, args, env });
277
- const exited = host.exited.then((code) => ({ kind: 'exit', code }));
278
- // Nothing to move on to (or better to wait): leave the session alone, keep listening (the user may still ask to
279
- // move on while it waits, ADR-0018), and say why once it ends.
280
- let kept;
281
- let outcome;
282
- for (;;) {
283
- const watcher = watchReady(dir, runId);
284
- const got = await Promise.race([
285
- exited,
286
- watcher.ready.then((ready) => ({ kind: 'ready', ready })),
287
- ]);
288
- watcher.stop();
289
- if (got.kind === 'exit') {
290
- outcome = got;
291
- break;
305
+ const d = await decide(rt, account, hops.hops, got.ready.to, got.ready.trigger === 'manual');
306
+ if (d.kind === 'pick') {
307
+ outcome = { ...got, decision: d };
308
+ break;
309
+ }
310
+ await rm(join(dir, FILES.ready), { force: true });
311
+ // A session kept at its limit (or kept to wait) ends no turn until it continues, so a request would never be
312
+ // picked up: `waiting.json` lets `handoff ready` hand over at once (ADR-0018). A `threshold` none is still in
313
+ // its turns and gets none.
314
+ const until = d.kind === 'wait' ? d.until : got.ready.trigger === 'limit' ? limitUntil(got.ready) : undefined;
315
+ if (until)
316
+ await writeJsonFile(join(dir, FILES.waiting), {
317
+ runId,
318
+ until,
319
+ at: new Date().toISOString(),
320
+ trigger: got.ready.trigger,
321
+ });
322
+ kept = d;
323
+ }
324
+ clearInterval(refresh);
325
+ stopped = true;
326
+ await pending;
327
+ await rm(join(dir, FILES.waiting), { force: true });
328
+ if (outcome.kind === 'exit') {
329
+ if (kept)
330
+ io.err(`sideby: ${account.ref} did not hand over: ${explain(kept)}`);
331
+ else
332
+ await noteUnhandedHighQuota(rt, account, hops.hops, settings.threshold, io);
333
+ return outcome.code;
292
334
  }
293
- const d = await decide(rt, account, hops.hops, got.ready.to, got.ready.trigger === 'manual');
294
- if (d.kind === 'pick') {
295
- outcome = { ...got, decision: d };
296
- break;
335
+ const decision = outcome.decision;
336
+ // The session is ready: end the Host, give it time to save, never kill it.
337
+ host.child.kill('SIGTERM');
338
+ const ended = await Promise.race([
339
+ host.exited.then((code) => ({ code })),
340
+ new Promise((r) => setTimeout(() => r(null), grace).unref()),
341
+ ]);
342
+ if (!ended) {
343
+ 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
+ return await host.exited;
297
345
  }
346
+ const ready = outcome.ready;
347
+ const assembled = await h
348
+ .briefFromSession?.(account, {
349
+ ...(ready.sessionId ? { id: ready.sessionId } : {}),
350
+ ...(ready.transcriptPath ? { transcriptPath: ready.transcriptPath } : {}),
351
+ })
352
+ .catch(() => undefined);
353
+ const done = await finishBrief({
354
+ target: brief,
355
+ ready,
356
+ ...(assembled ? { assembled } : {}),
357
+ cwd: process.cwd(),
358
+ });
359
+ const last = hops.hops[hops.hops.length - 1];
360
+ Object.assign(last, {
361
+ trigger: ready.trigger,
362
+ briefSource: done.source,
363
+ brief: done.path,
364
+ ...(ready.window ? { window: ready.window } : {}),
365
+ });
366
+ await writeJsonFile(join(dir, FILES.chain), hops);
298
367
  await rm(join(dir, FILES.ready), { force: true });
299
- // A session kept at its limit (or kept to wait) ends no turn until it continues, so a request would never be
300
- // picked up: `waiting.json` lets `handoff ready` hand over at once (ADR-0018). A `threshold` none is still in
301
- // its turns and gets none.
302
- const until = d.kind === 'wait' ? d.until : got.ready.trigger === 'limit' ? limitUntil(got.ready) : undefined;
303
- if (until)
304
- await writeJsonFile(join(dir, FILES.waiting), {
305
- runId,
306
- until,
307
- at: new Date().toISOString(),
308
- trigger: got.ready.trigger,
309
- });
310
- kept = d;
311
- }
312
- clearInterval(refresh);
313
- stopped = true;
314
- await pending;
315
- await rm(join(dir, FILES.waiting), { force: true });
316
- if (outcome.kind === 'exit') {
317
- if (kept)
318
- io.err(`sideby: ${account.ref} did not hand over: ${explain(kept)}`);
319
- else
320
- await noteUnhandedHighQuota(rt, account, hops.hops, settings.threshold, io);
321
- return outcome.code;
322
- }
323
- const decision = outcome.decision;
324
- // The session is ready: end the Host, give it time to save, never kill it.
325
- host.child.kill('SIGTERM');
326
- const ended = await Promise.race([
327
- host.exited.then((code) => ({ code })),
328
- new Promise((r) => setTimeout(() => r(null), grace).unref()),
329
- ]);
330
- if (!ended) {
331
- 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}\``);
332
- return host.exited;
333
- }
334
- const ready = outcome.ready;
335
- const assembled = await h
336
- .briefFromSession?.(account, {
337
- ...(ready.sessionId ? { id: ready.sessionId } : {}),
338
- ...(ready.transcriptPath ? { transcriptPath: ready.transcriptPath } : {}),
339
- })
340
- .catch(() => undefined);
341
- const done = await finishBrief({
342
- target: brief,
343
- ready,
344
- ...(assembled ? { assembled } : {}),
345
- cwd: process.cwd(),
346
- });
347
- const last = hops.hops[hops.hops.length - 1];
348
- Object.assign(last, {
349
- trigger: ready.trigger,
350
- briefSource: done.source,
351
- brief: done.path,
352
- ...(ready.window ? { window: ready.window } : {}),
353
- });
354
- await writeJsonFile(join(dir, FILES.chain), hops);
355
- await rm(join(dir, FILES.ready), { force: true });
356
- await rm(join(dir, FILES.request), { force: true });
357
- io.err(`sideby: ${account.ref} saved its session and is handing over because ${WHY[ready.trigger]}${ready.window ? ` (${windowText(ready.window)})` : ''}; next is ${decision.ref}${skippedText(decision)}. Brief: ${done.path}`);
358
- if (settings.countdownSeconds > 0 &&
359
- (await countdown(io, settings.countdownSeconds, decision.ref, account.ref))) {
360
- io.err(`sideby: staying in ${account.ref}`);
361
- if (!ready.sessionId) {
362
- io.err(`sideby: the session id is unknown, so start ${account.ref} yourself; the Brief is at ${done.path}`);
368
+ await rm(join(dir, FILES.request), { force: true });
369
+ io.err(`sideby: ${account.ref} saved its session and is handing over because ${WHY[ready.trigger]}${ready.window ? ` (${windowText(ready.window)})` : ''}; next is ${decision.ref}${skippedText(decision)}. Brief: ${done.path}`);
370
+ if (settings.countdownSeconds > 0 &&
371
+ (await countdown(io, settings.countdownSeconds, decision.ref, account.ref))) {
372
+ io.err(`sideby: staying in ${account.ref}`);
373
+ if (!ready.sessionId) {
374
+ io.err(`sideby: the session id is unknown, so start ${account.ref} yourself; the Brief is at ${done.path}`);
375
+ return ended.code;
376
+ }
377
+ const backArgs = [...h.continueArgs(hop.args), ...h.resumeArgs(ready.sessionId)];
378
+ const back = await rt.prepareLaunch(account.ref, backArgs, 'run', launchOpts);
379
+ // The same per-Account arguments as before (Grok's leader socket), without sideby's hooks.
380
+ const backElig = await h.eligibility(withoutNetwork(back), account, back.env);
381
+ return await runHost({ ...back, args: beforeDashes(back.args, backElig.args ?? []) });
382
+ }
383
+ let next;
384
+ try {
385
+ next = await rt.resolve(decision.ref);
386
+ }
387
+ catch (err) {
388
+ io.err(`sideby: cannot start ${decision.ref}: ${err.message}; the Brief is at ${done.path}`);
363
389
  return ended.code;
364
390
  }
365
- const backArgs = [...h.continueArgs(hop.args), ...h.resumeArgs(ready.sessionId)];
366
- const back = await rt.prepareLaunch(account.ref, backArgs, 'run', launchOpts);
367
- // The same per-Account arguments as before (Grok's leader socket), without sideby's hooks.
368
- const backElig = await h.eligibility(withoutNetwork(back), account, back.env);
369
- return runHost({ ...back, args: beforeDashes(back.args, backElig.args ?? []) });
370
- }
371
- let next;
372
- try {
373
- next = await rt.resolve(decision.ref);
374
- }
375
- catch (err) {
376
- io.err(`sideby: cannot start ${decision.ref}: ${err.message}; the Brief is at ${done.path}`);
377
- return ended.code;
391
+ io.err(`sideby: handing over from ${account.ref} to ${next.ref}`);
392
+ hop = {
393
+ ref: next.ref,
394
+ args: next.family === account.family ? h.continueArgs(hop.args) : [],
395
+ prompt: firstPrompt(account.ref, done.path, ready.trigger),
396
+ };
397
+ n++;
378
398
  }
379
- io.err(`sideby: handing over from ${account.ref} to ${next.ref}`);
380
- hop = {
381
- ref: next.ref,
382
- args: next.family === account.family ? h.continueArgs(hop.args) : [],
383
- prompt: firstPrompt(account.ref, done.path, ready.trigger),
384
- };
385
- n++;
399
+ }
400
+ finally {
401
+ // Read by Claude Code while a session runs, so it goes only once the chain's last Host is over.
402
+ await rm(chainSettings, { force: true });
386
403
  }
387
404
  }
388
405
  /** After a session ended on its own: when its Quota passed the threshold but nothing could take over, say why. */