sideby 0.34.0 → 0.35.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.
package/dist/build.json CHANGED
@@ -1 +1 @@
1
- {"id":"20261101T024154-fb1cda"}
1
+ {"id":"20261101T165541-3a6da8"}
@@ -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;
@@ -485,9 +518,11 @@ export async function cmdNew(a, io) {
485
518
  for (const e of res.hookErrors)
486
519
  io.err(c.red(` ${e.message}`));
487
520
  if (res.alias?.added)
488
- io.out(`${c.green('✓')} short command ${c.bold(res.alias.name)} (in a new shell)`);
521
+ io.out(`${c.green('✓')} short command ${c.bold(res.alias.name)} (at your next prompt)`);
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)
@@ -2131,21 +2166,29 @@ export async function cmdBrowser(a, io) {
2131
2166
  }
2132
2167
  export async function cmdAlias(a, io) {
2133
2168
  const [sub, alias, target, ...more] = a.positionals;
2134
- const usage = 'usage: sideby alias add <short-command> <account> [-- host args] | sideby alias add <short-command> --pick <family> [--yes] | sideby alias rm <short-command> | sideby alias list';
2169
+ const usage = 'usage: sideby alias add <short-command> <account> [-- host args] | sideby alias add <short-command> --pick <family> [--yes] | sideby alias rename <old> <new> | sideby alias rm <short-command> | sideby alias list';
2135
2170
  const pick = a.flags.get('pick');
2136
2171
  if (sub === 'list' && alias === undefined && pick === undefined)
2137
2172
  return aliasList(a, io);
2138
2173
  const addPick = sub === 'add' && alias !== undefined && typeof pick === 'string' && target === undefined && !a.rest.length;
2139
2174
  const add = sub === 'add' && pick === undefined && alias !== undefined && target !== undefined && more.length === 0;
2140
2175
  const rm = sub === 'rm' && pick === undefined && alias !== undefined && target === undefined && a.rest.length === 0;
2141
- if (!add && !rm && !addPick)
2176
+ const rename = sub === 'rename' &&
2177
+ pick === undefined &&
2178
+ alias !== undefined &&
2179
+ target !== undefined &&
2180
+ !more.length &&
2181
+ !a.rest.length;
2182
+ if (!add && !rm && !addPick && !rename)
2142
2183
  throw new UsageError(usage);
2143
2184
  const rt = await createRuntime();
2144
- const res = addPick
2145
- ? await rt.addPickCommand(alias, pick, { yes: a.flags.has('yes') })
2146
- : add
2147
- ? await rt.addAlias(alias, target, a.rest)
2148
- : await rt.removeAlias(alias);
2185
+ const res = rename
2186
+ ? await rt.renameAlias(alias, target)
2187
+ : addPick
2188
+ ? await rt.addPickCommand(alias, pick, { yes: a.flags.has('yes') })
2189
+ : add
2190
+ ? await rt.addAlias(alias, target, a.rest)
2191
+ : await rt.removeAlias(alias);
2149
2192
  if (a.flags.has('json')) {
2150
2193
  json(io, res);
2151
2194
  return res.status === 'confirm' ? 10 : res.ok ? 0 : 1;
@@ -2165,9 +2208,10 @@ export async function cmdAlias(a, io) {
2165
2208
  : '';
2166
2209
  const what = res.kind === 'pick' ? 'pick command' : 'short command';
2167
2210
  const said = {
2168
- added: `${c.green('✓')} ${what} ${c.bold(res.alias)}${starts} (in a new shell)`,
2211
+ added: `${c.green('✓')} ${what} ${c.bold(res.alias)}${starts} (at your next prompt)`,
2169
2212
  exists: `${c.green('✓')} ${what} ${c.bold(res.alias)}${starts} was already in the config`,
2170
2213
  removed: `${c.green('✓')} removed ${what} ${c.bold(res.alias)}${starts}`,
2214
+ renamed: `${c.green('✓')} renamed ${what} ${res.renamedFrom} to ${c.bold(res.alias)}${starts} (open terminals pick it up at their next prompt)`,
2171
2215
  absent: `${c.dim('·')} no short command ${res.alias} in the config; nothing to remove`,
2172
2216
  };
2173
2217
  io.out(said[res.status]);
@@ -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.',
@@ -860,9 +865,11 @@ export const OUTPUT_SCHEMAS = {
860
865
  Type.Literal('removed'),
861
866
  Type.Literal('absent'),
862
867
  Type.Literal('confirm'),
868
+ Type.Literal('renamed'),
863
869
  ], {
864
- description: '`confirm` (exit 10): the pick command would hide a command on PATH, so nothing was written; run again with `--yes`.',
870
+ description: '`confirm` (exit 10): the pick command would hide a command on PATH, so nothing was written; run again with `--yes`. `renamed` (`alias rename`): `alias` is the new name.',
865
871
  }),
872
+ renamedFrom: Type.Optional(Type.String({ description: 'The old name, for `renamed`.' })),
866
873
  kind: Type.Optional(Type.Union([Type.Literal('account'), Type.Literal('pick')], {
867
874
  description: '`pick` for a Pick Command (`--pick`), `account` for a short command of one Account.',
868
875
  })),
@@ -16,27 +16,32 @@ 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).
37
41
  Exit: 0 done; 1 invalid name or alias, directory exists, or partly failed; 2 malformed command line.`,
38
42
  alias: `sideby alias add <short> <account> [-- host args] [--json]
39
43
  sideby alias add <short> --pick <family> [--yes] [--json]
44
+ sideby alias rename <old> <new> [--json]
40
45
  sideby alias rm <short> [--json]
41
46
  sideby alias list [--json]
42
47
 
@@ -52,10 +57,12 @@ Examples:
52
57
  sideby alias add cc008 claude:008
53
58
  sideby alias add pi-kimi pi:main -- --model kimi-coding/k3
54
59
  sideby alias add cc --pick claude # says first if cc hides a command (exit 10)
60
+ sideby alias rename cc-relay relay # same account and arguments, new name
55
61
  sideby alias rm cc008
56
62
 
57
- Writes: the config \`aliases\` or \`pickCommands\` and every \`shellInitFile\`. New shell functions work in a
58
- new shell, or after eval "$(sideby shell-init zsh)" (put that line in ~/.zshrc once).
63
+ Writes: the config \`aliases\` or \`pickCommands\`, every \`shellInitFile\` and the stamp open terminals watch.
64
+ A shell that loads eval "$(sideby shell-init zsh)" (\`sideby shell-init setup\` adds that line once) picks up
65
+ the change at its next prompt; a shell started before this version needs a new terminal once.
59
66
  Exit: 0 done (also when it already exists or is absent); 1 invalid, reserved or taken; 2 malformed;
60
67
  10 a pick command would hide a command on PATH, run again with --yes.`,
61
68
  login: `sideby login <account>
@@ -462,7 +469,7 @@ const COMMANDS = {
462
469
  flags: ['json', 'all', 'slot-end'],
463
470
  valued: ['for', 'until', 'days', 'from', 'to', 'name', 'at'],
464
471
  },
465
- new: { flags: ['api', 'json', 'next'], valued: ['alias'] },
472
+ new: { flags: ['api', 'json', 'next'], valued: ['alias', 'vendor'] },
466
473
  alias: { flags: ['json', 'yes'], valued: ['pick'] },
467
474
  doctor: { flags: ['fix', 'force', 'json'] },
468
475
  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,
@@ -9,11 +9,25 @@ export interface ResumeRouteFunction {
9
9
  bin: string;
10
10
  selectVar: string;
11
11
  }
12
+ /**
13
+ * A short hash of the functions `shell-init` defines for these inputs. sideby writes it to the Shell Init Stamp
14
+ * whenever the short commands change, and a terminal whose script carries another one reloads (spec §3.13).
15
+ */
16
+ export declare function shellInitGeneration(accounts: readonly Account[], aliases: Readonly<Record<string, unknown>> | undefined, routes?: readonly ResumeRouteFunction[]): string;
17
+ /** Where a terminal looks for the Shell Init Stamp, and which shell it is. */
18
+ export interface ShellInitReload {
19
+ shell: Shell;
20
+ stampFile: string;
21
+ }
12
22
  /**
13
23
  * The script for one shell, ending in a newline: exactly what `sideby shell-init <shell>` prints. zsh and bash
14
- * read the same function syntax, so the shell only names the file it goes to.
24
+ * read the same function syntax; with `reload` the script also carries that shell's reload hook.
15
25
  */
16
- export declare function shellInitScript(accounts: readonly Account[], aliases: Readonly<Record<string, unknown>> | undefined, routes?: readonly ResumeRouteFunction[]): string;
26
+ export declare function shellInitScript(accounts: readonly Account[], aliases: Readonly<Record<string, unknown>> | undefined, routes?: readonly ResumeRouteFunction[], reload?: ShellInitReload): string;
27
+ /** The Shell Init Stamp: one line, the generation of the short commands sideby wrote last. */
28
+ export declare const shellInitStampFile: (stateDir: string) => string;
29
+ /** Writes the Shell Init Stamp atomically (mode 644): the generation every open terminal compares with its own. */
30
+ export declare function writeShellInitStamp(stampFile: string, gen: string): Promise<void>;
17
31
  export interface ShellInitWrite {
18
32
  shell: Shell;
19
33
  /** The configured path, as written in the config (`~/…` kept). */
@@ -1,7 +1,8 @@
1
1
  // The shell functions `sideby shell-init` prints, and the optional files (config `shellInitFile`) sideby keeps
2
2
  // in sync with them whenever it adds an Account or an alias.
3
+ import { createHash } from 'node:crypto';
3
4
  import { mkdir, readFile } from 'node:fs/promises';
4
- import { dirname } from 'node:path';
5
+ import { dirname, join } from 'node:path';
5
6
  import { ALIAS_NAME, aliasProblem, RESERVED_ALIASES } from './config.js';
6
7
  import { realpathOrNull, statOrNull, writeFileAtomic } from './fs-safe.js';
7
8
  import { expandUserPath } from './paths.js';
@@ -26,27 +27,81 @@ function resumeRouteFunction(r) {
26
27
  ` command sideby resume ${quote(r.family)} -- "$@"; return;; esac; done; fi; command ${r.bin} "$@"; }`,
27
28
  ].join('');
28
29
  }
29
- /**
30
- * The script for one shell, ending in a newline: exactly what `sideby shell-init <shell>` prints. zsh and bash
31
- * read the same function syntax, so the shell only names the file it goes to.
32
- */
33
- export function shellInitScript(accounts, aliases, routes = []) {
34
- const lines = [SHELL_INIT_HEADER];
35
- for (const acc of accounts)
36
- lines.push(`sideby-${acc.family}-${acc.name}() { command sideby run ${quote(acc.ref)} -- "$@"; }`);
30
+ /** The function lines `shell-init` defines and their names, without the header or the reload hook. */
31
+ function functionLines(accounts, aliases, routes) {
32
+ const lines = [];
33
+ const names = [];
34
+ for (const acc of accounts) {
35
+ const name = `sideby-${acc.family}-${acc.name}`;
36
+ lines.push(`${name}() { command sideby run ${quote(acc.ref)} -- "$@"; }`);
37
+ names.push(name);
38
+ }
37
39
  // An alias function runs the alias itself, so `sideby run` reads its Account and arguments from the config.
38
40
  // `function name {`: zsh expands a shell alias of the same name in `name() {` and rejects the whole script, so a
39
41
  // user's own `alias cc=…` would leave every function undefined. With this form their alias still wins.
40
42
  for (const alias of Object.keys(aliases ?? {}))
41
- if (!aliasProblem(alias))
43
+ if (!aliasProblem(alias)) {
42
44
  lines.push(`function ${alias} { command sideby run ${quote(alias)} -- "$@"; }`);
45
+ names.push(alias);
46
+ }
43
47
  // An Alias with the Host's name wins: it already starts a chosen Account.
44
48
  for (const r of routes) {
45
49
  const fn = aliases && Object.hasOwn(aliases, r.bin) ? null : resumeRouteFunction(r);
46
- if (fn)
50
+ if (fn) {
47
51
  lines.push(fn);
52
+ names.push(r.bin);
53
+ }
48
54
  }
49
- return `${lines.join('\n')}\n`;
55
+ return { lines, names };
56
+ }
57
+ /**
58
+ * A short hash of the functions `shell-init` defines for these inputs. sideby writes it to the Shell Init Stamp
59
+ * whenever the short commands change, and a terminal whose script carries another one reloads (spec §3.13).
60
+ */
61
+ export function shellInitGeneration(accounts, aliases, routes = []) {
62
+ const { lines } = functionLines(accounts, aliases, routes);
63
+ return createHash('sha256').update(lines.join('\n')).digest('hex').slice(0, 12);
64
+ }
65
+ /**
66
+ * The reload hook: before each prompt the shell reads the stamp with a builtin (no process starts) and, only when it
67
+ * holds a generation this terminal has not loaded, drops the functions it defined and evaluates `sideby shell-init`
68
+ * again. `__sideby_seen` keeps a stamp that matches no script (a config edited by hand) to one reload.
69
+ */
70
+ function reloadHook(r, gen, names) {
71
+ const hook = r.shell === 'zsh'
72
+ ? 'autoload -Uz add-zsh-hook 2>/dev/null && add-zsh-hook precmd __sideby_reload'
73
+ : `case ";\${PROMPT_COMMAND-};" in *";__sideby_reload;"*) ;; *) PROMPT_COMMAND="__sideby_reload\${PROMPT_COMMAND:+;$PROMPT_COMMAND}";; esac`;
74
+ return [
75
+ `__sideby_gen=${quote(gen)}; __sideby_seen=${quote(gen)}; __sideby_fns=${quote(names.join(' '))}`,
76
+ [
77
+ `__sideby_reload() { local g f; { read -r g < ${quote(r.stampFile)}; } 2>/dev/null || return 0;`,
78
+ ` [ -z "$g" ] || [ "$g" = "$__sideby_gen" ] || [ "$g" = "$__sideby_seen" ] && return 0;`,
79
+ ` __sideby_seen=$g; for f in ${r.shell === 'zsh' ? `\${=__sideby_fns}` : '$__sideby_fns'}; do unset -f "$f" 2>/dev/null; done;`,
80
+ ` eval "$(command sideby shell-init ${r.shell} 2>/dev/null)"; __sideby_seen=$g; }`,
81
+ ].join(''),
82
+ hook,
83
+ ];
84
+ }
85
+ /**
86
+ * The script for one shell, ending in a newline: exactly what `sideby shell-init <shell>` prints. zsh and bash
87
+ * read the same function syntax; with `reload` the script also carries that shell's reload hook.
88
+ */
89
+ export function shellInitScript(accounts, aliases, routes = [], reload) {
90
+ const { lines, names } = functionLines(accounts, aliases, routes);
91
+ const out = [SHELL_INIT_HEADER, ...lines];
92
+ if (reload)
93
+ out.push(...reloadHook(reload, shellInitGeneration(accounts, aliases, routes), names));
94
+ return `${out.join('\n')}\n`;
95
+ }
96
+ /** The Shell Init Stamp: one line, the generation of the short commands sideby wrote last. */
97
+ export const shellInitStampFile = (stateDir) => join(stateDir, 'shell-init.stamp');
98
+ /** Writes the Shell Init Stamp atomically (mode 644): the generation every open terminal compares with its own. */
99
+ export async function writeShellInitStamp(stampFile, gen) {
100
+ await mkdir(dirname(stampFile), { recursive: true });
101
+ const current = await readFile(stampFile, 'utf8').catch(() => null);
102
+ if (current === `${gen}\n`)
103
+ return;
104
+ await writeFileAtomic(stampFile, `${gen}\n`, 0o644);
50
105
  }
51
106
  /**
52
107
  * Writes `content` to the configured file atomically (temp file in the same directory, then rename), keeping its
@@ -1311,6 +1311,32 @@ export function createPanelHandler(opts) {
1311
1311
  return rt.removeAlias(name);
1312
1312
  },
1313
1313
  },
1314
+ // An Alias for one Account: add one, or give one a new name (`replaces`); the page names the Account by ref.
1315
+ '/api/alias/set': {
1316
+ async run(body) {
1317
+ const name = optString(body, 'name')?.trim();
1318
+ const account = optString(body, 'account');
1319
+ const replaces = optString(body, 'replaces');
1320
+ if (!name || !account)
1321
+ throw new HttpError(400, 'enter a name and pick an account');
1322
+ const rt = await getRuntime();
1323
+ const args = Array.isArray(body.args)
1324
+ ? body.args.filter((x) => typeof x === 'string')
1325
+ : [];
1326
+ return replaces ? rt.renameAlias(replaces, name) : rt.addAlias(name, account, args);
1327
+ },
1328
+ },
1329
+ '/api/alias/remove': {
1330
+ async run(body) {
1331
+ const name = optString(body, 'name');
1332
+ if (!name)
1333
+ throw new HttpError(400, '"name" is required');
1334
+ const rt = await getRuntime();
1335
+ if (rt.pickCommandFamily(name) !== undefined)
1336
+ throw new HttpError(400, `"${name}" is a pick command`);
1337
+ return rt.removeAlias(name);
1338
+ },
1339
+ },
1314
1340
  // `sideby shell-init setup` (ADR-0036): the page has shown the line and the file; undo takes out only that line.
1315
1341
  '/api/shell-init/setup': {
1316
1342
  async run(body) {
@@ -177,10 +177,13 @@ declare const en: {
177
177
  'tb.family': string;
178
178
  'tb.allFamilies': string;
179
179
  'tb.sort': string;
180
+ 'sort.by': string;
181
+ 'sort.button': string;
180
182
  'sort.pressure': string;
181
183
  'sort.name': string;
182
184
  'sort.recent': string;
183
185
  'sort.manual': string;
186
+ 'sort.notSet': string;
184
187
  'order.handle': string;
185
188
  'order.moveFamily': string;
186
189
  'order.moveAccount': string;
@@ -265,6 +268,7 @@ declare const en: {
265
268
  'group.attentionShow': string;
266
269
  'acct.alias': string;
267
270
  'acct.aliasArgs': string;
271
+ 'acct.titleAlias': string;
268
272
  'acct.api': string;
269
273
  'acct.model': string;
270
274
  'acct.signedOut': string;
@@ -725,6 +729,21 @@ declare const en: {
725
729
  'row.copyRun': string;
726
730
  'row.installFirst': string;
727
731
  'menu.copyAlias': string;
732
+ 'menu.setAlias': string;
733
+ 'al.title': string;
734
+ 'al.intro': string;
735
+ 'al.nameLabel': string;
736
+ 'al.namePh': string;
737
+ 'al.hint': string;
738
+ 'al.copy': string;
739
+ 'al.badName': string;
740
+ 'al.addAnother': string;
741
+ 'al.live': string;
742
+ 'al.added': string;
743
+ 'al.addedSetup': string;
744
+ 'al.renamed': string;
745
+ 'al.renamedSetup': string;
746
+ 'al.removed': string;
728
747
  'menu.copyLogin': string;
729
748
  'menu.copyDir': string;
730
749
  'menu.copyEmail': string;
@@ -1239,6 +1258,12 @@ declare const en: {
1239
1258
  'nf.aliasPh': string;
1240
1259
  'nf.aliasHint': string;
1241
1260
  'nf.aliasSuggested': string;
1261
+ 'nf.aliasVendor': string;
1262
+ 'nf.aliasVendorTip': string;
1263
+ 'nf.vendor': string;
1264
+ 'nf.vendorPh': string;
1265
+ 'nf.vendorHint': string;
1266
+ 'nf.vendorWord': string;
1242
1267
  'nf.aliasBad': string;
1243
1268
  'nf.aliasReserved': string;
1244
1269
  'nf.aliasTaken': string;
@@ -179,16 +179,19 @@ const en = {
179
179
  'tb.family': 'Filter by tool',
180
180
  'tb.allFamilies': 'All tools',
181
181
  'tb.sort': 'Sort accounts',
182
- 'sort.pressure': 'Sort: quota used',
183
- 'sort.name': 'Sort: name',
184
- 'sort.recent': 'Sort: last used',
185
- 'sort.manual': 'Sort: my order',
182
+ 'sort.by': 'Sort by',
183
+ 'sort.button': 'Sort: {choice}',
184
+ 'sort.pressure': 'Quota used',
185
+ 'sort.name': 'Name',
186
+ 'sort.recent': 'Last used',
187
+ 'sort.manual': 'My order',
188
+ 'sort.notSet': 'Not set',
186
189
  'order.handle': 'Drag to move, or use the arrow keys',
187
190
  'order.moveFamily': 'Move {name}',
188
191
  'order.moveAccount': 'Move {name}',
189
192
  'order.position': '{name}: place {n} of {total}',
190
193
  'order.failed': 'Could not save the order: {msg}. It is back as it was.',
191
- 'sort.arrange': 'Arrange order…',
194
+ 'sort.arrange': 'Arrange order and pins…',
192
195
  'set.order': 'Account order, pins and hidden',
193
196
  'set.orderMine': 'Yours',
194
197
  'set.orderDefault': 'Default',
@@ -267,6 +270,7 @@ const en = {
267
270
  'group.attentionShow': 'Show {name}',
268
271
  'acct.alias': 'Alias',
269
272
  'acct.aliasArgs': 'Alias, starts this account with {args}',
273
+ 'acct.titleAlias': '{alias} starts {ref}',
270
274
  'acct.api': 'API',
271
275
  'acct.model': 'Model',
272
276
  'acct.signedOut': 'Signed out',
@@ -727,6 +731,21 @@ const en = {
727
731
  'row.copyRun': 'Copy the start command: {cmd}',
728
732
  'row.installFirst': 'Install {host} first; the start command needs it',
729
733
  'menu.copyAlias': 'Copy alias',
734
+ 'menu.setAlias': 'Set short command…',
735
+ 'al.title': 'Short command for {ref}',
736
+ 'al.intro': 'Type a short command in a terminal and it starts {ref}, with the same sign-in and sessions.',
737
+ 'al.nameLabel': 'Short command',
738
+ 'al.namePh': 'e.g. cc-relay',
739
+ 'al.hint': 'Letters, digits, - and _. It becomes a command in your terminal.',
740
+ 'al.copy': 'Copy',
741
+ 'al.badName': 'Use only letters, digits, - and _, and start with a letter or _.',
742
+ 'al.addAnother': 'Add another',
743
+ 'al.live': 'Open terminals pick up the change at their next prompt (press Enter once); new ones have it right away.',
744
+ 'al.added': 'Added {name}. Press Enter once in an open terminal, then type {name}.',
745
+ 'al.addedSetup': 'Added {name}. Add the line shown in the dialog so your terminals load it.',
746
+ 'al.renamed': 'Renamed {old} to {name}. Press Enter once in an open terminal, then type {name}.',
747
+ 'al.renamedSetup': 'Renamed {old} to {name}. Add the line shown in the dialog so your terminals load it.',
748
+ 'al.removed': 'Removed {name}.',
730
749
  'menu.copyLogin': 'Copy sign-in command',
731
750
  'menu.copyDir': 'Copy folder path',
732
751
  'menu.copyEmail': 'Copy email',
@@ -1241,6 +1260,12 @@ const en = {
1241
1260
  'nf.aliasPh': 'none',
1242
1261
  'nf.aliasHint': 'A shell command that starts this account. Leave it empty for none.',
1243
1262
  'nf.aliasSuggested': 'Follows the short commands of your other {host} accounts.',
1263
+ 'nf.aliasVendor': 'Named after the vendor, so you can tell your API accounts apart.',
1264
+ 'nf.aliasVendorTip': 'Fill in the vendor above to get {example}.',
1265
+ 'nf.vendor': 'Vendor',
1266
+ 'nf.vendorPh': 'ds, kimi, glm…',
1267
+ 'nf.vendorHint': 'Who this key is from, in a few letters. It names the short command.',
1268
+ 'nf.vendorWord': 'vendor',
1244
1269
  'nf.aliasBad': 'Use letters, digits, "_" or "-", starting with a letter or "_".',
1245
1270
  'nf.aliasReserved': '"{alias}" is a shell keyword or builtin. Pick another.',
1246
1271
  'nf.aliasTaken': '{alias} already starts {ref}.',
@@ -1780,16 +1805,19 @@ const zh = {
1780
1805
  'tb.family': '按工具筛选',
1781
1806
  'tb.allFamilies': '全部工具',
1782
1807
  'tb.sort': '账号排序',
1783
- 'sort.pressure': '排序:额度用量',
1784
- 'sort.name': '排序:名称',
1785
- 'sort.recent': '排序:最近使用',
1786
- 'sort.manual': '排序:我的顺序',
1808
+ 'sort.by': '排序方式',
1809
+ 'sort.button': '排序:{choice}',
1810
+ 'sort.pressure': '额度用量',
1811
+ 'sort.name': '名称',
1812
+ 'sort.recent': '最近使用',
1813
+ 'sort.manual': '我的顺序',
1814
+ 'sort.notSet': '未设置',
1787
1815
  'order.handle': '拖动换位置,或用方向键',
1788
1816
  'order.moveFamily': '移动 {name}',
1789
1817
  'order.moveAccount': '移动 {name}',
1790
1818
  'order.position': '{name}:第 {n} 个,共 {total} 个',
1791
1819
  'order.failed': '顺序没有保存:{msg}。已恢复原来的顺序。',
1792
- 'sort.arrange': '调整顺序…',
1820
+ 'sort.arrange': '调整顺序与置顶…',
1793
1821
  'set.order': '账号顺序、置顶与隐藏',
1794
1822
  'set.orderMine': '已调整',
1795
1823
  'set.orderDefault': '默认',
@@ -1868,6 +1896,7 @@ const zh = {
1868
1896
  'group.attentionShow': '定位到 {name}',
1869
1897
  'acct.alias': '别名',
1870
1898
  'acct.aliasArgs': '别名,启动这个账号并附加 {args}',
1899
+ 'acct.titleAlias': '{alias} 启动 {ref}',
1871
1900
  'acct.api': 'API',
1872
1901
  'acct.model': '模型',
1873
1902
  'acct.signedOut': '未登录',
@@ -2328,6 +2357,21 @@ const zh = {
2328
2357
  'row.copyRun': '复制启动命令:{cmd}',
2329
2358
  'row.installFirst': '先安装 {host},启动命令才能用',
2330
2359
  'menu.copyAlias': '复制别名',
2360
+ 'menu.setAlias': '设置别名…',
2361
+ 'al.title': '{ref} 的别名',
2362
+ 'al.intro': '别名是一个短命令:在终端里输入它,就会启动 {ref},登录和会话都不变。',
2363
+ 'al.nameLabel': '别名',
2364
+ 'al.namePh': '例如 cc-relay',
2365
+ 'al.hint': '可用字母、数字、- 和 _,保存后就是终端里的一个命令。',
2366
+ 'al.copy': '复制',
2367
+ 'al.badName': '只能用字母、数字、- 和 _,并以字母或 _ 开头。',
2368
+ 'al.addAnother': '再加一个',
2369
+ 'al.live': '已打开的终端在下一次出提示符时生效(按一次回车即可),新开的终端直接可用。',
2370
+ 'al.added': '已添加 {name}。在已打开的终端里按一次回车,再输入 {name}。',
2371
+ 'al.addedSetup': '已添加 {name}。还需要加一行配置,终端才会加载它,见弹窗里的提示。',
2372
+ 'al.renamed': '已把 {old} 改成 {name}。在已打开的终端里按一次回车,再输入 {name}。',
2373
+ 'al.renamedSetup': '已把 {old} 改成 {name}。还需要加一行配置,终端才会加载它,见弹窗里的提示。',
2374
+ 'al.removed': '已删除 {name}。',
2331
2375
  'menu.copyLogin': '复制登录命令',
2332
2376
  'menu.copyDir': '复制目录路径',
2333
2377
  'menu.copyEmail': '复制邮箱',
@@ -2842,6 +2886,12 @@ const zh = {
2842
2886
  'nf.aliasPh': '不设置',
2843
2887
  'nf.aliasHint': '在终端里启动这个账号的命令。留空表示不设置。',
2844
2888
  'nf.aliasSuggested': '按你其他 {host} 账号的短命令规律填入。',
2889
+ 'nf.aliasVendor': '按厂商命名,几个 API 账号一眼就能分清。',
2890
+ 'nf.aliasVendorTip': '在上面填厂商,就会得到 {example}。',
2891
+ 'nf.vendor': '厂商',
2892
+ 'nf.vendorPh': 'ds、kimi、glm…',
2893
+ 'nf.vendorHint': '这个 key 是哪家的,写几个字母就行。短命令按它命名。',
2894
+ 'nf.vendorWord': '厂商',
2845
2895
  'nf.aliasBad': '只能用字母、数字、“_”或“-”,并以字母或“_”开头。',
2846
2896
  'nf.aliasReserved': '“{alias}”是 shell 关键字或内置命令,请换一个。',
2847
2897
  'nf.aliasTaken': '{alias} 已用于启动 {ref}。',