sideby 0.33.0 → 0.35.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 (38) hide show
  1. package/dist/build.json +1 -1
  2. package/dist/src/cli/commands.d.ts +2 -0
  3. package/dist/src/cli/commands.js +67 -17
  4. package/dist/src/cli/json-schemas.js +11 -3
  5. package/dist/src/cli/main.js +11 -5
  6. package/dist/src/core/cli-commands.js +2 -2
  7. package/dist/src/core/live-sessions.d.ts +4 -0
  8. package/dist/src/core/live-sessions.js +17 -3
  9. package/dist/src/core/messages.d.ts +9 -0
  10. package/dist/src/core/messages.js +36 -2
  11. package/dist/src/core/session-status.d.ts +55 -0
  12. package/dist/src/core/session-status.js +59 -0
  13. package/dist/src/core/unattended-retry.d.ts +39 -0
  14. package/dist/src/core/unattended-retry.js +107 -0
  15. package/dist/src/core/unattended.d.ts +2 -2
  16. package/dist/src/core/unattended.js +10 -2
  17. package/dist/src/families/claude/deliver.js +6 -2
  18. package/dist/src/families/claude/messaging.d.ts +8 -1
  19. package/dist/src/families/claude/messaging.js +15 -3
  20. package/dist/src/families/messaging.d.ts +6 -0
  21. package/dist/src/handoff/messages.js +1 -1
  22. package/dist/src/panel/i18n.d.ts +13 -0
  23. package/dist/src/panel/i18n.js +35 -9
  24. package/dist/src/panel/page-logic.d.ts +49 -5
  25. package/dist/src/panel/page-logic.js +74 -10
  26. package/dist/src/panel/page-script.js +59 -17
  27. package/dist/src/panel/page-styles.js +11 -0
  28. package/dist/src/unattended/hook.d.ts +4 -0
  29. package/dist/src/unattended/hook.js +86 -2
  30. package/package.json +1 -1
  31. package/schemas/new.json +4 -1
  32. package/schemas/sessions.json +22 -1
  33. package/skills/sideby/SKILL.md +2 -2
  34. package/skills/sideby/references/accounts.md +10 -0
  35. package/skills/sideby/references/ai-tasks.md +1 -1
  36. package/skills/sideby/references/sessions.md +1 -1
  37. package/skills/sideby/references/setup.md +1 -1
  38. package/skills/sideby/references/unattended.md +4 -2
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261031T154831-0045dd"}
1
+ {"id":"20261101T124822-834cc8"}
@@ -57,6 +57,8 @@ export interface NewSuggestion {
57
57
  alias?: string;
58
58
  /** Why the alias the pattern suggests was left out (taken, reserved); the Account is created without it. */
59
59
  aliasProblem?: string;
60
+ /** No short command was suggested, and how to get one (an API Account without `--vendor`, or no prefix to use). */
61
+ aliasHint?: string;
60
62
  }
61
63
  export declare function cmdNew(a: ParsedArgs, io: Io): Promise<number>;
62
64
  export declare function cmdRun(a: ParsedArgs, io: Io, command: 'run' | 'login'): Promise<number>;
@@ -27,7 +27,7 @@ import { SEARCH_CATALOG, searchCatalog } from '../core/search-catalog.js';
27
27
  import { SHELLS } from '../core/shell-init.js';
28
28
  import { clockText, daysText } from '../core/unattended-state.js';
29
29
  import { MODEL_NAME } from '../families/shared/model-args.js';
30
- import { AI_TASK_KINDS, hiddenIn, inDisplayOrder, pinnedIn, resetWhen, suggestAlias, suggestName, withPinned, } from '../panel/page-logic.js';
30
+ import { AI_TASK_KINDS, hiddenIn, inDisplayOrder, pinnedIn, resetWhen, suggestAlias, suggestName, vendorAlias, withPinned, } from '../panel/page-logic.js';
31
31
  import { createRuntime, UnknownFamilyError } from '../runtime.js';
32
32
  import { UsageError } from './args.js';
33
33
  import { c, clock, compactNumber, quotaText, table, truncate, tuningLines, usageText } from './format.js';
@@ -422,22 +422,44 @@ export async function cmdList(a, io) {
422
422
  return 0;
423
423
  }
424
424
  /**
425
- * `new --next`: the next name of a Family, and a short command following the pattern of its existing aliases,
426
- * from the same helpers the Panel uses (spec §3.16).
425
+ * `new --next` and `new --vendor`: the name (the next one of the Family with `--next`), and a short command from the
426
+ * same helpers the Panel uses (spec §3.16). A Subscription Account follows the pattern of the Family's aliases
427
+ * (`cc008`); an API Account is named after its Vendor (`cc-ds`) and never gets a numbered one.
427
428
  */
428
- async function suggestNew(rt, family, alias) {
429
+ async function suggestNew(rt, family, opts) {
429
430
  if (!(await rt.familyInfo()).some((f) => f.id === family))
430
431
  throw new UnknownFamilyError(`unknown family "${family}"; run \`sideby families\` to see them`);
431
432
  const all = await rt.accounts();
432
433
  const mine = all.filter((x) => x.family === family);
433
- const name = suggestName(mine.map((x) => x.name));
434
- if (alias !== undefined)
434
+ const name = opts.name ?? suggestName(mine.map((x) => x.name));
435
+ if (opts.alias !== undefined)
435
436
  return { name };
436
437
  const byRef = aliasesByAccount(aliasRefs(rt.config.aliases), all);
437
- const offer = suggestAlias(mine.map((x) => ({ family: x.family, name: x.name, ref: x.ref, aliases: byRef.get(x.ref) ?? [] })), family, name);
438
+ const logic = mine.map((x) => ({
439
+ family: x.family,
440
+ name: x.name,
441
+ ref: x.ref,
442
+ aliases: byRef.get(x.ref) ?? [],
443
+ }));
444
+ const ref = `${family}:${name}`;
445
+ if (opts.api && opts.vendor === undefined) {
446
+ const example = vendorAlias(logic, family, '<slug>');
447
+ return example
448
+ ? {
449
+ name,
450
+ aliasHint: `API accounts get a short command named after their vendor: add \`--vendor <slug>\` for ${example}, or run \`sideby alias add ${example} ${ref}\` later`,
451
+ }
452
+ : { name };
453
+ }
454
+ const offer = opts.api ? vendorAlias(logic, family, opts.vendor ?? '') : suggestAlias(logic, family, name);
438
455
  if (!offer)
439
- return { name };
440
- const problem = rt.aliasProblem(offer, `${family}:${name}`);
456
+ return opts.api
457
+ ? {
458
+ name,
459
+ aliasHint: `your ${family} short commands show no prefix to put before ${opts.vendor}: add one with \`sideby alias add <short> ${ref}\``,
460
+ }
461
+ : { name };
462
+ const problem = rt.aliasProblem(offer, ref);
441
463
  return problem ? { name, aliasProblem: `${offer}: ${problem}` } : { name, alias: offer };
442
464
  }
443
465
  export async function cmdNew(a, io) {
@@ -445,12 +467,23 @@ export async function cmdNew(a, io) {
445
467
  const next = a.flags.has('next');
446
468
  if (!family || (next ? given !== undefined : !given) || a.positionals.length > 2)
447
469
  throw new UsageError(next
448
- ? 'usage: sideby new <family> --next [--api] [--alias <short-command>]; --next picks the name, so leave it out'
449
- : 'usage: sideby new <family> <name> [--api] [--alias <short-command>], or `--next` instead of <name>');
470
+ ? 'usage: sideby new <family> --next [--api [--vendor <slug>]] [--alias <short-command>]; --next picks the name, so leave it out'
471
+ : 'usage: sideby new <family> <name> [--api [--vendor <slug>]] [--alias <short-command>], or `--next` instead of <name>');
450
472
  const givenAlias = a.flags.get('alias');
473
+ const givenVendor = a.flags.get('vendor');
474
+ const vendor = typeof givenVendor === 'string' ? givenVendor.trim() : undefined;
475
+ if (vendor !== undefined && !a.flags.has('api'))
476
+ throw new UsageError('--vendor names the vendor an API account calls; add --api (usage: sideby new <family> --next --api --vendor <slug>)');
477
+ if (vendor === '')
478
+ throw new UsageError('--vendor needs a short name for the vendor, such as ds (DeepSeek)');
451
479
  const rt = await createRuntime();
452
- const suggestion = next
453
- ? await suggestNew(rt, family, typeof givenAlias === 'string' ? givenAlias : undefined)
480
+ const suggestion = next || vendor !== undefined
481
+ ? await suggestNew(rt, family, {
482
+ ...(next ? {} : { name: given }),
483
+ ...(typeof givenAlias === 'string' ? { alias: givenAlias } : {}),
484
+ api: a.flags.has('api'),
485
+ ...(vendor !== undefined ? { vendor } : {}),
486
+ })
454
487
  : undefined;
455
488
  const name = suggestion?.name ?? given;
456
489
  const alias = typeof givenAlias === 'string' ? givenAlias : suggestion?.alias;
@@ -488,6 +521,8 @@ export async function cmdNew(a, io) {
488
521
  io.out(`${c.green('✓')} short command ${c.bold(res.alias.name)} (in a new shell)`);
489
522
  else if (res.alias)
490
523
  io.out(` ${c.red('✗')} ${res.alias.message}`);
524
+ else if (suggestion?.aliasHint)
525
+ io.out(` ${c.dim('·')} no short command yet. ${suggestion.aliasHint[0]?.toUpperCase()}${suggestion.aliasHint.slice(1)}`);
491
526
  printShellInitWrites(io, res.shellInitFiles ?? [], home);
492
527
  io.out('\nNext:');
493
528
  for (const n of res.nextSteps)
@@ -3057,6 +3092,17 @@ const SESSION_STATUS = {
3057
3092
  idle: 'idle',
3058
3093
  unknown: '—',
3059
3094
  };
3095
+ /** What the user does for a Session that needs them, when it is not the Host itself asking (spec §3.32 step 1). */
3096
+ const NEEDS_YOU_FOR = {
3097
+ 'pending-decision': 'a decision',
3098
+ 'message-to-approve': 'approve a message',
3099
+ 'message-to-paste': 'paste a message',
3100
+ };
3101
+ function sessionStatusText(s) {
3102
+ const why = s.reason ? NEEDS_YOU_FOR[s.reason] : undefined;
3103
+ const text = SESSION_STATUS[s.status] ?? SESSION_STATUS.unknown;
3104
+ return s.status === 'needs-you' ? c.yellow(why ? `${text}: ${why}` : text) : text;
3105
+ }
3060
3106
  /** The language of a copied Session Reference: `--lang`, else the user's locale. */
3061
3107
  function copyLang(a, env) {
3062
3108
  const flag = a.flags.get('lang');
@@ -3107,7 +3153,7 @@ export async function cmdSessions(a, io, runtime) {
3107
3153
  const anyRun = sessions.some((s) => s.run);
3108
3154
  const rows = sessions.map((s) => [
3109
3155
  c.bold(sessionLabel(s.accountLabel, truncate(s.title, 40), s.sessionId)),
3110
- s.status === 'needs-you' ? c.yellow(SESSION_STATUS[s.status]) : SESSION_STATUS[s.status],
3156
+ sessionStatusText(s),
3111
3157
  s.cwd ? tildify(s.cwd, home) : '',
3112
3158
  s.startedAt ? clock(s.startedAt, now) : '',
3113
3159
  ...(anyRun
@@ -3126,6 +3172,10 @@ export async function cmdSessions(a, io, runtime) {
3126
3172
  io.out(c.dim(`Run: ${title} ${tildify(board, home)}`));
3127
3173
  if (boards.size)
3128
3174
  io.out(c.dim('Open its run report: sideby sessions open-run <account|session-id>'));
3175
+ if (sessions.some((s) => s.reason === 'pending-decision'))
3176
+ io.out(c.dim('See the decisions waiting for you: sideby unattended pending'));
3177
+ if (sessions.some((s) => s.reason === 'message-to-paste' || s.reason === 'message-to-approve'))
3178
+ io.out(c.dim('See the messages waiting for you, with the line to paste: sideby messages'));
3129
3179
  io.out(c.dim('Copy one for another AI: sideby sessions copy <account|session-id>'));
3130
3180
  return 0;
3131
3181
  }
@@ -4052,12 +4102,12 @@ function unattendedLine(s, now) {
4052
4102
  const at = (iso) => clock2(iso, now);
4053
4103
  const slot = s.slot ? ` · Slot "${s.slot}"` : '';
4054
4104
  if (s.reason === 'slot' || s.reason === 'manual')
4055
- return `${c.green('on')}${s.reason === 'manual' ? ' · turned on by hand' : slot}${s.until ? ` · until ${at(s.until)}` : ' · no end: the Schedule covers every hour'}`;
4105
+ return `${c.green('on')}${s.until ? ` · until ${at(s.until)}` : ' · no end: the Schedule covers every hour'}${s.reason === 'manual' ? ' · turned on by hand' : slot}`;
4056
4106
  if (s.reason === 'session')
4057
4107
  return `${c.green('on')} for this session only (started with --unattended)`;
4058
4108
  if (s.reason === 'paused')
4059
- return `${c.yellow('paused')}${slot}${s.until ? ` · until ${at(s.until)}, then the Schedule goes on` : ' · until you turn it on (`sideby unattended on`)'}`;
4060
- return `${c.dim('off')}${s.next ? ` · next ${at(s.next.at)}${s.next.slot ? ` (${s.next.slot})` : ''}` : ''}`;
4109
+ return `${c.yellow('paused')}${s.until ? ` · back on at ${at(s.until)}` : ' · until you turn it on (`sideby unattended on`)'}${slot}`;
4110
+ return `${c.dim('off')}${s.next ? ` · turns on at ${at(s.next.at)}${s.next.slot ? ` (Slot "${s.next.slot}")` : ''}` : ''}`;
4061
4111
  }
4062
4112
  const clock2 = (iso, now) => clockText(Date.parse(iso), now.getTime());
4063
4113
  function printSchedule(io, schedule) {
@@ -843,8 +843,13 @@ export const OUTPUT_SCHEMAS = {
843
843
  nextSteps: Type.Array(Str),
844
844
  alias: Type.Optional(Type.Object({ name: Str, added: Type.Boolean(), message: Type.Optional(Str) }, { description: 'The `--alias` short command; `added: false` means the Account exists without it.' })),
845
845
  shellInitFiles: Type.Optional(ShellInitFiles),
846
- suggestion: Type.Optional(Type.Object({ name: Str, alias: Type.Optional(Str), aliasProblem: Type.Optional(Str) }, {
847
- description: 'Only with `--next`: the picked name, the short command that follows the existing pattern, or why that short command was left out.',
846
+ suggestion: Type.Optional(Type.Object({
847
+ name: Str,
848
+ alias: Type.Optional(Str),
849
+ aliasProblem: Type.Optional(Str),
850
+ aliasHint: Type.Optional(Str),
851
+ }, {
852
+ description: 'Only with `--next` or `--vendor`: the name, the short command suggested for it (the existing pattern, `cc008`, for a subscription account; the prefix and the vendor, `cc-ds`, for an API account with `--vendor`), why that short command was left out (`aliasProblem`), or, when none was suggested, how to get one (`aliasHint`, such as an API account without `--vendor`).',
848
853
  })),
849
854
  pickCommandOffer: Type.Optional(Type.Object({ name: Str, command: Str, shadows: Type.Optional(Str) }, {
850
855
  description: 'Set once, when this is the Family’s second subscription account and it has no pick command: the command that adds one.',
@@ -1002,8 +1007,11 @@ export const OUTPUT_SCHEMAS = {
1002
1007
  description: 'The Session Label: `<accountLabel> · <title> · <first 8 of sessionId>`.',
1003
1008
  }),
1004
1009
  status: Type.Union(['needs-you', 'busy', 'idle', 'unknown'].map((k) => Type.Literal(k)), {
1005
- description: '`needs-you`: it waits for the user (a permission or a question); `unknown` where the host does not say.',
1010
+ description: "`needs-you`: the user has to act on it (`reason` says why); `busy` and `idle` as the host says; `unknown` where the host does not say. The first matching row of spec §3.32 step 1's status table.",
1006
1011
  }),
1012
+ reason: Type.Optional(Type.Union(['host-waits', 'pending-decision', 'message-to-approve', 'message-to-paste'].map((k) => Type.Literal(k)), {
1013
+ description: 'Only with `needs-you`: the host waits for a permission or an answer; an open Pending Decision names the session (`sideby unattended pending`); a Message to it waits for the user to approve it in its terminal; or a Message to it waits to be pasted (`sideby messages`). New values may be added.',
1014
+ })),
1007
1015
  cwd: Type.Optional(Str),
1008
1016
  pid: Type.Optional(Type.Integer({ description: 'The host process running it.' })),
1009
1017
  startedAt: Type.Optional(Str),
@@ -16,21 +16,25 @@ const COMMAND_HELP = {
16
16
  key: 'sideby key <account> [--var <NAME>] [--json]\nEnter an API key without echo. Run in a terminal or use the Panel key box.',
17
17
  try: 'sideby try <account> [--model <model>] [--yes] [--json]\nSend a short request through the Host. This spends a few tokens. Exit 10 waits for --yes.\n<account> may be a short command; its arguments apply as in sideby run. --model tries another model once.',
18
18
  plugins: 'sideby plugins [--json]\nsideby plugins new <id> [--json]\nsideby plugins check <id|path> [--json]\nPlugins run as you, with your permissions. Only load plugins you trust.',
19
- new: `sideby new <family> <name> [--api] [--alias <short>] [--json]
20
- sideby new <family> --next [--api] [--alias <short>] [--json]
19
+ new: `sideby new <family> <name> [--api [--vendor <slug>]] [--alias <short>] [--json]
20
+ sideby new <family> --next [--api [--vendor <slug>]] [--alias <short>] [--json]
21
21
 
22
22
  Create an account directory (~/.claude-<name>, ~/.codex-<name>, ~/.grok-<name>, ~/.pi-<name>/agent) and link or
23
23
  copy the main account's shared items into it. \`sideby families <family>\` lists them.
24
24
 
25
25
  --next pick the name: the next number after the highest numbered account (001…007 → 008), else work;
26
26
  without --alias, also add a short command that follows your existing ones (cc007 → cc008)
27
- --api API account: also writes an empty proxy.env template (mode 600) for the user to fill in
27
+ --api API account: also writes an empty proxy.env template (mode 600) for the user to fill in;
28
+ it gets no numbered short command
29
+ --vendor <slug> with --api: the vendor it calls, in a few letters (ds, kimi, glm); without --alias, the short
30
+ command is your prefix and the vendor (cc-ds), so it says what it calls
28
31
  --alias <short> add a short command for it to the config (it becomes a shell function)
29
32
 
30
33
  Examples:
31
34
  sideby new claude --next --json # ~/.claude-008 plus cc008 when cc001…cc007 exist
32
35
  sideby new claude work # ~/.claude-work
33
36
  sideby new claude deepseek --api # then the user fills in ~/.claude-deepseek/proxy.env
37
+ sideby new claude --next --api --vendor ds --json # ~/.claude-009 plus cc-ds when cc001… exist
34
38
 
35
39
  Writes: the account directory; the config \`aliases\` and every \`shellInitFile\` when a short command is added.
36
40
  Next: the user signs in with \`sideby login <account>\` (subscription) or fills in proxy.env (API).
@@ -338,7 +342,9 @@ a Claude or Codex session sideby started is not allowed to ask a question: the m
338
342
  where it can be undone, and skips anything hard to undo (deleting, sending, publishing, deploying, paying). Each
339
343
  question it could not ask, and each thing it skipped (\`defer\`), is kept as a Pending Decision for when you are back.
340
344
  In Claude sessions, a permission prompt Claude Code is about to show (a command it wants a person to confirm, also in
341
- a subagent) is answered with "no" and how to do it without one, and kept as a Pending Decision too. Codex's own
345
+ a subagent) is answered with "no" and how to do it without one, and kept as a Pending Decision too. A Claude turn
346
+ that failed for a passing reason (an overloaded server, a dropped connection, a rate limit that is not a used-up
347
+ Quota) is started again after 1, 2, then 4 minutes; after three it is kept as a Pending Decision. Codex's own
342
348
  approval prompts are not covered.
343
349
 
344
350
  When it is on: during a Slot of the Schedule (local days and times; an end before the start is the next day), from
@@ -460,7 +466,7 @@ const COMMANDS = {
460
466
  flags: ['json', 'all', 'slot-end'],
461
467
  valued: ['for', 'until', 'days', 'from', 'to', 'name', 'at'],
462
468
  },
463
- new: { flags: ['api', 'json', 'next'], valued: ['alias'] },
469
+ new: { flags: ['api', 'json', 'next'], valued: ['alias', 'vendor'] },
464
470
  alias: { flags: ['json', 'yes'], valued: ['pick'] },
465
471
  doctor: { flags: ['fix', 'force', 'json'] },
466
472
  quota: { flags: ['json', 'yes', 'refresh'] },
@@ -41,8 +41,8 @@ export const CLI_COMMANDS = [
41
41
  {
42
42
  id: 'new',
43
43
  group: 'accounts',
44
- usage: 'sideby new <family> <name>|--next [--api] [--alias <short>]',
45
- help: 'create an account (families: claude, codex, grok, pi); --next picks the next name and short command (cc008); --alias also adds a short command such as cc008',
44
+ usage: 'sideby new <family> <name>|--next [--api [--vendor <slug>]] [--alias <short>]',
45
+ help: "create an account (families: claude, codex, grok, pi); --next picks the next name and short command (cc008); --api --vendor ds names an API account's short command after its vendor (cc-ds); --alias also adds a short command such as cc008",
46
46
  summary: { en: 'Create an account; --next picks the name for you', zh: '新建账号;--next 自动起名' },
47
47
  example: 'sideby new claude --next',
48
48
  common: 4,
@@ -3,6 +3,7 @@ import type { Runtime } from '../runtime.ts';
3
3
  import type { Account } from '../types.ts';
4
4
  import { type LiveSessionDeps } from './live-sessions-procs.ts';
5
5
  import type { SessionRun } from './run-link.ts';
6
+ import { type NeedsYouReason } from './session-status.ts';
6
7
  export type LiveSessionStatus = 'needs-you' | 'busy' | 'idle' | 'unknown';
7
8
  export interface LiveSession {
8
9
  /** The Account ref, for example `claude:002`. */
@@ -15,7 +16,10 @@ export interface LiveSession {
15
16
  title: string;
16
17
  /** `<accountLabel> · <title> · <first 8 of sessionId>`. */
17
18
  label: string;
19
+ /** The first matching row of the status table (spec §3.32 step 1, `STATUS_RULES` in session-status.ts). */
18
20
  status: LiveSessionStatus;
21
+ /** Why the Session needs the user; only with status `needs-you`. */
22
+ reason?: NeedsYouReason;
19
23
  cwd?: string;
20
24
  pid?: number;
21
25
  startedAt?: string;
@@ -5,6 +5,7 @@ import { liveSessionReader } from '../families/live-sessions.js';
5
5
  import { aliasesByAccount } from './accounts.js';
6
6
  import { aliasArgs, aliasRefs } from './config.js';
7
7
  import { processView, systemDeps } from './live-sessions-procs.js';
8
+ import { MESSAGES_LOOKED_AT, readAttention, withStatus, } from './session-status.js';
8
9
  export const shortId = (id) => id.slice(0, 8);
9
10
  /** `<accountLabel> · <title> · <first 8 of id>`; a Session without a title leaves its part out. */
10
11
  export const sessionLabel = (accountLabel, title, id) => [accountLabel, title, shortId(id)].filter(Boolean).join(' · ');
@@ -87,6 +88,13 @@ export async function listLiveSessions(rt, opts = {}, deps) {
87
88
  const readable = accounts.filter((a) => liveSessionReader(a.family));
88
89
  if (!readable.length)
89
90
  return { sessions: [], problems };
91
+ // What sideby keeps for Sessions (Pending Decisions, Messages) is read beside the Hosts' files. The Messages module
92
+ // reaches back here to pick a target, so it is loaded only when needed.
93
+ const kept = readAttention(rt.readContext().stateDir, async () => (await import('./messages.js')).listMessages(rt, { limit: MESSAGES_LOOKED_AT, persist: false }), problems);
94
+ let keptNow;
95
+ const keptRead = kept.then((k) => {
96
+ keptNow = k;
97
+ });
90
98
  const ctl = new AbortController();
91
99
  const procs = processView(deps ?? systemDeps(rt.env), ctl.signal);
92
100
  const found = [];
@@ -122,13 +130,19 @@ export async function listLiveSessions(rt, opts = {}, deps) {
122
130
  const late = new Promise((resolve) => {
123
131
  timer = setTimeout(() => resolve('late'), deadlineMs);
124
132
  });
125
- if ((await Promise.race([work.then(() => 'done'), late])) === 'late') {
133
+ const done = Promise.all([work, keptRead]).then(() => 'done');
134
+ if ((await Promise.race([done, late])) === 'late') {
126
135
  ctl.abort();
127
- problems.push(`stopped looking after ${deadlineMs / 1000} s; ${[...pending].join(', ') || 'some accounts'} may run sessions that are not shown; run \`sideby sessions\` again`);
136
+ if (pending.size || !keptNow)
137
+ problems.push(pending.size
138
+ ? `stopped looking after ${deadlineMs / 1000} s; ${[...pending].join(', ')} may run sessions that are not shown; run \`sideby sessions\` again`
139
+ : `stopped looking after ${deadlineMs / 1000} s; a session waiting on a decision or a message may not show as needing you; run \`sideby sessions\` again`);
128
140
  }
129
141
  clearTimeout(timer);
142
+ // Past the deadline, what sideby keeps counts only if it was read in time.
143
+ const sessions = withStatus(found, keptNow ?? { decisions: [], receipts: [] });
130
144
  // One unreadable process is met by every Account of its Family: say it once.
131
- return { sessions: sortSessions([...found]), problems: [...new Set(problems)] };
145
+ return { sessions: sortSessions(sessions), problems: [...new Set(problems)] };
132
146
  }
133
147
  export function referenceText(s, lang) {
134
148
  const id = shortId(s.sessionId);
@@ -57,7 +57,16 @@ export interface MessageDeps {
57
57
  timeoutMs?: number;
58
58
  /** How `codex <args>` runs for Codex delivery; resolves to its exit code. */
59
59
  runCodex?: (args: readonly string[], env: NodeJS.ProcessEnv, timeoutMs: number) => Promise<number>;
60
+ /** The wait between delivery tries; a real timer when left out. */
61
+ sleep?: (ms: number) => Promise<void>;
60
62
  }
63
+ /** How many times a delivery whose channel failed in a way that may pass is tried, the first time included. */
64
+ export declare const DELIVERY_TRIES = 3;
65
+ /** The wait before the second try; each next one waits twice as long, at most `DELIVERY_RETRY_MAX_MS`. */
66
+ export declare const DELIVERY_RETRY_FIRST_MS = 2000;
67
+ export declare const DELIVERY_RETRY_MAX_MS = 60000;
68
+ /** The wait before try `n` (2-based: the first try does not wait). */
69
+ export declare const deliveryRetryDelay: (n: number) => number;
61
70
  /** The largest screenshot sideby copies. */
62
71
  export declare const MAX_IMAGE_BYTES: number;
63
72
  /** The image type of a file's first bytes (`png`, `jpg`, `gif`, `webp`), or null. */
@@ -11,6 +11,13 @@ import { UserError } from './errors.js';
11
11
  import { ownedFolder, UnsafeFolderError, writeFileAtomic } from './fs-safe.js';
12
12
  import { processView, systemDeps } from './live-sessions-procs.js';
13
13
  import { selectSession } from './session-select.js';
14
+ /** How many times a delivery whose channel failed in a way that may pass is tried, the first time included. */
15
+ export const DELIVERY_TRIES = 3;
16
+ /** The wait before the second try; each next one waits twice as long, at most `DELIVERY_RETRY_MAX_MS`. */
17
+ export const DELIVERY_RETRY_FIRST_MS = 2_000;
18
+ export const DELIVERY_RETRY_MAX_MS = 60_000;
19
+ /** The wait before try `n` (2-based: the first try does not wait). */
20
+ export const deliveryRetryDelay = (n) => Math.min(DELIVERY_RETRY_MAX_MS, DELIVERY_RETRY_FIRST_MS * 2 ** Math.max(0, n - 2));
14
21
  /** The largest screenshot sideby copies. */
15
22
  export const MAX_IMAGE_BYTES = 20 * 1024 * 1024;
16
23
  const IMAGE_TYPES = [
@@ -253,7 +260,7 @@ async function sendOpened(rt, target, opts, deps) {
253
260
  let result;
254
261
  try {
255
262
  const acct = (await rt.accounts()).find((a) => a.ref === to.account);
256
- result = await deliver(rt, to, acct, receipt, text, reply, procDeps, deps);
263
+ result = await deliverWithRetry(() => deliver(rt, to, acct, receipt, text, reply, procDeps, deps), to, procDeps, deps);
257
264
  }
258
265
  catch (err) {
259
266
  result = {
@@ -261,7 +268,8 @@ async function sendOpened(rt, target, opts, deps) {
261
268
  note: `sideby could not deliver it (${err.code ?? err.message}); paste the line into its tab`,
262
269
  };
263
270
  }
264
- Object.assign(receipt, result);
271
+ const { retry: _retry, ...outcome } = result;
272
+ Object.assign(receipt, outcome);
265
273
  try {
266
274
  await saveReceipt(receipt);
267
275
  }
@@ -275,6 +283,32 @@ async function sendOpened(rt, target, opts, deps) {
275
283
  }
276
284
  return { ...publicReceipt(receipt), ...(handedOverFrom ? { handedOverFrom } : {}) };
277
285
  }
286
+ /**
287
+ * Delivers, and tries again while the channel failed in a way that may pass and took nothing (`retry`, never after a
288
+ * write that may have reached the session, ADR-0065): up to `DELIVERY_TRIES` times, 2 s, then 4 s apart, and not once
289
+ * the target's process is gone. Every try runs every check again (settings, session record, socket owner and folder).
290
+ * The last failure is the result, its note saying how many tries were made.
291
+ */
292
+ async function deliverWithRetry(once, to, procDeps, deps) {
293
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
294
+ let result = await once();
295
+ let tries = 1;
296
+ while (result.retry && result.status === 'paste-needed' && tries < DELIVERY_TRIES) {
297
+ if (to.pid === undefined)
298
+ break;
299
+ const gone = await processView(procDeps)
300
+ .get(to.pid)
301
+ .then((p) => !p, () => false);
302
+ if (gone)
303
+ break;
304
+ tries++;
305
+ await sleep(deliveryRetryDelay(tries));
306
+ result = await once();
307
+ }
308
+ if (result.retry && result.status === 'paste-needed' && tries > 1 && result.note)
309
+ result = { ...result, note: result.note.replace(/\); paste /, `; tried ${tries} times); paste `) };
310
+ return result;
311
+ }
278
312
  async function deliver(rt, to, acct, r, text, reply, procDeps, deps) {
279
313
  if (to.guessed)
280
314
  return {
@@ -0,0 +1,55 @@
1
+ import type { LiveSessionStatus } from './live-sessions.ts';
2
+ import type { MessageReceipt } from './messages.ts';
3
+ import { type PendingDecision } from './unattended-pending.ts';
4
+ /** Why a Session needs the user: the row of `STATUS_RULES` that matched. Set only with status `needs-you`. */
5
+ export type NeedsYouReason = 'host-waits' | 'pending-decision' | 'message-to-approve' | 'message-to-paste';
6
+ /** What the table looks at for one Session. */
7
+ export interface StatusSignals {
8
+ /** What the Host's own files say (a Family reader's status). */
9
+ host: LiveSessionStatus;
10
+ /** Open Pending Decisions kept for this Session. */
11
+ pendingDecisions: number;
12
+ /** Messages delivered to it that it shows only once the user approves them in its terminal (ADR-0045). */
13
+ messagesToApprove: number;
14
+ /** Messages to it that wait for the user to paste them (`paste-needed`) and its record does not show yet. */
15
+ messagesToPaste: number;
16
+ }
17
+ export interface StatusRule {
18
+ status: LiveSessionStatus;
19
+ reason?: NeedsYouReason;
20
+ when: (s: StatusSignals) => boolean;
21
+ }
22
+ /** The table of spec §3.32 step 1, in order; the first row whose `when` holds gives the status. */
23
+ export declare const STATUS_RULES: readonly StatusRule[];
24
+ /** The status the first matching row of `STATUS_RULES` gives, and its reason when it is `needs-you`. */
25
+ export declare function sessionStatus(s: StatusSignals): {
26
+ status: LiveSessionStatus;
27
+ reason?: NeedsYouReason;
28
+ };
29
+ /** The fields of a Live Session the table needs. */
30
+ export interface StatusTarget {
31
+ account: string;
32
+ family: string;
33
+ sessionId: string;
34
+ status: LiveSessionStatus;
35
+ transcript?: string;
36
+ }
37
+ /** What sideby keeps for Sessions, read once per listing. */
38
+ export interface SessionAttention {
39
+ decisions: readonly PendingDecision[];
40
+ receipts: readonly MessageReceipt[];
41
+ }
42
+ /** The signals of one Session, from its Host status and what sideby keeps for it. */
43
+ export declare function signalsOf(s: StatusTarget, kept: SessionAttention): StatusSignals;
44
+ /** Each Session with the status the table gives it; `reason` is set only on `needs-you`, and dropped otherwise. */
45
+ export declare function withStatus<T extends StatusTarget & {
46
+ reason?: NeedsYouReason;
47
+ }>(sessions: readonly T[], kept: SessionAttention): T[];
48
+ /** How many of the newest Messages are looked at: each may read the end of its target's record. */
49
+ export declare const MESSAGES_LOOKED_AT = 50;
50
+ /**
51
+ * Reads what sideby keeps for Sessions: open Pending Decisions and the newest Messages, both without writing (an old
52
+ * done Decision is not deleted, a Message found read is not saved). A store that cannot be read adds a problem line
53
+ * and counts as empty.
54
+ */
55
+ export declare function readAttention(stateDir: string, messages: () => Promise<readonly MessageReceipt[]>, problems: string[]): Promise<SessionAttention>;
@@ -0,0 +1,59 @@
1
+ import { listPendingDecisions } from './unattended-pending.js';
2
+ /** The table of spec §3.32 step 1, in order; the first row whose `when` holds gives the status. */
3
+ export const STATUS_RULES = [
4
+ { status: 'needs-you', reason: 'host-waits', when: (s) => s.host === 'needs-you' },
5
+ { status: 'needs-you', reason: 'pending-decision', when: (s) => s.pendingDecisions > 0 },
6
+ { status: 'needs-you', reason: 'message-to-approve', when: (s) => s.messagesToApprove > 0 },
7
+ { status: 'needs-you', reason: 'message-to-paste', when: (s) => s.messagesToPaste > 0 },
8
+ { status: 'busy', when: (s) => s.host === 'busy' },
9
+ { status: 'idle', when: (s) => s.host === 'idle' },
10
+ { status: 'unknown', when: () => true },
11
+ ];
12
+ /** The status the first matching row of `STATUS_RULES` gives, and its reason when it is `needs-you`. */
13
+ export function sessionStatus(s) {
14
+ const row = STATUS_RULES.find((r) => r.when(s));
15
+ return row.reason ? { status: row.status, reason: row.reason } : { status: row.status };
16
+ }
17
+ /** The signals of one Session, from its Host status and what sideby keeps for it. */
18
+ export function signalsOf(s, kept) {
19
+ const pendingDecisions = kept.decisions.filter((d) => !d.doneAt &&
20
+ d.sessionId === s.sessionId &&
21
+ d.family === s.family &&
22
+ (!d.account || d.account === s.account)).length;
23
+ const mine = kept.receipts.filter((r) => r.toSessionId === s.sessionId && r.toAccount === s.account);
24
+ return {
25
+ host: s.status,
26
+ pendingDecisions,
27
+ messagesToApprove: mine.filter((r) => r.status === 'delivered' && r.needsApproval).length,
28
+ // Only where sideby can see the Session's record: a paste shows there and clears the row; without one it never would.
29
+ messagesToPaste: s.transcript ? mine.filter((r) => r.status === 'paste-needed').length : 0,
30
+ };
31
+ }
32
+ /** Each Session with the status the table gives it; `reason` is set only on `needs-you`, and dropped otherwise. */
33
+ export function withStatus(sessions, kept) {
34
+ return sessions.map((s) => {
35
+ const { reason: _old, ...rest } = s;
36
+ const r = sessionStatus(signalsOf(s, kept));
37
+ return { ...rest, status: r.status, ...(r.reason ? { reason: r.reason } : {}) };
38
+ });
39
+ }
40
+ /** How many of the newest Messages are looked at: each may read the end of its target's record. */
41
+ export const MESSAGES_LOOKED_AT = 50;
42
+ /**
43
+ * Reads what sideby keeps for Sessions: open Pending Decisions and the newest Messages, both without writing (an old
44
+ * done Decision is not deleted, a Message found read is not saved). A store that cannot be read adds a problem line
45
+ * and counts as empty.
46
+ */
47
+ export async function readAttention(stateDir, messages, problems) {
48
+ const [decisions, receipts] = await Promise.all([
49
+ listPendingDecisions(stateDir, { prune: false }).catch((err) => {
50
+ problems.push(`could not read Pending Decisions (${err.code ?? err.message}); sessions waiting on one are not marked; run \`sideby unattended pending\` to see why`);
51
+ return [];
52
+ }),
53
+ messages().catch((err) => {
54
+ problems.push(`could not read sent messages (${err.code ?? err.message}); sessions with a message to paste are not marked; run \`sideby messages\` to see why`);
55
+ return [];
56
+ }),
57
+ ]);
58
+ return { decisions, receipts };
59
+ }
@@ -0,0 +1,39 @@
1
+ /** How many times in a row one session's failed turn is started again before it is left for the user. */
2
+ export declare const RETRY_LIMIT = 3;
3
+ /** The wait before the first retry; each next one waits twice as long (1, 2 and 4 minutes). */
4
+ export declare const RETRY_FIRST_MS = 60000;
5
+ /** A streak older than this starts again from one (a failure the next night is not the fourth of last night's). */
6
+ export declare const RETRY_FRESH_MS: number;
7
+ /** The `timeout` of the hook entry: the longest wait (4 minutes) with room to spare. */
8
+ export declare const RETRY_HOOK_TIMEOUT_S = 600;
9
+ /** The wait before retry `n` (1-based). */
10
+ export declare const retryDelay: (n: number) => number;
11
+ /** The `StopFailure` error types (Claude Code's hook `error` field) that can be a passing failure. */
12
+ export declare const PASSING_ERRORS: readonly string[];
13
+ /**
14
+ * Whether a failed turn's error is a passing one, from the hook input's `error` type and its text
15
+ * (`last_assistant_message`, `error_details`). Checked with Claude Code 2.1.316 against a local server: HTTP 500 and
16
+ * a refused connection come as `server_error`, 429 as `rate_limit`, 408 as `unknown`.
17
+ */
18
+ export declare function passingFailure(error: string | undefined, text: string): boolean;
19
+ /** One session's run of failed turns that were started again. */
20
+ export interface RetryStreak {
21
+ /** How many failures in a row, this one included. */
22
+ count: number;
23
+ /** The wait this failure's hook owns; a later failure or a finished turn replaces or removes it. */
24
+ token: string;
25
+ at: string;
26
+ }
27
+ /** The session's streak, or undefined when there is none or its folder is not safe to read. */
28
+ export declare function readRetryStreak(stateDir: string, sessionId: string): Promise<RetryStreak | undefined>;
29
+ /**
30
+ * Counts one more failure for the session and returns the streak with a new token. A streak older than
31
+ * `RETRY_FRESH_MS` starts again from one. Throws when the folder is not safe to use (the caller then retries nothing).
32
+ */
33
+ export declare function countFailure(stateDir: string, sessionId: string, now: Date): Promise<RetryStreak>;
34
+ /** Ends the session's streak: its turn finished, or it was left for the user. */
35
+ export declare function clearRetryStreak(stateDir: string, sessionId: string): Promise<void>;
36
+ /** What the model reads when its session is woken to go on after a passing failure. */
37
+ export declare function retryMessage(error: string, text: string, count: number, zh: boolean): string;
38
+ /** What the user reads in the morning when the retries ran out: kept as a Pending Decision. */
39
+ export declare function retryGaveUpText(error: string, text: string): string;