sideby 0.17.0 → 0.19.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 (112) hide show
  1. package/README.md +11 -1
  2. package/ai-tasks.json +90 -0
  3. package/dist/build.json +1 -1
  4. package/dist/src/cli/commands.d.ts +9 -1
  5. package/dist/src/cli/commands.js +507 -26
  6. package/dist/src/cli/json-schemas.js +196 -19
  7. package/dist/src/cli/main.js +79 -13
  8. package/dist/src/core/after-install.d.ts +54 -0
  9. package/dist/src/core/after-install.js +78 -0
  10. package/dist/src/core/ask.d.ts +87 -1
  11. package/dist/src/core/ask.js +122 -7
  12. package/dist/src/core/autostart.d.ts +38 -8
  13. package/dist/src/core/autostart.js +85 -39
  14. package/dist/src/core/brand-mark.d.ts +49 -11
  15. package/dist/src/core/brand-mark.js +116 -38
  16. package/dist/src/core/browser-profiles.js +7 -32
  17. package/dist/src/core/config.d.ts +19 -0
  18. package/dist/src/core/config.js +75 -2
  19. package/dist/src/core/desktop-app.d.ts +1 -1
  20. package/dist/src/core/desktop-app.js +2 -2
  21. package/dist/src/core/edit-settings.d.ts +24 -0
  22. package/dist/src/core/edit-settings.js +97 -0
  23. package/dist/src/core/handoff-brief.d.ts +4 -2
  24. package/dist/src/core/handoff-brief.js +6 -1
  25. package/dist/src/core/handoff-chain.d.ts +24 -0
  26. package/dist/src/core/handoff-chain.js +2 -0
  27. package/dist/src/core/handoff-run.d.ts +4 -3
  28. package/dist/src/core/handoff-run.js +14 -9
  29. package/dist/src/core/launch.d.ts +2 -0
  30. package/dist/src/core/launch.js +14 -10
  31. package/dist/src/core/local-build.d.ts +12 -5
  32. package/dist/src/core/local-build.js +49 -31
  33. package/dist/src/core/lock.d.ts +30 -0
  34. package/dist/src/core/lock.js +143 -0
  35. package/dist/src/core/pick-commands.d.ts +42 -0
  36. package/dist/src/core/pick-commands.js +44 -0
  37. package/dist/src/core/quota-levels.d.ts +6 -1
  38. package/dist/src/core/quota-levels.js +16 -5
  39. package/dist/src/core/shell-init.js +3 -1
  40. package/dist/src/core/shell-setup.d.ts +40 -0
  41. package/dist/src/core/shell-setup.js +54 -0
  42. package/dist/src/core/skill-check.d.ts +2 -0
  43. package/dist/src/core/skill-check.js +2 -0
  44. package/dist/src/core/task-spec.d.ts +95 -0
  45. package/dist/src/core/task-spec.js +209 -0
  46. package/dist/src/core/terminal.d.ts +21 -4
  47. package/dist/src/core/terminal.js +155 -10
  48. package/dist/src/core/update.d.ts +27 -16
  49. package/dist/src/core/update.js +69 -95
  50. package/dist/src/core/windows-dirs.d.ts +19 -0
  51. package/dist/src/core/windows-dirs.js +39 -0
  52. package/dist/src/desktop/icon.js +12 -15
  53. package/dist/src/families/claude/ai-task.d.ts +8 -0
  54. package/dist/src/families/claude/ai-task.js +38 -0
  55. package/dist/src/families/claude/handoff-hook.js +4 -4
  56. package/dist/src/families/claude/index.js +3 -0
  57. package/dist/src/families/codex/handoff-hook.js +4 -4
  58. package/dist/src/families/codex/index.js +9 -0
  59. package/dist/src/families/grok/handoff-hook.js +4 -4
  60. package/dist/src/families/grok/index.js +1 -0
  61. package/dist/src/families/pi/index.js +1 -0
  62. package/dist/src/handoff/hook.js +51 -30
  63. package/dist/src/handoff/levels.d.ts +24 -0
  64. package/dist/src/handoff/levels.js +70 -0
  65. package/dist/src/handoff/messages.d.ts +6 -3
  66. package/dist/src/handoff/messages.js +20 -7
  67. package/dist/src/handoff/reader.d.ts +6 -3
  68. package/dist/src/menubar/agent.d.ts +3 -0
  69. package/dist/src/menubar/agent.js +21 -0
  70. package/dist/src/menubar/script.d.ts +8 -0
  71. package/dist/src/menubar/script.js +457 -0
  72. package/dist/src/menubar/snapshot.d.ts +115 -0
  73. package/dist/src/menubar/snapshot.js +255 -0
  74. package/dist/src/menubar/strings.d.ts +87 -0
  75. package/dist/src/menubar/strings.js +88 -0
  76. package/dist/src/panel/background.js +12 -19
  77. package/dist/src/panel/handler.d.ts +30 -0
  78. package/dist/src/panel/handler.js +148 -80
  79. package/dist/src/panel/i18n.d.ts +72 -0
  80. package/dist/src/panel/i18n.js +144 -0
  81. package/dist/src/panel/page-logic.d.ts +105 -0
  82. package/dist/src/panel/page-logic.js +170 -15
  83. package/dist/src/panel/page-script.js +419 -111
  84. package/dist/src/panel/page-styles.js +45 -13
  85. package/dist/src/panel/page.d.ts +7 -0
  86. package/dist/src/panel/page.js +11 -1
  87. package/dist/src/runtime.d.ts +44 -2
  88. package/dist/src/runtime.js +107 -6
  89. package/dist/src/types.d.ts +14 -0
  90. package/package.json +4 -3
  91. package/schemas/alias-list.json +119 -0
  92. package/schemas/alias.json +27 -1
  93. package/schemas/ask-choices.json +168 -0
  94. package/schemas/ask-print.json +87 -0
  95. package/schemas/config.json +28 -1
  96. package/schemas/edit.json +119 -0
  97. package/schemas/error.json +4 -0
  98. package/schemas/families.json +4 -0
  99. package/schemas/list.json +4 -0
  100. package/schemas/local.json +1 -1
  101. package/schemas/menubar-snapshot.json +646 -0
  102. package/schemas/menubar-start.json +112 -0
  103. package/schemas/menubar.json +165 -0
  104. package/schemas/new.json +19 -0
  105. package/schemas/shell-init-setup.json +124 -0
  106. package/skills/sideby/SKILL.md +11 -4
  107. package/skills/sideby/references/accounts.md +10 -0
  108. package/skills/sideby/references/ai-tasks.md +10 -0
  109. package/skills/sideby/references/handoff.md +3 -1
  110. package/skills/sideby/references/panel.md +6 -0
  111. package/skills/sideby/references/setup.md +1 -1
  112. package/skills/sideby/references/update.md +1 -1
@@ -0,0 +1,95 @@
1
+ import type { Runtime } from '../runtime.ts';
2
+ import { type AiTaskInput } from './ask.ts';
3
+ import { type Attachment } from './attachments.ts';
4
+ import { UserError } from './errors.ts';
5
+ /** The largest Task Spec read from stdin. */
6
+ export declare const MAX_SPEC_BYTES: number;
7
+ /** The Task Spec version this sideby understands; a Portal that sends another one is told to update sideby. */
8
+ export declare const SPEC_VERSION = 1;
9
+ /** Why a Task Spec was refused; `spec-version` exits 2 so a Portal can tell "update sideby" apart. */
10
+ export type SpecErrorCode = 'spec-invalid' | 'spec-too-large' | 'spec-version' | 'bad-cwd';
11
+ export declare class SpecError extends UserError {
12
+ readonly code: SpecErrorCode;
13
+ constructor(code: SpecErrorCode, message: string);
14
+ }
15
+ interface SpecCommon {
16
+ lang?: 'en' | 'zh';
17
+ account?: string;
18
+ terminal?: string;
19
+ remember?: boolean;
20
+ files?: string[];
21
+ }
22
+ export type TaskSpec = (SpecCommon & {
23
+ prompt: string;
24
+ cwd?: string;
25
+ }) | (SpecCommon & {
26
+ native: {
27
+ task: string;
28
+ text?: string;
29
+ context?: AiTaskInput['context'];
30
+ };
31
+ });
32
+ /** Reads a Task Spec from `input` (stdin), refusing more than MAX_SPEC_BYTES before it is all read. */
33
+ export declare function readSpecText(input: AsyncIterable<Buffer | string>): Promise<string>;
34
+ /** Checks a Task Spec's shape. Values are kept as given; `cwd` is checked later against the HOME. */
35
+ export declare function parseTaskSpec(text: string): TaskSpec;
36
+ /**
37
+ * The folder a Task Spec's prompt starts in: an existing directory inside the HOME, as its real path. Without one,
38
+ * sideby's own task work folder (`"cwd": "engine"` in a Tool's declaration).
39
+ */
40
+ export declare function specCwd(rt: Runtime, cwd: string | undefined): Promise<string | undefined>;
41
+ /** `sideby ask --spec - --print`: the prompt the Host would get, without writing a task or copying a file. */
42
+ export declare function previewTaskSpec(rt: Runtime, spec: TaskSpec): Promise<{
43
+ schemaVersion: 1;
44
+ prompt: string;
45
+ removedSecrets: boolean;
46
+ }>;
47
+ /** `sideby ask --spec -`: starts the AI Task the spec describes; the result is `startAiTask`'s. */
48
+ export declare function startTaskSpec(rt: Runtime, spec: TaskSpec): Promise<{
49
+ schemaVersion: 1;
50
+ task: null;
51
+ account: null;
52
+ terminal: null;
53
+ opened: boolean;
54
+ command: null;
55
+ prompt: string;
56
+ reason: import("./ask.ts").AiTaskReason;
57
+ detail: string;
58
+ removedSecrets: boolean;
59
+ attachments: Attachment[];
60
+ } | {
61
+ schemaVersion: 1;
62
+ task: string;
63
+ account: string;
64
+ terminal: string;
65
+ opened: boolean;
66
+ command: string;
67
+ reason?: import("./ask.ts").AiTaskReason | undefined;
68
+ detail?: string | undefined;
69
+ prompt?: undefined;
70
+ removedSecrets: boolean;
71
+ attachments: Attachment[];
72
+ }>;
73
+ /**
74
+ * `sideby ask --choices` (ADR-0030): what a Portal's dialog offers before it starts a task. `account` is what an AI
75
+ * Task would pick now (null with `reason` and `detail` when nothing can be picked); `accounts` lists every API
76
+ * Account and Subscription Account, signed-in ones first; `terminals` the supported terminals installed here, with
77
+ * the one a task would open in `terminal`.
78
+ */
79
+ export declare function taskChoices(rt: Runtime): Promise<{
80
+ schemaVersion: 1;
81
+ account: string | null;
82
+ accounts: {
83
+ ref: string;
84
+ label: string;
85
+ signedIn: boolean;
86
+ }[];
87
+ terminal: import("./terminal.ts").TerminalId;
88
+ terminals: {
89
+ id: import("./terminal.ts").TerminalId;
90
+ label: string;
91
+ }[];
92
+ reason: "all-full" | "no-accounts" | "none-signed-in" | null;
93
+ detail: string | null;
94
+ }>;
95
+ export {};
@@ -0,0 +1,209 @@
1
+ // Task Specs (spec §3.28 "Portal 交来的任务", ADR-0030): a Portal hands sideby an AI Task as one JSON object on
2
+ // stdin, either a Task Prompt it wrote for another Tool or one of sideby's own tasks (`native`). sideby picks the
3
+ // Account, takes the attachments and opens the Preferred Terminal exactly as for its own AI Tasks; the prompt reaches
4
+ // the Host only through the task file, never a shell.
5
+ import { isAbsolute } from 'node:path';
6
+ import { AI_TASK_KINDS, attachedSection, stripSecrets } from '../panel/page-logic.js';
7
+ import { newTaskId, openPromptTask, PICK_DETAIL, pickTaskAccount, previewAttachments, promptForTask, realCwdInHome, startAiTask, taskContext, taskLang, terminals, } from './ask.js';
8
+ import { checkAttachmentFiles, copyAttachments, MAX_ATTACHMENTS } from './attachments.js';
9
+ import { UserError } from './errors.js';
10
+ import { TERMINALS } from './terminal.js';
11
+ /** The largest Task Spec read from stdin. */
12
+ export const MAX_SPEC_BYTES = 1024 * 1024;
13
+ /** The Task Spec version this sideby understands; a Portal that sends another one is told to update sideby. */
14
+ export const SPEC_VERSION = 1;
15
+ export class SpecError extends UserError {
16
+ code;
17
+ constructor(code, message) {
18
+ super(message, { code });
19
+ this.code = code;
20
+ }
21
+ }
22
+ const invalid = (message) => new SpecError('spec-invalid', `${message}; fix the Task Spec and send it again.`);
23
+ const COMMON = ['specVersion', 'lang', 'account', 'terminal', 'remember', 'files'];
24
+ /** Reads a Task Spec from `input` (stdin), refusing more than MAX_SPEC_BYTES before it is all read. */
25
+ export async function readSpecText(input) {
26
+ const chunks = [];
27
+ let size = 0;
28
+ for await (const chunk of input) {
29
+ const buf = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
30
+ size += buf.length;
31
+ if (size > MAX_SPEC_BYTES)
32
+ throw new SpecError('spec-too-large', `The Task Spec is larger than ${MAX_SPEC_BYTES} bytes; attach big content as files instead.`);
33
+ chunks.push(buf);
34
+ }
35
+ return Buffer.concat(chunks).toString('utf8');
36
+ }
37
+ /** Checks a Task Spec's shape. Values are kept as given; `cwd` is checked later against the HOME. */
38
+ export function parseTaskSpec(text) {
39
+ let raw;
40
+ try {
41
+ raw = JSON.parse(text);
42
+ }
43
+ catch {
44
+ throw invalid('The Task Spec is not valid JSON');
45
+ }
46
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
47
+ throw invalid('The Task Spec must be one JSON object');
48
+ const o = raw;
49
+ if (o.specVersion !== SPEC_VERSION) {
50
+ if (typeof o.specVersion === 'number')
51
+ throw new SpecError('spec-version', `This sideby reads Task Spec version ${SPEC_VERSION}, not ${o.specVersion}; update sideby with \`sideby update\`.`);
52
+ throw invalid(`"specVersion" must be ${SPEC_VERSION}`);
53
+ }
54
+ const hasPrompt = o.prompt !== undefined;
55
+ const hasNative = o.native !== undefined;
56
+ if (hasPrompt === hasNative)
57
+ throw invalid('Give either "prompt" (with "cwd") or "native", not both or neither');
58
+ const allowed = new Set([...COMMON, ...(hasPrompt ? ['prompt', 'cwd'] : ['native'])]);
59
+ for (const k of Object.keys(o))
60
+ if (!allowed.has(k))
61
+ throw invalid(`Unknown field "${k}"`);
62
+ const common = {};
63
+ if (o.lang !== undefined && o.lang !== null) {
64
+ if (o.lang !== 'en' && o.lang !== 'zh')
65
+ throw invalid('"lang" must be "en" or "zh"');
66
+ common.lang = o.lang;
67
+ }
68
+ for (const key of ['account', 'terminal']) {
69
+ const v = o[key];
70
+ if (v === undefined || v === null)
71
+ continue;
72
+ if (typeof v !== 'string' || !v)
73
+ throw invalid(`"${key}" must be a string or null`);
74
+ common[key] = v;
75
+ }
76
+ if (common.terminal && !TERMINALS.some((t) => t.id === common.terminal))
77
+ throw invalid(`"terminal" must be one of ${TERMINALS.map((t) => t.id).join(', ')}`);
78
+ if (o.remember !== undefined && o.remember !== null) {
79
+ if (typeof o.remember !== 'boolean')
80
+ throw invalid('"remember" must be true or false');
81
+ common.remember = o.remember;
82
+ }
83
+ if (o.files !== undefined && o.files !== null) {
84
+ const f = o.files;
85
+ if (!Array.isArray(f) ||
86
+ f.length > MAX_ATTACHMENTS ||
87
+ !f.every((p) => typeof p === 'string' && isAbsolute(p) && !p.includes('\0')))
88
+ throw invalid(`"files" must list at most ${MAX_ATTACHMENTS} absolute paths`);
89
+ if (f.length)
90
+ common.files = f;
91
+ }
92
+ if (hasPrompt) {
93
+ if (typeof o.prompt !== 'string' || !o.prompt.trim())
94
+ throw invalid('"prompt" must be a non-empty string');
95
+ if (o.cwd !== undefined && o.cwd !== null && typeof o.cwd !== 'string')
96
+ throw invalid('"cwd" must be a path');
97
+ return { ...common, prompt: o.prompt, ...(typeof o.cwd === 'string' ? { cwd: o.cwd } : {}) };
98
+ }
99
+ const n = o.native;
100
+ if (!n || typeof n !== 'object' || Array.isArray(n))
101
+ throw invalid('"native" must be an object');
102
+ const native = n;
103
+ for (const k of Object.keys(native))
104
+ if (!['task', 'text', 'context'].includes(k))
105
+ throw invalid(`Unknown field "native.${k}"`);
106
+ if (typeof native.task !== 'string' || !AI_TASK_KINDS.includes(native.task))
107
+ throw invalid(`"native.task" must be one of ${AI_TASK_KINDS.join(', ')}`);
108
+ if (native.text !== undefined && native.text !== null && typeof native.text !== 'string')
109
+ throw invalid('"native.text" must be a string');
110
+ const context = taskContext(native.context, (m) => invalid(m.replace('"context', '"native.context')));
111
+ return {
112
+ ...common,
113
+ native: {
114
+ task: native.task,
115
+ ...(typeof native.text === 'string' && native.text ? { text: native.text } : {}),
116
+ ...(context ? { context } : {}),
117
+ },
118
+ };
119
+ }
120
+ /**
121
+ * The folder a Task Spec's prompt starts in: an existing directory inside the HOME, as its real path. Without one,
122
+ * sideby's own task work folder (`"cwd": "engine"` in a Tool's declaration).
123
+ */
124
+ export async function specCwd(rt, cwd) {
125
+ if (cwd === undefined)
126
+ return undefined;
127
+ const bad = (why) => new SpecError('bad-cwd', `The task folder ${JSON.stringify(cwd)} ${why}; name an existing folder in your home.`);
128
+ const checked = await realCwdInHome(cwd, rt.paths.home);
129
+ if ('why' in checked)
130
+ throw bad(checked.why);
131
+ return checked.real;
132
+ }
133
+ function nativeInput(spec) {
134
+ return {
135
+ task: spec.native.task,
136
+ ...(spec.native.text ? { text: spec.native.text } : {}),
137
+ ...(spec.native.context ? { context: spec.native.context } : {}),
138
+ ...(spec.lang ? { lang: spec.lang } : {}),
139
+ ...(spec.account ? { account: spec.account } : {}),
140
+ ...(spec.terminal ? { terminal: spec.terminal } : {}),
141
+ ...(spec.remember ? { remember: spec.remember } : {}),
142
+ ...(spec.files ? { files: spec.files } : {}),
143
+ };
144
+ }
145
+ /** A Portal's prompt as the Host gets it: keys removed again, then the attachments section at its heading level. */
146
+ function specPrompt(rt, spec, attachments) {
147
+ const cleaned = stripSecrets(spec.prompt);
148
+ const heading = /^(#{1,6} )\S/m.exec(cleaned.text)?.[1] ?? '';
149
+ const files = attachments.map(({ path, kind }) => ({ path, kind }));
150
+ const section = attachedSection(files, taskLang(rt, spec.lang), heading);
151
+ return {
152
+ prompt: section ? `${cleaned.text.trimEnd()}\n\n${section}` : cleaned.text,
153
+ removedSecrets: cleaned.removed,
154
+ };
155
+ }
156
+ /** `sideby ask --spec - --print`: the prompt the Host would get, without writing a task or copying a file. */
157
+ export async function previewTaskSpec(rt, spec) {
158
+ if ('native' in spec) {
159
+ const input = nativeInput(spec);
160
+ const { prompt, removedSecrets } = promptForTask(rt, input, await previewAttachments(rt, input));
161
+ return { schemaVersion: 1, prompt, removedSecrets };
162
+ }
163
+ await specCwd(rt, spec.cwd);
164
+ const files = spec.files ? await checkAttachmentFiles(spec.files) : [];
165
+ return { schemaVersion: 1, ...specPrompt(rt, spec, files) };
166
+ }
167
+ /** `sideby ask --spec -`: starts the AI Task the spec describes; the result is `startAiTask`'s. */
168
+ export async function startTaskSpec(rt, spec) {
169
+ if ('native' in spec)
170
+ return startAiTask(rt, nativeInput(spec));
171
+ // The folder is checked before any attachment is copied.
172
+ const cwd = await specCwd(rt, spec.cwd);
173
+ const taskId = newTaskId();
174
+ const attachments = spec.files ? await copyAttachments(rt.paths, spec.files, taskId) : [];
175
+ const written = specPrompt(rt, spec, attachments);
176
+ return openPromptTask(rt, spec, { taskId, ...written, attachments, ...(cwd ? { cwd } : {}) });
177
+ }
178
+ /**
179
+ * `sideby ask --choices` (ADR-0030): what a Portal's dialog offers before it starts a task. `account` is what an AI
180
+ * Task would pick now (null with `reason` and `detail` when nothing can be picked); `accounts` lists every API
181
+ * Account and Subscription Account, signed-in ones first; `terminals` the supported terminals installed here, with
182
+ * the one a task would open in `terminal`.
183
+ */
184
+ export async function taskChoices(rt) {
185
+ const pick = await pickTaskAccount(rt);
186
+ const signedIn = [];
187
+ const api = [];
188
+ const signedOut = [];
189
+ const all = [...(await rt.accounts())].sort((a, b) => (a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0));
190
+ for (const a of all) {
191
+ if (a.kind === 'api')
192
+ api.push({ ref: a.ref, label: `${a.ref} · API`, signedIn: true });
193
+ else if ((await rt.status(a)).login === 'logged-in')
194
+ signedIn.push({ ref: a.ref, label: a.ref, signedIn: true });
195
+ else
196
+ signedOut.push({ ref: a.ref, label: a.ref, signedIn: false });
197
+ }
198
+ const t = await terminals(rt);
199
+ const name = (id) => TERMINALS.find((x) => x.id === id)?.name ?? id;
200
+ return {
201
+ schemaVersion: 1,
202
+ account: 'account' in pick ? pick.account.ref : null,
203
+ accounts: [...signedIn, ...api, ...signedOut],
204
+ terminal: t.guess.id,
205
+ terminals: t.installed.map((i) => ({ id: i.id, label: name(i.id) })),
206
+ reason: 'reason' in pick ? pick.reason : null,
207
+ detail: 'reason' in pick ? PICK_DETAIL[pick.reason] : null,
208
+ };
209
+ }
@@ -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,11 +432,26 @@ 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);
353
- if (result.code === 0)
448
+ if (result.code === 0) {
449
+ // `orca terminal create --focus` only switches tabs inside Orca; bring its window to the front too.
450
+ const bundleId = id === 'orca' ? TERMINALS.find((t) => t.id === 'orca')?.bundleId : null;
451
+ if (bundleId)
452
+ await exec('/usr/bin/open', ['-b', bundleId]).catch(() => undefined);
354
453
  return { ok: true };
454
+ }
355
455
  if (launch.file === '/usr/bin/osascript' &&
356
456
  (result.code === -1743 || /-1743|Not authorized to send Apple events/i.test(result.stderr)))
357
457
  return {
@@ -369,3 +469,48 @@ export async function openTerminal(id, opts, exec) {
369
469
  detail: 'Could not open the terminal; check its settings or paste the task command into your terminal.',
370
470
  };
371
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
+ }