sideby 0.18.0 → 0.19.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 (42) hide show
  1. package/README.md +8 -0
  2. package/dist/build.json +1 -1
  3. package/dist/src/cli/commands.js +159 -13
  4. package/dist/src/cli/json-schemas.js +39 -1
  5. package/dist/src/cli/main.js +23 -6
  6. package/dist/src/core/ask.d.ts +14 -0
  7. package/dist/src/core/ask.js +16 -1
  8. package/dist/src/core/browser-profiles.js +7 -32
  9. package/dist/src/core/config.d.ts +14 -0
  10. package/dist/src/core/config.js +64 -1
  11. package/dist/src/core/file-memo.js +26 -4
  12. package/dist/src/core/pick-commands.d.ts +42 -0
  13. package/dist/src/core/pick-commands.js +44 -0
  14. package/dist/src/core/shell-init.js +3 -1
  15. package/dist/src/core/shell-setup.d.ts +40 -0
  16. package/dist/src/core/shell-setup.js +54 -0
  17. package/dist/src/core/skill-check.d.ts +2 -0
  18. package/dist/src/core/skill-check.js +2 -0
  19. package/dist/src/core/terminal.d.ts +21 -4
  20. package/dist/src/core/terminal.js +149 -9
  21. package/dist/src/core/update.js +2 -2
  22. package/dist/src/core/windows-dirs.d.ts +19 -0
  23. package/dist/src/core/windows-dirs.js +39 -0
  24. package/dist/src/panel/handler.d.ts +18 -0
  25. package/dist/src/panel/handler.js +69 -1
  26. package/dist/src/panel/i18n.d.ts +39 -0
  27. package/dist/src/panel/i18n.js +78 -0
  28. package/dist/src/panel/page-script.js +184 -3
  29. package/dist/src/panel/page-styles.js +3 -0
  30. package/dist/src/panel/page.js +6 -1
  31. package/dist/src/plugins/account-script.js +61 -27
  32. package/dist/src/runtime.d.ts +35 -1
  33. package/dist/src/runtime.js +96 -3
  34. package/package.json +2 -2
  35. package/schemas/alias-list.json +119 -0
  36. package/schemas/alias.json +27 -1
  37. package/schemas/config.json +11 -0
  38. package/schemas/new.json +19 -0
  39. package/schemas/shell-init-setup.json +124 -0
  40. package/skills/sideby/SKILL.md +6 -3
  41. package/skills/sideby/references/accounts.md +10 -0
  42. package/skills/sideby/references/setup.md +1 -1
@@ -99,7 +99,17 @@ export const ConfigSchema = Type.Object({
99
99
  }, { additionalProperties: false, description: 'The Menu Bar Item on macOS (spec §3.31).' })),
100
100
  terminal: Type.Optional(Type.Object({
101
101
  preferred: Type.Optional(Type.String({
102
- enum: ['terminal', 'iterm2', 'ghostty', 'orca', 'wezterm', 'kitty', 'alacritty', 'custom'],
102
+ enum: [
103
+ 'terminal',
104
+ 'iterm2',
105
+ 'ghostty',
106
+ 'orca',
107
+ 'wezterm',
108
+ 'kitty',
109
+ 'alacritty',
110
+ 'windows-terminal',
111
+ 'custom',
112
+ ],
103
113
  description: 'The terminal sideby opens for AI Tasks; without it sideby picks the one you use.',
104
114
  })),
105
115
  custom: Type.Optional(Type.String({
@@ -119,6 +129,9 @@ export const ConfigSchema = Type.Object({
119
129
  aliases: Type.Optional(Type.Record(Type.String({ pattern: '^[A-Za-z_][A-Za-z0-9_-]*$' }), AliasSchema, {
120
130
  description: 'Short shell function names created by `sideby shell-init`, mapped to an Account ref or to `{ account, args }`.',
121
131
  })),
132
+ pickCommands: Type.Optional(Type.Record(Type.String({ pattern: '^[A-Za-z_][A-Za-z0-9_-]*$' }), Type.String({ minLength: 1 }), {
133
+ description: 'Pick Commands: short shell function names created by `sideby shell-init`, mapped to a Family. Each run starts the Account of that Family with the most Quota left, or the Main Account when none has Quota data (ADR-0035). They share one namespace with `aliases`.',
134
+ })),
122
135
  ignore: Type.Optional(Type.Array(Type.String(), { description: 'Account refs that are not Accounts.' })),
123
136
  pluginDirs: Type.Optional(Type.Array(Type.String(), { description: 'Absolute or `~/` paths of Plugin directories.' })),
124
137
  plugins: Type.Optional(Type.Record(Type.String(), Type.Record(Type.String(), Type.Unknown()), {
@@ -226,8 +239,22 @@ export async function loadConfig(file) {
226
239
  if (problem)
227
240
  throw new ConfigError(`${file}: alias "${alias}" ${problem} (it becomes a shell function name)`);
228
241
  }
242
+ const shortProblem = shortCommandProblem(data);
243
+ if (shortProblem)
244
+ throw new ConfigError(`${file}: ${shortProblem}`);
229
245
  return data;
230
246
  }
247
+ /** A Pick Command whose name is unsafe in a shell or also an Alias (they share one namespace), or null. */
248
+ function shortCommandProblem(data) {
249
+ for (const name of Object.keys(data.pickCommands ?? {})) {
250
+ const problem = aliasProblem(name);
251
+ if (problem)
252
+ return `pick command "${name}" ${problem} (it becomes a shell function name); pick another name`;
253
+ if (data.aliases && Object.hasOwn(data.aliases, name))
254
+ return `"${name}" is both an alias and a pick command; remove one with \`sideby alias rm ${name}\` and add it again`;
255
+ }
256
+ return null;
257
+ }
231
258
  /** Where the config file is read and written: the target of a link (a dotfiles manager may link it). */
232
259
  async function configTarget(file) {
233
260
  return (await lstatOrNull(file))?.isSymbolicLink() ? ((await realpathOrNull(file)) ?? file) : file;
@@ -287,6 +314,9 @@ async function editConfigKey(file, key, retry, edit, opts = {}) {
287
314
  code: 'bad-value',
288
315
  });
289
316
  }
317
+ const shortProblem = shortCommandProblem(next);
318
+ if (shortProblem)
319
+ throw new ConfigError(shortProblem, { code: 'bad-value' });
290
320
  const h = handoffSettings(next);
291
321
  if (h.prepareAt >= h.threshold)
292
322
  throw new ConfigError(`handoff.prepareAt must be lower than handoff.threshold; fix them in ${file} and ${retry} again`);
@@ -398,6 +428,38 @@ export async function removeConfigAlias(file, alias) {
398
428
  });
399
429
  return { status, aliases };
400
430
  }
431
+ /**
432
+ * Adds `name → family` to the config file's `pickCommands` (see `editConfigKey` for how the file is written). Refuses
433
+ * an invalid name, one that is an Alias, or one that already picks in another Family.
434
+ */
435
+ export async function addConfigPickCommand(file, name, family) {
436
+ const problem = aliasProblem(name);
437
+ if (problem)
438
+ throw new ConfigError(`pick command "${name}" ${problem} (it becomes a shell function name)`);
439
+ let status = 'added';
440
+ const r = await editConfigKey(file, 'pickCommands', 'add the pick command', (current) => {
441
+ const now = current ?? {};
442
+ if (!Object.hasOwn(now, name))
443
+ return { ...now, [name]: family };
444
+ if (now[name] !== family)
445
+ throw new ConfigError(`"${name}" already starts the ${now[name]} account with the most room; pick another name, or remove it first with \`sideby alias rm ${name}\``);
446
+ status = 'exists';
447
+ return null;
448
+ });
449
+ return { status, pickCommands: r.after ?? {} };
450
+ }
451
+ /** Removes `name` from `pickCommands`; `absent` when it was not there. An emptied key goes away with it. */
452
+ export async function removeConfigPickCommand(file, name) {
453
+ let status = 'absent';
454
+ const r = await editConfigKey(file, 'pickCommands', 'remove the pick command', (current) => {
455
+ if (!current || !Object.hasOwn(current, name))
456
+ return null;
457
+ status = 'removed';
458
+ const { [name]: _gone, ...rest } = current;
459
+ return Object.keys(rest).length ? rest : undefined;
460
+ });
461
+ return { status, pickCommands: r.after ?? {} };
462
+ }
401
463
  export function editConfigTerminal(file, patch) {
402
464
  return editConfigKey(file, 'terminal', 'run `sideby terminal`', (current) => {
403
465
  const next = { ...current, ...patch };
@@ -429,6 +491,7 @@ export function editConfigPanel(file, patch, opts = {}) {
429
491
  const PLACEHOLDERS = {
430
492
  accounts: '<family>:<name>',
431
493
  aliases: '<short>',
494
+ pickCommands: '<short>',
432
495
  plugins: '<plugin>',
433
496
  extraSharedItems: '<family>',
434
497
  'handoff.families': '<family>',
@@ -5,6 +5,11 @@ export function fileSignature(st) {
5
5
  export const persistedMemos = new Map();
6
6
  export class FileMemo {
7
7
  #scopes = new Map();
8
+ /**
9
+ * Parses running now, by scope and path: a second reader of the same file version (two passes at once, such as an
10
+ * Account's own identity and the Same Login check) waits for that parse instead of starting another.
11
+ */
12
+ #running = new Map();
8
13
  /** Counters for tests and timing. */
9
14
  stats = { hits: 0, misses: 0 };
10
15
  /** True when a pass changed what is remembered since the last `dump`. */
@@ -29,11 +34,28 @@ export class FileMemo {
29
34
  seen.set(path, hit);
30
35
  return hit.value;
31
36
  }
37
+ const key = `${scope}\0${path}`;
38
+ const running = this.#running.get(key);
39
+ if (running && running.sig === sig) {
40
+ this.stats.hits++;
41
+ const value = await running.value;
42
+ if (!keep || keep(value))
43
+ seen.set(path, { sig, value });
44
+ return value;
45
+ }
32
46
  this.stats.misses++;
33
- const value = await parse();
34
- if (!keep || keep(value))
35
- seen.set(path, { sig, value });
36
- return value;
47
+ const started = parse();
48
+ this.#running.set(key, { sig, value: started });
49
+ try {
50
+ const value = await started;
51
+ if (!keep || keep(value))
52
+ seen.set(path, { sig, value });
53
+ return value;
54
+ }
55
+ finally {
56
+ if (this.#running.get(key)?.value === started)
57
+ this.#running.delete(key);
58
+ }
37
59
  },
38
60
  done: () => {
39
61
  if (!before || before.size !== seen.size || [...seen].some(([k, v]) => before.get(k) !== v))
@@ -0,0 +1,42 @@
1
+ import type { HandoffPlan } from './handoff.ts';
2
+ /** The name offered for a built-in Family when its Aliases follow no pattern; pi gets none (`pi` is the Host). */
3
+ export declare const DEFAULT_PICK_NAMES: Readonly<Record<string, string>>;
4
+ /**
5
+ * The Pick Command name offered for a Family: the letters its numbered Aliases share (cc001, cc008 → cc), else the
6
+ * built-in default. Never the Host's own command name, which would hide the Host from the shell.
7
+ */
8
+ export declare function suggestPickName(family: string, bin: string, familyAliases: readonly string[]): string | null;
9
+ /** What a Pick Command starts this time, or why it starts nothing. */
10
+ export type PickChoice = {
11
+ ref: string;
12
+ reason: 'most-room';
13
+ pressure: number;
14
+ }
15
+ /** No Account of the Family has Quota data: the Main Account, or the Handoff pick when the main cannot start. */
16
+ | {
17
+ ref: string;
18
+ reason: 'no-quota-data';
19
+ }
20
+ /** The Accounts with Quota data are full; this one has none yet. */
21
+ | {
22
+ ref: string;
23
+ reason: 'others-full';
24
+ } | {
25
+ ref: null;
26
+ reason: 'none-usable';
27
+ earliestReset?: {
28
+ ref: string;
29
+ at: string;
30
+ };
31
+ signIn: string[];
32
+ };
33
+ /**
34
+ * Turns a Handoff plan into the Account to start (ADR-0035). With some Quota data: the pick. Without any: the Main
35
+ * Account (`mainRef`, a Subscription Account) when it can start, else the pick. Nothing usable (all full, signed out
36
+ * or API): nothing starts.
37
+ */
38
+ export declare function choosePick(plan: HandoffPlan, mainRef: string | null): PickChoice;
39
+ /** The line a Pick Command prints before it starts the Host. */
40
+ export declare function pickLine(name: string, choice: Exclude<PickChoice, {
41
+ ref: null;
42
+ }>): string;
@@ -0,0 +1,44 @@
1
+ /** The name offered for a built-in Family when its Aliases follow no pattern; pi gets none (`pi` is the Host). */
2
+ export const DEFAULT_PICK_NAMES = { claude: 'cc', codex: 'cx', grok: 'gk' };
3
+ /**
4
+ * The Pick Command name offered for a Family: the letters its numbered Aliases share (cc001, cc008 → cc), else the
5
+ * built-in default. Never the Host's own command name, which would hide the Host from the shell.
6
+ */
7
+ export function suggestPickName(family, bin, familyAliases) {
8
+ const prefixes = new Set(familyAliases.map((a) => /^([A-Za-z][A-Za-z_-]*?)-?\d+$/.exec(a)?.[1]).filter((p) => !!p));
9
+ const fromAliases = prefixes.size === 1 ? [...prefixes][0] : undefined;
10
+ const name = fromAliases ?? DEFAULT_PICK_NAMES[family];
11
+ return name && name !== bin ? name : null;
12
+ }
13
+ /**
14
+ * Turns a Handoff plan into the Account to start (ADR-0035). With some Quota data: the pick. Without any: the Main
15
+ * Account (`mainRef`, a Subscription Account) when it can start, else the pick. Nothing usable (all full, signed out
16
+ * or API): nothing starts.
17
+ */
18
+ export function choosePick(plan, mainRef) {
19
+ const startable = (ref) => plan.accounts.some((e) => e.ref === ref && !e.sameLoginAs && (e.state === 'ready' || e.state === 'unknown'));
20
+ if (!plan.hasQuota && mainRef && startable(mainRef))
21
+ return { ref: mainRef, reason: 'no-quota-data' };
22
+ if (plan.pick && plan.accounts.some((e) => e.ref === plan.pick && e.state !== 'api')) {
23
+ const e = plan.accounts.find((x) => x.ref === plan.pick);
24
+ if (!plan.hasQuota)
25
+ return { ref: plan.pick, reason: 'no-quota-data' };
26
+ return e.state === 'ready' && e.pressure !== null
27
+ ? { ref: plan.pick, reason: 'most-room', pressure: Math.round(e.pressure) }
28
+ : { ref: plan.pick, reason: 'others-full' };
29
+ }
30
+ return {
31
+ ref: null,
32
+ reason: 'none-usable',
33
+ ...(plan.earliestReset ? { earliestReset: plan.earliestReset } : {}),
34
+ signIn: plan.accounts.filter((e) => e.state === 'logged-out').map((e) => e.ref),
35
+ };
36
+ }
37
+ /** The line a Pick Command prints before it starts the Host. */
38
+ export function pickLine(name, choice) {
39
+ if (choice.reason === 'most-room')
40
+ return `${name} → ${choice.ref} (${choice.pressure}% used, the most room)`;
41
+ if (choice.reason === 'others-full')
42
+ return `${name} → ${choice.ref} (no quota data for it yet; the accounts with data are full)`;
43
+ return `${name} → ${choice.ref} (no quota data yet; \`sideby quota\` shows why)`;
44
+ }
@@ -35,9 +35,11 @@ export function shellInitScript(accounts, aliases, routes = []) {
35
35
  for (const acc of accounts)
36
36
  lines.push(`sideby-${acc.family}-${acc.name}() { command sideby run ${quote(acc.ref)} -- "$@"; }`);
37
37
  // An alias function runs the alias itself, so `sideby run` reads its Account and arguments from the config.
38
+ // `function name {`: zsh expands a shell alias of the same name in `name() {` and rejects the whole script, so a
39
+ // user's own `alias cc=…` would leave every function undefined. With this form their alias still wins.
38
40
  for (const alias of Object.keys(aliases ?? {}))
39
41
  if (!aliasProblem(alias))
40
- lines.push(`${alias}() { command sideby run ${quote(alias)} -- "$@"; }`);
42
+ lines.push(`function ${alias} { command sideby run ${quote(alias)} -- "$@"; }`);
41
43
  // An Alias with the Host's name wins: it already starts a chosen Account.
42
44
  for (const r of routes) {
43
45
  const fn = aliases && Object.hasOwn(aliases, r.bin) ? null : resumeRouteFunction(r);
@@ -0,0 +1,40 @@
1
+ import type { Env } from '../types.ts';
2
+ import { type Shell } from './shell-init.ts';
3
+ /** The block setup appends; `--undo` removes only this exact text. */
4
+ export declare const setupBlock: (shell: Shell) => string;
5
+ /** The user's shell, from `$SHELL`; zsh when it is neither zsh nor bash (the macOS default). */
6
+ export declare function userShell(env: Env): Shell;
7
+ /** The rc file an interactive shell reads: `$ZDOTDIR/.zshrc` (else `~/.zshrc`), or `~/.bashrc`. */
8
+ export declare const rcFile: (shell: Shell, home: string, env: Env) => string;
9
+ export interface ShellSetupStatus {
10
+ shell: Shell;
11
+ /** The rc file, as found (a link is not followed here). */
12
+ rc: string;
13
+ /**
14
+ * Whether new terminals load the short commands: the rc file names `sideby shell-init`, or the config has a
15
+ * `shellInitFile` for this shell (the user sources it themselves).
16
+ */
17
+ loaded: boolean;
18
+ /** Set when sideby's own block is in the rc file, so `--undo` can take it out. */
19
+ added: boolean;
20
+ }
21
+ export declare function shellSetupStatus(shell: Shell, home: string, env: Env, shellInitFile: Partial<Record<Shell, string>> | undefined): Promise<ShellSetupStatus>;
22
+ export type ShellSetupResult = {
23
+ status: 'added' | 'removed';
24
+ shell: Shell;
25
+ rc: string;
26
+ target: string;
27
+ } | {
28
+ status: 'unchanged';
29
+ shell: Shell;
30
+ rc: string;
31
+ reason: 'already-loaded' | 'not-added';
32
+ };
33
+ /**
34
+ * Appends the block to the rc file (`undo`: removes it). A link is written at its real target, never replaced; a
35
+ * missing file is created (mode 644); every other line stays as it was; nothing is written when the file changed
36
+ * while sideby read it. Refuses a path that exists but is not a regular file.
37
+ */
38
+ export declare function applyShellSetup(shell: Shell, home: string, env: Env, shellInitFile: Partial<Record<Shell, string>> | undefined, opts?: {
39
+ undo?: boolean;
40
+ }): Promise<ShellSetupResult>;
@@ -0,0 +1,54 @@
1
+ // `sideby shell-init setup` (spec §3.13, ADR-0036): adds the one line that loads sideby's short commands to the
2
+ // user's shell rc file, after a preview, the way mise, Starship and zoxide ask users to add theirs; `--undo` takes out
3
+ // exactly what it added.
4
+ import { readFile } from 'node:fs/promises';
5
+ import { basename, join } from 'node:path';
6
+ import { UserError } from './errors.js';
7
+ import { lstatOrNull, realpathOrNull, sha256, statOrNull, writeIfUnchanged } from './fs-safe.js';
8
+ import { SHELLS } from './shell-init.js';
9
+ const START = '# >>> sideby shell-init >>>';
10
+ const END = '# <<< sideby shell-init <<<';
11
+ /** The block setup appends; `--undo` removes only this exact text. */
12
+ export const setupBlock = (shell) => `${START}\n# Short commands such as cc and cc008. Remove with: sideby shell-init setup --undo\neval "$(sideby shell-init ${shell})"\n${END}\n`;
13
+ /** The user's shell, from `$SHELL`; zsh when it is neither zsh nor bash (the macOS default). */
14
+ export function userShell(env) {
15
+ const name = basename(env.SHELL ?? '');
16
+ return SHELLS.includes(name) ? name : 'zsh';
17
+ }
18
+ /** The rc file an interactive shell reads: `$ZDOTDIR/.zshrc` (else `~/.zshrc`), or `~/.bashrc`. */
19
+ export const rcFile = (shell, home, env) => shell === 'zsh' ? join(env.ZDOTDIR || home, '.zshrc') : join(home, '.bashrc');
20
+ export async function shellSetupStatus(shell, home, env, shellInitFile) {
21
+ const rc = rcFile(shell, home, env);
22
+ const text = await readFile(rc, 'utf8').catch(() => '');
23
+ return {
24
+ shell,
25
+ rc,
26
+ loaded: text.includes('sideby shell-init') || Boolean(shellInitFile?.[shell]),
27
+ added: text.includes(setupBlock(shell)),
28
+ };
29
+ }
30
+ /**
31
+ * Appends the block to the rc file (`undo`: removes it). A link is written at its real target, never replaced; a
32
+ * missing file is created (mode 644); every other line stays as it was; nothing is written when the file changed
33
+ * while sideby read it. Refuses a path that exists but is not a regular file.
34
+ */
35
+ export async function applyShellSetup(shell, home, env, shellInitFile, opts = {}) {
36
+ const st = await shellSetupStatus(shell, home, env, shellInitFile);
37
+ const block = setupBlock(shell);
38
+ if (opts.undo ? !st.added : st.loaded)
39
+ return { status: 'unchanged', shell, rc: st.rc, reason: opts.undo ? 'not-added' : 'already-loaded' };
40
+ const target = (await lstatOrNull(st.rc))?.isSymbolicLink()
41
+ ? ((await realpathOrNull(st.rc)) ?? st.rc)
42
+ : st.rc;
43
+ const info = await statOrNull(target);
44
+ if (info && !info.isFile())
45
+ throw new UserError(`${st.rc} is not a regular file; add the line yourself: ${block}`);
46
+ const before = info ? await readFile(target, 'utf8') : null;
47
+ const after = opts.undo
48
+ ? before.replace(`\n${block}`, '').replace(block, '')
49
+ : `${before ?? ''}${before && !before.endsWith('\n') ? '\n' : ''}${before ? '\n' : ''}${block}`;
50
+ const ok = await writeIfUnchanged(target, before === null ? null : sha256(before), after, info ? info.mode & 0o777 : 0o644);
51
+ if (!ok)
52
+ throw new UserError(`${st.rc} changed while sideby was writing it; nothing was changed. Try again`);
53
+ return { status: opts.undo ? 'removed' : 'added', shell, rc: st.rc, target };
54
+ }
@@ -1,5 +1,7 @@
1
1
  import type { FamilyDef, Finding } from '../types.ts';
2
2
  export declare const SKILL_SOURCE = "Adonis0123/sideby";
3
+ /** sideby's repository, linked from the Panel's header. */
4
+ export declare const REPO_URL = "https://github.com/Adonis0123/sideby";
3
5
  export declare const SKILL_INSTALL = "npx skills add Adonis0123/sideby -g";
4
6
  /** The command a person runs to update the skill where sideby leaves it alone. */
5
7
  export declare const SKILL_UPDATE_SHOWN = "npx skills update sideby -g";
@@ -6,6 +6,8 @@ import { dirname, join } from 'node:path';
6
6
  import { mainDirOf } from './accounts.js';
7
7
  import { tildify } from './paths.js';
8
8
  export const SKILL_SOURCE = 'Adonis0123/sideby';
9
+ /** sideby's repository, linked from the Panel's header. */
10
+ export const REPO_URL = `https://github.com/${SKILL_SOURCE}`;
9
11
  export const SKILL_INSTALL = `npx skills add ${SKILL_SOURCE} -g`;
10
12
  /** The command a person runs to update the skill where sideby leaves it alone. */
11
13
  export const SKILL_UPDATE_SHOWN = 'npx skills update sideby -g';
@@ -1,7 +1,8 @@
1
- import { access, stat } from 'node:fs/promises';
1
+ import { access, readdir, stat } from 'node:fs/promises';
2
2
  import type { Env } from '../types.ts';
3
3
  import type { DesktopDeps } from './desktop-app.ts';
4
- export type TerminalId = 'terminal' | 'iterm2' | 'ghostty' | 'orca' | 'wezterm' | 'kitty' | 'alacritty' | 'custom';
4
+ import { type WindowsExec } from './windows-dirs.ts';
5
+ export type TerminalId = 'terminal' | 'iterm2' | 'ghostty' | 'orca' | 'wezterm' | 'kitty' | 'alacritty' | 'windows-terminal' | 'custom';
5
6
  export interface TerminalDef {
6
7
  id: TerminalId;
7
8
  name: string;
@@ -11,7 +12,7 @@ export interface TerminalDef {
11
12
  marker?: string;
12
13
  binary?: string;
13
14
  }
14
- /** Supported macOS terminals; custom templates have no app bundle or environment marker. */
15
+ /** Supported terminals: macOS apps, and Windows Terminal on WSL; custom templates have no app bundle or environment marker. */
15
16
  export declare const TERMINALS: readonly TerminalDef[];
16
17
  export interface InstalledTerminal {
17
18
  id: TerminalId;
@@ -26,11 +27,16 @@ export interface TerminalDeps {
26
27
  fs?: {
27
28
  stat: typeof stat;
28
29
  access: typeof access;
30
+ readdir?: typeof readdir;
29
31
  };
32
+ /** On WSL, where Windows drives are mounted (normally `/mnt`); undefined elsewhere. */
33
+ wslMount?: string;
34
+ /** On WSL, runs `cmd.exe` to name the current Windows user's folders (core/windows-dirs.ts). */
35
+ exec?: WindowsExec;
30
36
  }
31
37
  /** Finds bundles and command line launchers without opening apps or reading user files. */
32
38
  export declare function installedTerminals(deps: TerminalDeps): Promise<InstalledTerminal[]>;
33
- /** Chooses an installed preference, then the launching environment, then macOS Terminal. */
39
+ /** Chooses an installed preference, then the launching environment, then macOS Terminal (Windows Terminal on WSL). */
34
40
  export declare function guessTerminal(opts: {
35
41
  preferred?: string;
36
42
  env: Env;
@@ -64,6 +70,12 @@ export interface TerminalLaunchOptions {
64
70
  custom?: string;
65
71
  appPath?: string;
66
72
  executable?: string;
73
+ /** Windows Terminal: the WSL distribution the tab returns to; the default distribution when absent. */
74
+ wslDistro?: string;
75
+ /** Windows Terminal: the user's login shell; zsh and bash run the task interactively, so their rc files apply. */
76
+ shell?: string;
77
+ /** Orca's Windows CLI from WSL: the worktree selector to open in; it also gets a WSL shell instead of its default. */
78
+ orcaWorktree?: string;
67
79
  }
68
80
  export interface TerminalCommand {
69
81
  file: string;
@@ -91,3 +103,8 @@ export declare function openTerminal(id: TerminalId, opts: TerminalLaunchOptions
91
103
  platform?: NodeJS.Platform;
92
104
  installed: readonly InstalledTerminal[];
93
105
  }, exec: DesktopDeps['exec']): Promise<TerminalOpenResult>;
106
+ /**
107
+ * The WSL distribution this runs in: `WSL_DISTRO_NAME`, which a background service lacks, else the name in
108
+ * `wslpath -w /` (`\\wsl.localhost\Ubuntu\`). Undefined when neither says.
109
+ */
110
+ export declare function wslDistro(env: Env, exec: DesktopDeps['exec']): Promise<string | undefined>;
@@ -1,8 +1,9 @@
1
1
  import { constants, realpathSync } from 'node:fs';
2
- import { access, stat } from 'node:fs/promises';
2
+ import { access, readdir, stat } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- /** Supported macOS terminals; custom templates have no app bundle or environment marker. */
5
+ import { askWindowsDirs } from './windows-dirs.js';
6
+ /** Supported terminals: macOS apps, and Windows Terminal on WSL; custom templates have no app bundle or environment marker. */
6
7
  export const TERMINALS = [
7
8
  {
8
9
  id: 'terminal',
@@ -58,11 +59,63 @@ export const TERMINALS = [
58
59
  termPrograms: [],
59
60
  marker: 'ALACRITTY_WINDOW_ID',
60
61
  },
62
+ {
63
+ id: 'windows-terminal',
64
+ name: 'Windows Terminal',
65
+ bundleId: null,
66
+ app: null,
67
+ termPrograms: [],
68
+ marker: 'WT_SESSION',
69
+ binary: 'wt.exe',
70
+ },
61
71
  { id: 'custom', name: 'Custom', bundleId: null, app: null, termPrograms: [] },
62
72
  ];
73
+ const isExecutable = async (fs, path) => (await fs.stat(path).then((s) => s.isFile(), () => false)) &&
74
+ (await fs.access(path, constants.X_OK).then(() => true, () => false));
75
+ /**
76
+ * The Windows terminals sideby can open from WSL: Windows Terminal (`wt.exe`) and Orca's Windows CLI (`orca.exe`), each
77
+ * on PATH or else in the current Windows user's `%LOCALAPPDATA%` (a background service's PATH has no Windows folders).
78
+ * When cmd.exe cannot name that user, a terminal only one user under `C:\Users` has is used; several are not guessed
79
+ * between.
80
+ */
81
+ async function wslTerminals(deps, mount) {
82
+ const fs = { stat, access, readdir, ...deps.fs };
83
+ const local = deps.exec ? (await askWindowsDirs(deps.exec, mount))?.localAppData?.unix : undefined;
84
+ const users = join(mount, 'c', 'Users');
85
+ const names = local ? [] : await fs.readdir(users).catch(() => []);
86
+ const find = async (exe, inLocal) => {
87
+ for (const dir of (deps.env.PATH ?? '').split(':').filter(Boolean)) {
88
+ const path = join(dir, exe);
89
+ if (await isExecutable(fs, path))
90
+ return path;
91
+ }
92
+ if (local) {
93
+ const path = join(local, ...inLocal, exe);
94
+ return (await isExecutable(fs, path)) ? path : undefined;
95
+ }
96
+ const hits = [];
97
+ for (const user of names) {
98
+ const path = join(users, user, 'AppData', 'Local', ...inLocal, exe);
99
+ if (await isExecutable(fs, path))
100
+ hits.push(path);
101
+ }
102
+ return hits.length === 1 ? hits[0] : undefined;
103
+ };
104
+ const found = [];
105
+ const wt = await find('wt.exe', ['Microsoft', 'WindowsApps']);
106
+ if (wt)
107
+ found.push({ id: 'windows-terminal', executable: wt });
108
+ const orca = await find('orca.exe', ['Programs', 'orca', 'resources', 'bin']);
109
+ if (orca)
110
+ found.push({ id: 'orca', executable: orca });
111
+ return found;
112
+ }
63
113
  /** Finds bundles and command line launchers without opening apps or reading user files. */
64
114
  export async function installedTerminals(deps) {
65
- if ((deps.platform ?? process.platform) !== 'darwin')
115
+ const platform = deps.platform ?? process.platform;
116
+ if (platform === 'linux' && deps.wslMount)
117
+ return wslTerminals(deps, deps.wslMount);
118
+ if (platform !== 'darwin')
66
119
  return [];
67
120
  const fs = deps.fs ?? { stat, access };
68
121
  const dirs = deps.appDirs ?? [
@@ -87,8 +140,7 @@ export async function installedTerminals(deps) {
87
140
  if (terminal.binary) {
88
141
  for (const dir of (deps.env.PATH ?? '').split(':').filter(Boolean)) {
89
142
  const path = join(dir, terminal.binary);
90
- if ((await fs.stat(path).then((s) => s.isFile(), () => false)) &&
91
- (await fs.access(path, constants.X_OK).then(() => true, () => false))) {
143
+ if (await isExecutable(fs, path)) {
92
144
  executable = path;
93
145
  break;
94
146
  }
@@ -101,14 +153,16 @@ export async function installedTerminals(deps) {
101
153
  }
102
154
  return found;
103
155
  }
104
- /** Chooses an installed preference, then the launching environment, then macOS Terminal. */
156
+ /** Chooses an installed preference, then the launching environment, then macOS Terminal (Windows Terminal on WSL). */
105
157
  export function guessTerminal(opts) {
106
158
  const has = (id) => opts.installed.some((t) => t.id === id);
107
159
  if (opts.preferred && has(opts.preferred))
108
160
  return { id: opts.preferred, source: 'config' };
109
161
  const match = TERMINALS.find((t) => has(t.id) &&
110
162
  (t.termPrograms.includes(opts.env.TERM_PROGRAM ?? '') || Boolean(t.marker && opts.env[t.marker])));
111
- return match ? { id: match.id, source: 'env' } : { id: 'terminal', source: 'default' };
163
+ if (match)
164
+ return { id: match.id, source: 'env' };
165
+ return { id: has('windows-terminal') ? 'windows-terminal' : 'terminal', source: 'default' };
112
166
  }
113
167
  /** This process's Node and the real path of the CLI entry next to this module (`main.ts` from source, `main.js` from dist). */
114
168
  export function askLauncher() {
@@ -291,7 +345,8 @@ end tell`,
291
345
  'terminal',
292
346
  'create',
293
347
  '--worktree',
294
- 'active',
348
+ opts.orcaWorktree ?? 'active',
349
+ ...(opts.orcaWorktree ? ['--shell', 'wsl.exe'] : []),
295
350
  '--command',
296
351
  command,
297
352
  '--title',
@@ -325,6 +380,33 @@ end tell`,
325
380
  held,
326
381
  ],
327
382
  };
383
+ // wt.exe splits its command line at `;`, and a `"` would be unquoted again on the way through wsl.exe; refuse
384
+ // both rather than guess at three layers of quoting. The hold therefore uses `&&` instead of `;`.
385
+ case 'windows-terminal': {
386
+ if (/[;"]/.test(command) || /[;"]/.test(cwd))
387
+ throw new Error('The task folder or command has ; or " in it; paste the task command into your terminal.');
388
+ const tabHeld = `${command} || (echo && echo sideby: press Return to close && read _)`;
389
+ // Like Terminal.app, run it in the user's own interactive shell: on WSL, version managers such as nvm put
390
+ // sideby on PATH only in ~/.zshrc or ~/.bashrc, and the Host runs `sideby` by name for Auto Handoff.
391
+ const shell = opts.shell && /\/(zsh|bash)$/.test(opts.shell) ? [opts.shell, '-lic'] : ['/bin/sh', '-lc'];
392
+ return {
393
+ file: opts.executable ?? 'wt.exe',
394
+ args: [
395
+ '-w',
396
+ '0',
397
+ 'new-tab',
398
+ '--title',
399
+ 'sideby',
400
+ 'wsl.exe',
401
+ ...(opts.wslDistro ? ['-d', opts.wslDistro] : []),
402
+ '--cd',
403
+ cwd,
404
+ '-e',
405
+ ...shell,
406
+ tabHeld,
407
+ ],
408
+ };
409
+ }
328
410
  case 'custom': {
329
411
  const [file, ...args] = validateCustomTemplate(opts.custom ?? '');
330
412
  return {
@@ -338,7 +420,10 @@ end tell`,
338
420
  }
339
421
  /** Opens through the injected Desktop exec boundary, returning safe, actionable failures only. */
340
422
  export async function openTerminal(id, opts, exec) {
341
- if ((opts.platform ?? process.platform) !== 'darwin')
423
+ const platform = opts.platform ?? process.platform;
424
+ const opensHere = platform === 'darwin' ||
425
+ (platform === 'linux' && (id === 'windows-terminal' || id === 'orca' || id === 'custom'));
426
+ if (!opensHere)
342
427
  return { ok: false, reason: 'unsupported-platform' };
343
428
  const installed = opts.installed.find((t) => t.id === id);
344
429
  if (!installed && id !== 'custom')
@@ -347,6 +432,16 @@ export async function openTerminal(id, opts, exec) {
347
432
  reason: 'not-installed',
348
433
  detail: 'Install this terminal or choose another in Settings; paste the task command into your terminal.',
349
434
  };
435
+ if (platform === 'linux' && id === 'orca') {
436
+ const worktree = await orcaWslWorktree(installed?.executable ?? 'orca.exe', opts.wslDistro, exec);
437
+ if (!worktree)
438
+ return {
439
+ ok: false,
440
+ reason: 'failed',
441
+ detail: 'Orca has no project open from this WSL distribution; open one in Orca, or choose another terminal in Settings.',
442
+ };
443
+ opts = { ...opts, orcaWorktree: worktree };
444
+ }
350
445
  try {
351
446
  const launch = launchArgs(id, { ...opts, ...installed });
352
447
  const result = await exec(launch.file, launch.args);
@@ -374,3 +469,48 @@ export async function openTerminal(id, opts, exec) {
374
469
  detail: 'Could not open the terminal; check its settings or paste the task command into your terminal.',
375
470
  };
376
471
  }
472
+ /**
473
+ * The WSL distribution this runs in: `WSL_DISTRO_NAME`, which a background service lacks, else the name in
474
+ * `wslpath -w /` (`\\wsl.localhost\Ubuntu\`). Undefined when neither says.
475
+ */
476
+ export async function wslDistro(env, exec) {
477
+ if (env.WSL_DISTRO_NAME)
478
+ return env.WSL_DISTRO_NAME;
479
+ try {
480
+ const r = await exec('wslpath', ['-w', '/']);
481
+ return r.code === 0 ? /^\\\\wsl(?:\.localhost|\$)\\([^\\]+)/.exec(r.stdout.trim())?.[1] : undefined;
482
+ }
483
+ catch {
484
+ return undefined;
485
+ }
486
+ }
487
+ /**
488
+ * Orca's Windows CLI resolves `--worktree active` from its current folder only, so from WSL sideby picks the worktree
489
+ * of this distribution (`\\wsl.localhost\<distribution>\…`) that Orca used last. Undefined when there is none.
490
+ */
491
+ async function orcaWslWorktree(orca, distro, exec) {
492
+ if (!distro)
493
+ return undefined;
494
+ try {
495
+ const r = await exec(orca, ['worktree', 'list', '--json']);
496
+ if (r.code !== 0)
497
+ return undefined;
498
+ const list = (JSON.parse(r.stdout)?.result?.worktrees ?? []);
499
+ const prefixes = [`\\\\wsl.localhost\\${distro}\\`, `\\\\wsl$\\${distro}\\`].map((p) => p.toLowerCase());
500
+ let best;
501
+ for (const w of list) {
502
+ if (typeof w.id !== 'string' || typeof w.path !== 'string')
503
+ continue;
504
+ const path = w.path.toLowerCase();
505
+ if (!prefixes.some((p) => path.startsWith(p)))
506
+ continue;
507
+ const at = typeof w.lastActivityAt === 'number' ? w.lastActivityAt : 0;
508
+ if (!best || at > best.at)
509
+ best = { id: w.id, at };
510
+ }
511
+ return best && `id:${best.id}`;
512
+ }
513
+ catch {
514
+ return undefined;
515
+ }
516
+ }