@agy-daddy/plugin-cli 0.0.0-stage → 1.1.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.
- package/LICENSE +22 -0
- package/NOTICE +7 -0
- package/README.md +7 -2
- package/agy-plugin.json +49 -0
- package/baseline.json +10 -0
- package/locales/en.json +4 -0
- package/locales/zh-CN.json +4 -0
- package/package.json +31 -4
- package/scripts/cli-window-helper.cs +453 -0
- package/settings.schema.json +141 -0
- package/src/node.js +531 -0
- package/src/renderer.js +491 -0
- package/src/terminals.js +1075 -0
package/src/terminals.js
ADDED
|
@@ -0,0 +1,1075 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const os = require('os');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const { fileURLToPath } = require('url');
|
|
7
|
+
|
|
8
|
+
const CLI_PERMISSION_MODES = Object.freeze([
|
|
9
|
+
'default',
|
|
10
|
+
'plan',
|
|
11
|
+
'accept-edits',
|
|
12
|
+
'auto',
|
|
13
|
+
'skip-permissions'
|
|
14
|
+
]);
|
|
15
|
+
|
|
16
|
+
const TERMINAL_LABELS = Object.freeze({
|
|
17
|
+
auto: '自动探测',
|
|
18
|
+
terminal: 'Terminal.app',
|
|
19
|
+
iterm2: 'iTerm2',
|
|
20
|
+
ghostty: 'Ghostty',
|
|
21
|
+
warp: 'Warp',
|
|
22
|
+
kitty: 'Kitty',
|
|
23
|
+
wezterm: 'WezTerm',
|
|
24
|
+
cmux: 'cmux',
|
|
25
|
+
alacritty: 'Alacritty',
|
|
26
|
+
rex: 'Rex',
|
|
27
|
+
tmux: 'tmux',
|
|
28
|
+
wt: 'Windows Terminal',
|
|
29
|
+
powershell: 'PowerShell',
|
|
30
|
+
cmd: 'Command Prompt',
|
|
31
|
+
wsl: 'WSL'
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
function resolvePermissionArgs(options = {}) {
|
|
35
|
+
const mode = typeof options.cliPermissionMode === 'string' ? options.cliPermissionMode.trim() : '';
|
|
36
|
+
if (CLI_PERMISSION_MODES.includes(mode)) {
|
|
37
|
+
if (mode === 'skip-permissions') return ['--dangerously-skip-permissions'];
|
|
38
|
+
if (mode === 'auto' || mode === 'accept-edits' || mode === 'plan') return ['--mode', mode];
|
|
39
|
+
return [];
|
|
40
|
+
}
|
|
41
|
+
if (options.cliSkipPermissions) {
|
|
42
|
+
return ['--dangerously-skip-permissions'];
|
|
43
|
+
}
|
|
44
|
+
return [];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function parseQuickCommands(rawList) {
|
|
48
|
+
if (!Array.isArray(rawList)) return [];
|
|
49
|
+
const out = [];
|
|
50
|
+
rawList.forEach((rawItem, idx) => {
|
|
51
|
+
let name = '';
|
|
52
|
+
let command = '';
|
|
53
|
+
let pinToTopbar = true;
|
|
54
|
+
let id = `quick-${idx}`;
|
|
55
|
+
if (rawItem && typeof rawItem === 'object' && !Array.isArray(rawItem)) {
|
|
56
|
+
command = String(rawItem.command || '').trim();
|
|
57
|
+
name = String(rawItem.name || '').trim();
|
|
58
|
+
pinToTopbar = rawItem.pinToTopbar !== false;
|
|
59
|
+
if (rawItem.id) id = String(rawItem.id);
|
|
60
|
+
} else {
|
|
61
|
+
const rawStr = String(rawItem ?? '').trim();
|
|
62
|
+
if (!rawStr) return;
|
|
63
|
+
if (rawStr.startsWith('{')) {
|
|
64
|
+
try {
|
|
65
|
+
const parsed = JSON.parse(rawStr);
|
|
66
|
+
if (parsed && typeof parsed === 'object') {
|
|
67
|
+
command = String(parsed.command || '').trim();
|
|
68
|
+
name = String(parsed.name || '').trim();
|
|
69
|
+
pinToTopbar = parsed.pinToTopbar !== false;
|
|
70
|
+
if (parsed.id) id = String(parsed.id);
|
|
71
|
+
}
|
|
72
|
+
} catch {}
|
|
73
|
+
}
|
|
74
|
+
if (!command) command = rawStr;
|
|
75
|
+
}
|
|
76
|
+
if (!command) return;
|
|
77
|
+
if (!name) name = command.split(/\s+/)[0] || `命令 ${idx + 1}`;
|
|
78
|
+
out.push({ id, name, command, pinToTopbar });
|
|
79
|
+
});
|
|
80
|
+
return out;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function escapePosixArg(arg) {
|
|
84
|
+
return "'" + String(arg ?? '').replace(/'/g, "'\\''") + "'";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function formatCliArgToken(raw) {
|
|
88
|
+
const clean = String(raw ?? '').replace(/\0/g, '').trim();
|
|
89
|
+
if (!clean) return '';
|
|
90
|
+
return /^[a-zA-Z0-9._:@/=+-]+$/.test(clean) ? clean : escapePosixArg(clean);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function buildDefaultCliCommand(options = {}) {
|
|
94
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
95
|
+
const cliBin = String(opts.cliBin || 'agy').replace(/\0/g, '').trim() || 'agy';
|
|
96
|
+
const tokens = [formatCliArgToken(cliBin)];
|
|
97
|
+
for (const arg of resolvePermissionArgs(opts)) {
|
|
98
|
+
const tok = formatCliArgToken(arg);
|
|
99
|
+
if (tok) tokens.push(tok);
|
|
100
|
+
}
|
|
101
|
+
const model = String(opts.cliDefaultModel ?? '').replace(/\0/g, '').trim();
|
|
102
|
+
if (model) {
|
|
103
|
+
tokens.push('--model', formatCliArgToken(model));
|
|
104
|
+
}
|
|
105
|
+
return tokens.filter(Boolean).join(' ');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function escapeAppleScriptString(str) {
|
|
109
|
+
return String(str ?? '')
|
|
110
|
+
.replace(/\\/g, '\\\\')
|
|
111
|
+
.replace(/"/g, '\\"')
|
|
112
|
+
.replace(/\r/g, '\\r')
|
|
113
|
+
.replace(/\n/g, '\\n');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function escapePowerShellSingleQuoted(str) {
|
|
117
|
+
return String(str ?? '').replace(/'/g, "''");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function toWslPath(winPath) {
|
|
121
|
+
const s = String(winPath || '').trim();
|
|
122
|
+
const match = s.match(/^([a-zA-Z]):[\\/](.*)$/);
|
|
123
|
+
if (match) {
|
|
124
|
+
return `/mnt/${match[1].toLowerCase()}/${match[2].replace(/\\/g, '/')}`;
|
|
125
|
+
}
|
|
126
|
+
if (/^[a-zA-Z]:$/.test(s)) {
|
|
127
|
+
return `/mnt/${s[0].toLowerCase()}`;
|
|
128
|
+
}
|
|
129
|
+
return s.replace(/\\/g, '/');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function sanitizeMuxHost(raw) {
|
|
133
|
+
const trimmed = String(raw || '').trim();
|
|
134
|
+
if (!trimmed) return '';
|
|
135
|
+
const lower = trimmed.toLowerCase();
|
|
136
|
+
if (['local', 'localhost', '127.0.0.1', '__local__'].includes(lower) || lower.startsWith('unix://')) {
|
|
137
|
+
return '';
|
|
138
|
+
}
|
|
139
|
+
if (/^[a-zA-Z0-9][a-zA-Z0-9._:@-]{0,127}$/.test(trimmed)) {
|
|
140
|
+
return trimmed;
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function findInPath(binName, options = {}) {
|
|
146
|
+
const platform = options.platform || process.platform;
|
|
147
|
+
const env = options.env || process.env;
|
|
148
|
+
const existsSync = options.existsSync || fs.existsSync;
|
|
149
|
+
const pathMod = platform === 'win32' ? path.win32 : path.posix;
|
|
150
|
+
const sep = platform === 'win32' ? ';' : ':';
|
|
151
|
+
const rawPath = env.PATH || env.Path || '';
|
|
152
|
+
const dirs = String(rawPath).split(sep).filter(Boolean);
|
|
153
|
+
if (options.includeDefaultDirs !== false && platform === 'darwin' && !options.env) {
|
|
154
|
+
const home = options.homeDir || os.homedir();
|
|
155
|
+
for (const fallbackDir of ['/opt/homebrew/bin', '/usr/local/bin', path.posix.join(home, '.local', 'bin')]) {
|
|
156
|
+
if (!dirs.includes(fallbackDir)) dirs.push(fallbackDir);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
for (const dir of dirs) {
|
|
160
|
+
const cand = pathMod.join(dir, binName);
|
|
161
|
+
try {
|
|
162
|
+
if (existsSync(cand)) return cand;
|
|
163
|
+
} catch {}
|
|
164
|
+
}
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function getDarwinTerminalSpecs(options = {}) {
|
|
169
|
+
const home = options.homeDir || os.homedir();
|
|
170
|
+
return [
|
|
171
|
+
{ id: 'terminal', name: 'Terminal.app', paths: ['/System/Applications/Utilities/Terminal.app', '/Applications/Utilities/Terminal.app'] },
|
|
172
|
+
{ id: 'iterm2', name: 'iTerm2', paths: ['/Applications/iTerm.app', path.posix.join(home, 'Applications', 'iTerm.app')] },
|
|
173
|
+
{ id: 'ghostty', name: 'Ghostty', bin: 'ghostty', paths: ['/Applications/Ghostty.app', path.posix.join(home, 'Applications', 'Ghostty.app')] },
|
|
174
|
+
{ id: 'warp', name: 'Warp', paths: ['/Applications/Warp.app', path.posix.join(home, 'Applications', 'Warp.app')] },
|
|
175
|
+
{ id: 'cmux', name: 'cmux', bin: 'cmux', paths: ['/Applications/cmux.app', path.posix.join(home, 'Applications', 'cmux.app')] },
|
|
176
|
+
{ id: 'wezterm', name: 'WezTerm', bin: 'wezterm', paths: ['/Applications/WezTerm.app', path.posix.join(home, 'Applications', 'WezTerm.app')] },
|
|
177
|
+
{ id: 'kitty', name: 'Kitty', bin: 'kitty', paths: ['/Applications/kitty.app', path.posix.join(home, 'Applications', 'kitty.app')] },
|
|
178
|
+
{ id: 'alacritty', name: 'Alacritty', bin: 'alacritty', paths: ['/Applications/Alacritty.app', path.posix.join(home, 'Applications', 'Alacritty.app')] }
|
|
179
|
+
];
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const TERMINAL_CATALOG = Object.freeze([
|
|
183
|
+
'terminal', 'iterm2', 'ghostty', 'warp', 'kitty', 'wezterm', 'cmux',
|
|
184
|
+
'alacritty', 'rex', 'wt', 'powershell', 'cmd', 'wsl'
|
|
185
|
+
]);
|
|
186
|
+
|
|
187
|
+
function detectRexAppPath(options = {}) {
|
|
188
|
+
const existsSync = options.existsSync || fs.existsSync;
|
|
189
|
+
const home = options.homeDir || os.homedir();
|
|
190
|
+
const candidates = [
|
|
191
|
+
'/Applications/Rex.app',
|
|
192
|
+
'/Applications/Rex Beta.app',
|
|
193
|
+
path.posix.join(home, 'Applications', 'Rex.app'),
|
|
194
|
+
path.posix.join(home, 'Applications', 'Rex Beta.app')
|
|
195
|
+
];
|
|
196
|
+
for (const p of candidates) {
|
|
197
|
+
try {
|
|
198
|
+
if (existsSync(p)) return p;
|
|
199
|
+
} catch {}
|
|
200
|
+
}
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function getWindowsHelperPath() {
|
|
205
|
+
return path.resolve(__dirname, '..', 'scripts', 'cli-window-helper.cs');
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function detectAvailableTerminals(options = {}) {
|
|
209
|
+
const platform = options.platform || process.platform;
|
|
210
|
+
const existsSync = options.existsSync || fs.existsSync;
|
|
211
|
+
const found = [];
|
|
212
|
+
|
|
213
|
+
if (platform === 'darwin') {
|
|
214
|
+
const apps = getDarwinTerminalSpecs(options);
|
|
215
|
+
for (const a of apps) {
|
|
216
|
+
const binFound = a.bin ? findInPath(a.bin, options) : null;
|
|
217
|
+
const appFound = (a.paths || []).find((p) => {
|
|
218
|
+
try { return existsSync(p); } catch { return false; }
|
|
219
|
+
}) || null;
|
|
220
|
+
if (appFound || binFound) {
|
|
221
|
+
found.push({ id: a.id, name: a.name, path: appFound || binFound, available: true });
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
for (const mux of ['rex', 'tmux']) {
|
|
225
|
+
const p = findInPath(mux, options);
|
|
226
|
+
if (p) found.push({ id: mux, name: mux, path: p, available: true, isMux: true });
|
|
227
|
+
}
|
|
228
|
+
return found;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
if (platform === 'win32') {
|
|
232
|
+
const wt = findInPath('wt.exe', options);
|
|
233
|
+
const pwsh = findInPath('pwsh.exe', options) || findInPath('powershell.exe', options);
|
|
234
|
+
const cmd = findInPath('cmd.exe', options) || 'cmd.exe';
|
|
235
|
+
if (wt) found.push({ id: 'wt', name: 'Windows Terminal', path: wt, available: true });
|
|
236
|
+
if (pwsh) found.push({ id: 'powershell', name: 'PowerShell', path: pwsh, available: true });
|
|
237
|
+
found.push({ id: 'cmd', name: 'Command Prompt', path: cmd, available: true });
|
|
238
|
+
return found;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
for (const bin of ['wezterm', 'kitty', 'alacritty', 'gnome-terminal', 'konsole', 'xfce4-terminal', 'xterm', 'tmux', 'rex']) {
|
|
242
|
+
const p = findInPath(bin, options);
|
|
243
|
+
if (p) found.push({ id: bin, name: bin, path: p, available: true });
|
|
244
|
+
}
|
|
245
|
+
return found;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
function detectTerminalPath(terminalApp = 'auto', options = {}) {
|
|
249
|
+
const platform = options.platform || process.platform;
|
|
250
|
+
const existsSync = options.existsSync || fs.existsSync;
|
|
251
|
+
const env = options.env || process.env;
|
|
252
|
+
const target = String(terminalApp || 'auto').trim().toLowerCase() || 'auto';
|
|
253
|
+
const label = TERMINAL_LABELS[target] || target;
|
|
254
|
+
|
|
255
|
+
if (target === 'auto') {
|
|
256
|
+
const avail = detectAvailableTerminals(options);
|
|
257
|
+
const first = avail[0] || null;
|
|
258
|
+
if (first && first.path) {
|
|
259
|
+
return {
|
|
260
|
+
ok: true,
|
|
261
|
+
found: true,
|
|
262
|
+
terminalApp: 'auto',
|
|
263
|
+
resolvedTerminalId: first.id,
|
|
264
|
+
name: first.name || TERMINAL_LABELS[first.id] || first.id,
|
|
265
|
+
path: first.path,
|
|
266
|
+
message: `自动探测到 ${first.name || first.id}`
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
return {
|
|
270
|
+
ok: true,
|
|
271
|
+
found: false,
|
|
272
|
+
terminalApp: 'auto',
|
|
273
|
+
resolvedTerminalId: 'auto',
|
|
274
|
+
name: label,
|
|
275
|
+
path: '',
|
|
276
|
+
error: '未检测到可用终端程序路径,请手动输入路径或点击「浏览选择」'
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
let detectedPath = null;
|
|
281
|
+
if (platform === 'darwin') {
|
|
282
|
+
if (target === 'rex' || target === 'tmux') {
|
|
283
|
+
detectedPath = findInPath(target, options);
|
|
284
|
+
} else {
|
|
285
|
+
const spec = getDarwinTerminalSpecs(options).find((a) => a.id === target);
|
|
286
|
+
if (spec) {
|
|
287
|
+
const appFound = (spec.paths || []).find((p) => {
|
|
288
|
+
try { return existsSync(p); } catch { return false; }
|
|
289
|
+
}) || null;
|
|
290
|
+
const binFound = spec.bin ? findInPath(spec.bin, options) : null;
|
|
291
|
+
detectedPath = appFound || binFound;
|
|
292
|
+
} else {
|
|
293
|
+
detectedPath = findInPath(target, options);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
} else if (platform === 'win32') {
|
|
297
|
+
if (target === 'wt') {
|
|
298
|
+
detectedPath = findInPath('wt.exe', options);
|
|
299
|
+
if (!detectedPath && env.LOCALAPPDATA) {
|
|
300
|
+
const cand = path.win32.join(env.LOCALAPPDATA, 'Microsoft', 'WindowsApps', 'wt.exe');
|
|
301
|
+
try { if (existsSync(cand)) detectedPath = cand; } catch {}
|
|
302
|
+
}
|
|
303
|
+
} else if (target === 'powershell') {
|
|
304
|
+
detectedPath = findInPath('pwsh.exe', options) || findInPath('powershell.exe', options);
|
|
305
|
+
} else if (target === 'cmd') {
|
|
306
|
+
detectedPath = findInPath('cmd.exe', options);
|
|
307
|
+
} else if (target === 'wsl') {
|
|
308
|
+
detectedPath = findInPath('wsl.exe', options);
|
|
309
|
+
} else {
|
|
310
|
+
detectedPath = findInPath(`${target}.exe`, options) || findInPath(target, options);
|
|
311
|
+
}
|
|
312
|
+
} else {
|
|
313
|
+
detectedPath = findInPath(target, options);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
if (detectedPath) {
|
|
317
|
+
return {
|
|
318
|
+
ok: true,
|
|
319
|
+
found: true,
|
|
320
|
+
terminalApp: target,
|
|
321
|
+
resolvedTerminalId: target,
|
|
322
|
+
name: label,
|
|
323
|
+
path: detectedPath,
|
|
324
|
+
message: `已检测到 ${label}`
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
return {
|
|
329
|
+
ok: true,
|
|
330
|
+
found: false,
|
|
331
|
+
terminalApp: target,
|
|
332
|
+
resolvedTerminalId: target,
|
|
333
|
+
name: label,
|
|
334
|
+
path: '',
|
|
335
|
+
error: `未检测到 ${label} 的程序路径,请手动输入路径或点击「浏览选择」`
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function verifyTerminalPath(customPath, options = {}) {
|
|
340
|
+
const existsSync = options.existsSync || fs.existsSync;
|
|
341
|
+
const trimmed = String(customPath || '').trim();
|
|
342
|
+
if (!trimmed) {
|
|
343
|
+
return {
|
|
344
|
+
ok: true,
|
|
345
|
+
found: false,
|
|
346
|
+
path: '',
|
|
347
|
+
error: '程序路径为空,请输入路径或点击「浏览选择」'
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
let exists = false;
|
|
351
|
+
try {
|
|
352
|
+
exists = Boolean(existsSync(trimmed));
|
|
353
|
+
} catch {
|
|
354
|
+
exists = false;
|
|
355
|
+
}
|
|
356
|
+
if (!exists) {
|
|
357
|
+
return {
|
|
358
|
+
ok: true,
|
|
359
|
+
found: false,
|
|
360
|
+
path: trimmed,
|
|
361
|
+
error: `路径不存在或不可访问:${trimmed},请重新输入或点击「浏览选择」`
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
return {
|
|
365
|
+
ok: true,
|
|
366
|
+
found: true,
|
|
367
|
+
path: trimmed,
|
|
368
|
+
message: '路径有效'
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function listSshMuxHosts(options = {}) {
|
|
373
|
+
const readFileSync = options.readFileSync || fs.readFileSync;
|
|
374
|
+
const existsSync = options.existsSync || fs.existsSync;
|
|
375
|
+
const configPath = options.sshConfigPath || path.join(options.homeDir || os.homedir(), '.ssh', 'config');
|
|
376
|
+
try {
|
|
377
|
+
if (!existsSync(configPath)) return [];
|
|
378
|
+
} catch {
|
|
379
|
+
return [];
|
|
380
|
+
}
|
|
381
|
+
let content = '';
|
|
382
|
+
try {
|
|
383
|
+
content = String(readFileSync(configPath, 'utf8') || '');
|
|
384
|
+
} catch {
|
|
385
|
+
return [];
|
|
386
|
+
}
|
|
387
|
+
const blocks = [];
|
|
388
|
+
let current = null;
|
|
389
|
+
for (const rawLine of content.split(/\r?\n/)) {
|
|
390
|
+
const line = rawLine.replace(/#.*$/, '').trim();
|
|
391
|
+
if (!line) continue;
|
|
392
|
+
const match = line.match(/^([A-Za-z]+)\s+(.+)$/);
|
|
393
|
+
if (!match) continue;
|
|
394
|
+
const key = match[1].toLowerCase();
|
|
395
|
+
const rest = match[2].trim();
|
|
396
|
+
if (key === 'host') {
|
|
397
|
+
const patterns = rest.split(/\s+/).filter(Boolean);
|
|
398
|
+
current = { patterns, user: '', hostname: '' };
|
|
399
|
+
blocks.push(current);
|
|
400
|
+
} else if (current && key === 'user') {
|
|
401
|
+
current.user = rest;
|
|
402
|
+
} else if (current && key === 'hostname') {
|
|
403
|
+
current.hostname = rest;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
const out = [];
|
|
408
|
+
const seen = new Set();
|
|
409
|
+
for (const b of blocks) {
|
|
410
|
+
for (const pat of b.patterns) {
|
|
411
|
+
if (!pat || /[*?!]/.test(pat)) continue;
|
|
412
|
+
const lower = pat.toLowerCase();
|
|
413
|
+
if (lower === 'localhost' || lower === '127.0.0.1' || seen.has(pat)) continue;
|
|
414
|
+
if (sanitizeMuxHost(pat) === null) continue;
|
|
415
|
+
seen.add(pat);
|
|
416
|
+
const descParts = [];
|
|
417
|
+
if (b.user && b.hostname) descParts.push(`${b.user}@${b.hostname}`);
|
|
418
|
+
else if (b.hostname) descParts.push(b.hostname);
|
|
419
|
+
else if (b.user) descParts.push(b.user);
|
|
420
|
+
out.push({
|
|
421
|
+
value: pat,
|
|
422
|
+
label: pat,
|
|
423
|
+
description: descParts.join(' ')
|
|
424
|
+
});
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return out;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function buildLaunchPlan(options = {}) {
|
|
431
|
+
const platform = options.platform || process.platform;
|
|
432
|
+
const terminalApp = String(options.terminalApp || 'auto').toLowerCase();
|
|
433
|
+
const customTerminalPath = typeof options.customTerminalPath === 'string' ? options.customTerminalPath.trim() : '';
|
|
434
|
+
const cwd = normalizeWorkspacePath(options.cwd, { platform })
|
|
435
|
+
|| normalizeWorkspacePath(process.cwd(), { platform })
|
|
436
|
+
|| process.cwd();
|
|
437
|
+
const workspaceSource = typeof options.workspaceSource === 'string' ? options.workspaceSource : '';
|
|
438
|
+
const cliBin = options.cliBin || 'agy';
|
|
439
|
+
const rawCommand = typeof options.rawCommand === 'string' ? options.rawCommand.trim() : '';
|
|
440
|
+
const isCustomCommand = rawCommand.length > 0;
|
|
441
|
+
const extraArgs = Array.isArray(options.commandArgs) ? options.commandArgs.map(String) : [];
|
|
442
|
+
|
|
443
|
+
const cliArgs = [];
|
|
444
|
+
if (!isCustomCommand) {
|
|
445
|
+
cliArgs.push(...resolvePermissionArgs(options));
|
|
446
|
+
if (options.cliDefaultModel) cliArgs.push('--model', String(options.cliDefaultModel));
|
|
447
|
+
cliArgs.push(...extraArgs);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
let cleanMux = '';
|
|
451
|
+
if (options.muxHost) {
|
|
452
|
+
const sanitized = sanitizeMuxHost(options.muxHost);
|
|
453
|
+
if (sanitized === null) {
|
|
454
|
+
throw new Error(`Unsafe muxHost rejected: ${String(options.muxHost)}`);
|
|
455
|
+
}
|
|
456
|
+
cleanMux = sanitized;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const env = { ...(options.env || {}) };
|
|
460
|
+
delete env.ELECTRON_RUN_AS_NODE;
|
|
461
|
+
delete env.NO_COLOR;
|
|
462
|
+
env.TERM = env.TERM || 'xterm-256color';
|
|
463
|
+
env.COLORTERM = env.COLORTERM || 'truecolor';
|
|
464
|
+
|
|
465
|
+
const attachMeta = (plan) => (workspaceSource ? { ...plan, workspaceSource } : plan);
|
|
466
|
+
|
|
467
|
+
if (platform === 'win32') {
|
|
468
|
+
const cmdStatement = isCustomCommand
|
|
469
|
+
? rawCommand
|
|
470
|
+
: `& '${escapePowerShellSingleQuoted(cliBin)}' ${cliArgs.map((a) => `'${escapePowerShellSingleQuoted(a)}'`).join(' ')}`.trim();
|
|
471
|
+
const psCmdParts = [
|
|
472
|
+
`Set-Location -LiteralPath '${escapePowerShellSingleQuoted(cwd)}'`,
|
|
473
|
+
cmdStatement
|
|
474
|
+
];
|
|
475
|
+
const commandLine = psCmdParts.join('; ');
|
|
476
|
+
const targetTerm = terminalApp === 'auto' ? 'wt' : terminalApp;
|
|
477
|
+
if (targetTerm === 'wsl') {
|
|
478
|
+
const wslCwd = toWslPath(cwd);
|
|
479
|
+
return attachMeta({
|
|
480
|
+
ok: true,
|
|
481
|
+
platform,
|
|
482
|
+
terminalId: 'wsl',
|
|
483
|
+
executable: customTerminalPath || 'wsl.exe',
|
|
484
|
+
args: isCustomCommand
|
|
485
|
+
? ['--cd', wslCwd, '--', 'sh', '-lc', rawCommand]
|
|
486
|
+
: ['--cd', wslCwd, '--', cliBin, ...cliArgs],
|
|
487
|
+
env,
|
|
488
|
+
cwd: wslCwd,
|
|
489
|
+
muxHost: cleanMux,
|
|
490
|
+
isCustomCommand,
|
|
491
|
+
...(isCustomCommand ? { rawCommand } : {}),
|
|
492
|
+
windowsHelperPath: getWindowsHelperPath()
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
if (targetTerm === 'wt') {
|
|
496
|
+
return attachMeta({
|
|
497
|
+
ok: true,
|
|
498
|
+
platform,
|
|
499
|
+
terminalId: 'wt',
|
|
500
|
+
executable: customTerminalPath || 'wt.exe',
|
|
501
|
+
args: ['-d', cwd, 'powershell.exe', '-NoExit', '-Command', commandLine],
|
|
502
|
+
env,
|
|
503
|
+
cwd,
|
|
504
|
+
muxHost: cleanMux,
|
|
505
|
+
isCustomCommand,
|
|
506
|
+
...(isCustomCommand ? { rawCommand } : {}),
|
|
507
|
+
windowsHelperPath: getWindowsHelperPath()
|
|
508
|
+
});
|
|
509
|
+
}
|
|
510
|
+
return attachMeta({
|
|
511
|
+
ok: true,
|
|
512
|
+
platform,
|
|
513
|
+
terminalId: targetTerm === 'cmd' ? 'cmd' : 'powershell',
|
|
514
|
+
executable: customTerminalPath || (targetTerm === 'cmd' ? 'cmd.exe' : 'powershell.exe'),
|
|
515
|
+
args: targetTerm === 'cmd' ? ['/K', `cd /d "${cwd}" && ${isCustomCommand ? rawCommand : [cliBin, ...cliArgs].join(' ')}`] : ['-NoExit', '-Command', commandLine],
|
|
516
|
+
env,
|
|
517
|
+
cwd,
|
|
518
|
+
muxHost: cleanMux,
|
|
519
|
+
isCustomCommand,
|
|
520
|
+
...(isCustomCommand ? { rawCommand } : {}),
|
|
521
|
+
windowsHelperPath: getWindowsHelperPath()
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const posixCmd = isCustomCommand
|
|
526
|
+
? rawCommand
|
|
527
|
+
: [escapePosixArg(cliBin), ...cliArgs.map(escapePosixArg)].join(' ');
|
|
528
|
+
const fullShellCmd = `cd ${escapePosixArg(cwd)} && ${posixCmd}`;
|
|
529
|
+
const wrappedCmd = cleanMux
|
|
530
|
+
? `ssh -t ${escapePosixArg(cleanMux)} ${escapePosixArg(fullShellCmd)}`
|
|
531
|
+
: fullShellCmd;
|
|
532
|
+
|
|
533
|
+
let chosenTerm = terminalApp;
|
|
534
|
+
if (chosenTerm === 'auto') {
|
|
535
|
+
chosenTerm = platform === 'darwin' ? 'terminal' : 'xterm';
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
const isAppBundle = customTerminalPath.toLowerCase().endsWith('.app');
|
|
539
|
+
|
|
540
|
+
if (chosenTerm === 'rex') {
|
|
541
|
+
const rexArgs = cleanMux
|
|
542
|
+
? ['-S', cleanMux, 'run', '--interactive', '--keep-open', '-c', cwd, '--', 'sh', '-lc', fullShellCmd]
|
|
543
|
+
: ['run', '--interactive', '--keep-open', '-c', cwd, '--', 'sh', '-lc', fullShellCmd];
|
|
544
|
+
const activateApp = platform === 'darwin' ? detectRexAppPath(options) : null;
|
|
545
|
+
return attachMeta({
|
|
546
|
+
ok: true,
|
|
547
|
+
platform,
|
|
548
|
+
terminalId: 'rex',
|
|
549
|
+
executable: (!isAppBundle && customTerminalPath) ? customTerminalPath : 'rex',
|
|
550
|
+
args: rexArgs,
|
|
551
|
+
env,
|
|
552
|
+
cwd,
|
|
553
|
+
muxHost: cleanMux,
|
|
554
|
+
isCustomCommand,
|
|
555
|
+
...(activateApp ? { activateApp } : {}),
|
|
556
|
+
...(isCustomCommand ? { rawCommand } : {})
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
if (chosenTerm === 'wezterm') {
|
|
561
|
+
const wezArgs = isCustomCommand
|
|
562
|
+
? (cleanMux ? ['cli', 'spawn', '--domain-name', cleanMux, '--cwd', cwd, '--', 'sh', '-lc', rawCommand] : ['start', '--cwd', cwd, '--', 'sh', '-lc', rawCommand])
|
|
563
|
+
: (cleanMux ? ['cli', 'spawn', '--domain-name', cleanMux, '--cwd', cwd, '--', cliBin, ...cliArgs] : ['start', '--cwd', cwd, '--', cliBin, ...cliArgs]);
|
|
564
|
+
return attachMeta({
|
|
565
|
+
ok: true,
|
|
566
|
+
platform,
|
|
567
|
+
terminalId: 'wezterm',
|
|
568
|
+
executable: (!isAppBundle && customTerminalPath) ? customTerminalPath : 'wezterm',
|
|
569
|
+
args: wezArgs,
|
|
570
|
+
env,
|
|
571
|
+
cwd,
|
|
572
|
+
muxHost: cleanMux,
|
|
573
|
+
isCustomCommand,
|
|
574
|
+
...(isCustomCommand ? { rawCommand } : {})
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
if (chosenTerm === 'tmux') {
|
|
579
|
+
return attachMeta({
|
|
580
|
+
ok: true,
|
|
581
|
+
platform,
|
|
582
|
+
terminalId: 'tmux',
|
|
583
|
+
executable: (!isAppBundle && customTerminalPath) ? customTerminalPath : 'tmux',
|
|
584
|
+
args: ['new-window', '-c', cwd, wrappedCmd],
|
|
585
|
+
env,
|
|
586
|
+
cwd,
|
|
587
|
+
muxHost: cleanMux,
|
|
588
|
+
isCustomCommand,
|
|
589
|
+
...(isCustomCommand ? { rawCommand } : {})
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (platform === 'darwin') {
|
|
594
|
+
if (chosenTerm === 'iterm2') {
|
|
595
|
+
if (customTerminalPath && !isAppBundle) {
|
|
596
|
+
return attachMeta({
|
|
597
|
+
ok: true,
|
|
598
|
+
platform,
|
|
599
|
+
terminalId: 'iterm2',
|
|
600
|
+
executable: customTerminalPath,
|
|
601
|
+
args: ['-e', 'zsh', '-lc', wrappedCmd],
|
|
602
|
+
env,
|
|
603
|
+
cwd,
|
|
604
|
+
muxHost: cleanMux,
|
|
605
|
+
isCustomCommand,
|
|
606
|
+
...(isCustomCommand ? { rawCommand } : {})
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
const appRef = isAppBundle ? customTerminalPath : 'iTerm';
|
|
610
|
+
return attachMeta({
|
|
611
|
+
ok: true,
|
|
612
|
+
platform,
|
|
613
|
+
terminalId: 'iterm2',
|
|
614
|
+
executable: 'osascript',
|
|
615
|
+
args: [
|
|
616
|
+
'-e', `tell application "${escapeAppleScriptString(appRef)}" to activate`,
|
|
617
|
+
'-e', `tell application "${escapeAppleScriptString(appRef)}" to create window with default profile command "${escapeAppleScriptString(wrappedCmd)}"`
|
|
618
|
+
],
|
|
619
|
+
env,
|
|
620
|
+
cwd,
|
|
621
|
+
muxHost: cleanMux,
|
|
622
|
+
isCustomCommand,
|
|
623
|
+
...(isCustomCommand ? { rawCommand } : {})
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
if (['ghostty', 'warp', 'kitty', 'alacritty', 'cmux'].includes(chosenTerm)) {
|
|
627
|
+
if (customTerminalPath && !isAppBundle) {
|
|
628
|
+
return attachMeta({
|
|
629
|
+
ok: true,
|
|
630
|
+
platform,
|
|
631
|
+
terminalId: chosenTerm,
|
|
632
|
+
executable: customTerminalPath,
|
|
633
|
+
args: ['-e', 'zsh', '-lc', wrappedCmd],
|
|
634
|
+
env,
|
|
635
|
+
cwd,
|
|
636
|
+
muxHost: cleanMux,
|
|
637
|
+
isCustomCommand,
|
|
638
|
+
...(isCustomCommand ? { rawCommand } : {})
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
const defaultAppMap = {
|
|
642
|
+
ghostty: 'Ghostty',
|
|
643
|
+
warp: 'Warp',
|
|
644
|
+
kitty: 'kitty',
|
|
645
|
+
alacritty: 'Alacritty',
|
|
646
|
+
cmux: 'cmux'
|
|
647
|
+
};
|
|
648
|
+
const appTarget = isAppBundle ? customTerminalPath : (defaultAppMap[chosenTerm] || chosenTerm);
|
|
649
|
+
return attachMeta({
|
|
650
|
+
ok: true,
|
|
651
|
+
platform,
|
|
652
|
+
terminalId: chosenTerm,
|
|
653
|
+
executable: 'open',
|
|
654
|
+
args: ['-na', appTarget, '--args', '-e', 'zsh', '-lc', wrappedCmd],
|
|
655
|
+
env,
|
|
656
|
+
cwd,
|
|
657
|
+
muxHost: cleanMux,
|
|
658
|
+
isCustomCommand,
|
|
659
|
+
...(isCustomCommand ? { rawCommand } : {})
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
if (customTerminalPath && !isAppBundle) {
|
|
663
|
+
return attachMeta({
|
|
664
|
+
ok: true,
|
|
665
|
+
platform,
|
|
666
|
+
terminalId: chosenTerm,
|
|
667
|
+
executable: customTerminalPath,
|
|
668
|
+
args: ['-e', 'zsh', '-lc', wrappedCmd],
|
|
669
|
+
env,
|
|
670
|
+
cwd,
|
|
671
|
+
muxHost: cleanMux,
|
|
672
|
+
isCustomCommand,
|
|
673
|
+
...(isCustomCommand ? { rawCommand } : {})
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
const termAppRef = isAppBundle ? customTerminalPath : 'Terminal';
|
|
677
|
+
return attachMeta({
|
|
678
|
+
ok: true,
|
|
679
|
+
platform,
|
|
680
|
+
terminalId: 'terminal',
|
|
681
|
+
executable: 'osascript',
|
|
682
|
+
args: [
|
|
683
|
+
'-e', `tell application "${escapeAppleScriptString(termAppRef)}" to activate`,
|
|
684
|
+
'-e', `tell application "${escapeAppleScriptString(termAppRef)}" to do script "${escapeAppleScriptString(wrappedCmd)}"`
|
|
685
|
+
],
|
|
686
|
+
env,
|
|
687
|
+
cwd,
|
|
688
|
+
muxHost: cleanMux,
|
|
689
|
+
isCustomCommand,
|
|
690
|
+
...(isCustomCommand ? { rawCommand } : {})
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
return attachMeta({
|
|
695
|
+
ok: true,
|
|
696
|
+
platform,
|
|
697
|
+
terminalId: chosenTerm,
|
|
698
|
+
executable: customTerminalPath || chosenTerm,
|
|
699
|
+
args: ['-e', 'sh', '-lc', wrappedCmd],
|
|
700
|
+
env,
|
|
701
|
+
cwd,
|
|
702
|
+
muxHost: cleanMux,
|
|
703
|
+
isCustomCommand,
|
|
704
|
+
...(isCustomCommand ? { rawCommand } : {})
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
function normalizeWorkspacePath(raw, options = {}) {
|
|
709
|
+
if (typeof raw !== 'string') return null;
|
|
710
|
+
let str = raw.trim();
|
|
711
|
+
if (!str || str.includes('\0')) return null;
|
|
712
|
+
|
|
713
|
+
const platform = options.platform || process.platform;
|
|
714
|
+
const homeDir = options.homeDir || os.homedir();
|
|
715
|
+
|
|
716
|
+
if (/^file:\/\//i.test(str)) {
|
|
717
|
+
try {
|
|
718
|
+
const parsedUrl = new URL(str);
|
|
719
|
+
const isWinFileUri = /^\/[A-Za-z]:(?:\/|$)/.test(parsedUrl.pathname);
|
|
720
|
+
if (isWinFileUri) {
|
|
721
|
+
let winRaw = decodeURIComponent(parsedUrl.pathname.slice(1)).replace(/\//g, '\\');
|
|
722
|
+
if (/^[A-Za-z]:$/.test(winRaw)) winRaw += '\\';
|
|
723
|
+
const normWin = path.win32.normalize(winRaw);
|
|
724
|
+
return /^[A-Za-z]:\\$/.test(normWin) ? normWin : normWin.replace(/[\\/]+$/, '');
|
|
725
|
+
}
|
|
726
|
+
if (platform !== 'win32') {
|
|
727
|
+
try {
|
|
728
|
+
const nativePath = fileURLToPath(str);
|
|
729
|
+
const normPosix = path.posix.normalize(nativePath);
|
|
730
|
+
return normPosix === '/' ? '/' : normPosix.replace(/\/+$/, '');
|
|
731
|
+
} catch {}
|
|
732
|
+
}
|
|
733
|
+
str = decodeURIComponent(parsedUrl.pathname || '');
|
|
734
|
+
} catch {
|
|
735
|
+
return null;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
if (!str) return null;
|
|
740
|
+
|
|
741
|
+
if (str === '~' || str.startsWith('~/') || str.startsWith('~\\')) {
|
|
742
|
+
const rest = str.slice(1).replace(/^[\\/]+/, '');
|
|
743
|
+
const isWinHome = platform === 'win32' || /^[A-Za-z]:[\\/]/.test(homeDir);
|
|
744
|
+
const joinMod = isWinHome ? path.win32 : path.posix;
|
|
745
|
+
str = rest ? joinMod.join(homeDir, rest) : homeDir;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
if (/^[A-Za-z]:(?:[\\/]|$)/.test(str) || /^\\\\[^\\]/.test(str)) {
|
|
749
|
+
const rawWin = /^[A-Za-z]:$/.test(str) ? `${str}\\` : str;
|
|
750
|
+
const normWin = path.win32.normalize(rawWin);
|
|
751
|
+
return /^[A-Za-z]:\\$/.test(normWin) ? normWin : normWin.replace(/[\\/]+$/, '');
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
if (str.startsWith('/')) {
|
|
755
|
+
const normPosix = path.posix.normalize(str);
|
|
756
|
+
return normPosix === '/' ? '/' : normPosix.replace(/\/+$/, '');
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
if (platform === 'win32') {
|
|
760
|
+
const resolvedWin = path.win32.resolve(str);
|
|
761
|
+
return /^[A-Za-z]:\\$/.test(resolvedWin) ? resolvedWin : resolvedWin.replace(/[\\/]+$/, '');
|
|
762
|
+
}
|
|
763
|
+
const resolvedPosix = path.resolve(str);
|
|
764
|
+
return resolvedPosix === '/' ? '/' : resolvedPosix.replace(/\/+$/, '');
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
function extractWorkspacesFromTrajectory(entry, options = {}) {
|
|
768
|
+
if (!entry || typeof entry !== 'object') return [];
|
|
769
|
+
const rawList = [];
|
|
770
|
+
const collectWorkspaceArray = (arr) => {
|
|
771
|
+
if (!Array.isArray(arr)) return;
|
|
772
|
+
for (const w of arr) {
|
|
773
|
+
if (!w || typeof w !== 'object') continue;
|
|
774
|
+
if (w.workspaceFolderAbsoluteUri) rawList.push(w.workspaceFolderAbsoluteUri);
|
|
775
|
+
if (w.gitRootAbsoluteUri) rawList.push(w.gitRootAbsoluteUri);
|
|
776
|
+
if (w.workspacePath) rawList.push(w.workspacePath);
|
|
777
|
+
if (w.workspaceUri) rawList.push(w.workspaceUri);
|
|
778
|
+
}
|
|
779
|
+
};
|
|
780
|
+
|
|
781
|
+
collectWorkspaceArray(entry.workspaces);
|
|
782
|
+
collectWorkspaceArray(entry.trajectoryMetadata?.workspaces);
|
|
783
|
+
if (Array.isArray(entry.trajectoryMetadata?.workspaceUris)) {
|
|
784
|
+
rawList.push(...entry.trajectoryMetadata.workspaceUris);
|
|
785
|
+
}
|
|
786
|
+
collectWorkspaceArray(entry.trajectory?.metadata?.workspaces);
|
|
787
|
+
if (Array.isArray(entry.trajectory?.metadata?.workspaceUris)) {
|
|
788
|
+
rawList.push(...entry.trajectory.metadata.workspaceUris);
|
|
789
|
+
}
|
|
790
|
+
for (const k of ['workspacePath', 'workspaceUri', 'cwd', 'rootPath']) {
|
|
791
|
+
if (entry[k]) rawList.push(entry[k]);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
const out = [];
|
|
795
|
+
const seen = new Set();
|
|
796
|
+
for (const raw of rawList) {
|
|
797
|
+
const norm = normalizeWorkspacePath(String(raw || ''), options);
|
|
798
|
+
if (norm && !seen.has(norm)) {
|
|
799
|
+
seen.add(norm);
|
|
800
|
+
out.push(norm);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
return out;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
const GENERIC_HINT_TOKENS = new Set([
|
|
807
|
+
'antigravity', 'settings', '设置', 'agy-daddy', 'cli', 'terminal', 'new chat', 'untitled'
|
|
808
|
+
]);
|
|
809
|
+
|
|
810
|
+
function extractWorkspaceNameTokens(workspaceHints = {}) {
|
|
811
|
+
const hints = workspaceHints && typeof workspaceHints === 'object' ? workspaceHints : {};
|
|
812
|
+
const rawTokens = [];
|
|
813
|
+
const pushToken = (val) => {
|
|
814
|
+
const s = String(val || '').trim();
|
|
815
|
+
if (!s || s.length > 120) return;
|
|
816
|
+
if (!rawTokens.includes(s)) rawTokens.push(s);
|
|
817
|
+
};
|
|
818
|
+
if (Array.isArray(hints.workspaceNameHints)) {
|
|
819
|
+
for (const t of hints.workspaceNameHints) pushToken(t);
|
|
820
|
+
}
|
|
821
|
+
if (Array.isArray(hints.titlebarTexts)) {
|
|
822
|
+
for (const t of hints.titlebarTexts) pushToken(t);
|
|
823
|
+
}
|
|
824
|
+
if (typeof hints.pageTitle === 'string' && hints.pageTitle.trim()) {
|
|
825
|
+
for (const part of hints.pageTitle.split(/\s+[—–\-|·]\s+|\s+-\s+/)) {
|
|
826
|
+
pushToken(part);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
return rawTokens.filter((t) => !GENERIC_HINT_TOKENS.has(t.toLowerCase()));
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
function pathBasenameCrossPlatform(p) {
|
|
833
|
+
const str = String(p || '');
|
|
834
|
+
const idx = Math.max(str.lastIndexOf('/'), str.lastIndexOf('\\'));
|
|
835
|
+
return idx >= 0 ? str.slice(idx + 1) : str;
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function pathDirnameCrossPlatform(p) {
|
|
839
|
+
const str = String(p || '');
|
|
840
|
+
if (/^[A-Za-z]:\\/.test(str) || str.includes('\\')) return path.win32.dirname(str);
|
|
841
|
+
return path.posix.dirname(str);
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
function resolveLocalDirectoryCandidate(candidatePath, options = {}) {
|
|
845
|
+
const existsSync = options.existsSync || fs.existsSync;
|
|
846
|
+
const statSync = options.statSync || fs.statSync;
|
|
847
|
+
try {
|
|
848
|
+
if (!existsSync(candidatePath)) return null;
|
|
849
|
+
if (typeof statSync === 'function') {
|
|
850
|
+
const st = statSync(candidatePath);
|
|
851
|
+
if (st && typeof st.isFile === 'function' && st.isFile()) {
|
|
852
|
+
return pathDirnameCrossPlatform(candidatePath);
|
|
853
|
+
}
|
|
854
|
+
if (st && typeof st.isDirectory === 'function' && !st.isDirectory()) {
|
|
855
|
+
return null;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
return candidatePath;
|
|
859
|
+
} catch {
|
|
860
|
+
return null;
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
function pickBestCandidatePath(candidates, nameHints = [], options = {}) {
|
|
865
|
+
if (!Array.isArray(candidates) || candidates.length === 0) return null;
|
|
866
|
+
const localOnly = options.localOnly !== false;
|
|
867
|
+
let pool = candidates;
|
|
868
|
+
if (localOnly) {
|
|
869
|
+
const existing = [];
|
|
870
|
+
for (const c of candidates) {
|
|
871
|
+
const resolved = resolveLocalDirectoryCandidate(c, options);
|
|
872
|
+
if (resolved && !existing.includes(resolved)) existing.push(resolved);
|
|
873
|
+
}
|
|
874
|
+
if (existing.length > 0) pool = existing;
|
|
875
|
+
}
|
|
876
|
+
if (pool.length > 1 && Array.isArray(nameHints) && nameHints.length > 0) {
|
|
877
|
+
const lowerHints = new Set(nameHints.map((h) => String(h || '').trim().toLowerCase()).filter(Boolean));
|
|
878
|
+
for (const cand of pool) {
|
|
879
|
+
const base = pathBasenameCrossPlatform(cand).toLowerCase();
|
|
880
|
+
if (base && lowerHints.has(base)) {
|
|
881
|
+
return cand;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
return pool[0] || null;
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
function getTrajectoryTimestamps(summary = {}) {
|
|
889
|
+
const viewTs = Date.parse(summary?.annotations?.lastUserViewTime || 0) || 0;
|
|
890
|
+
const modTs = Date.parse(summary?.lastModifiedTime || summary?.updatedAt || summary?.createdTime || 0) || 0;
|
|
891
|
+
return { viewTs, modTs };
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
function resolveWorkspaceFromTrajectories(summaries, options = {}) {
|
|
895
|
+
const hints = options.workspaceHints && typeof options.workspaceHints === 'object' ? options.workspaceHints : {};
|
|
896
|
+
const localOnly = options.localOnly !== false;
|
|
897
|
+
const nameHints = extractWorkspaceNameTokens(hints);
|
|
898
|
+
|
|
899
|
+
// 1. DOM 显式绝对路径
|
|
900
|
+
if (Array.isArray(hints.domPaths) && hints.domPaths.length > 0) {
|
|
901
|
+
const domCandidates = [];
|
|
902
|
+
for (const raw of hints.domPaths) {
|
|
903
|
+
const norm = normalizeWorkspacePath(String(raw || ''), options);
|
|
904
|
+
if (!norm) continue;
|
|
905
|
+
if (localOnly) {
|
|
906
|
+
const verified = resolveLocalDirectoryCandidate(norm, options);
|
|
907
|
+
if (verified && !domCandidates.includes(verified)) domCandidates.push(verified);
|
|
908
|
+
} else if (!domCandidates.includes(norm)) {
|
|
909
|
+
domCandidates.push(norm);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
if (domCandidates.length > 0) {
|
|
913
|
+
return { cwd: domCandidates[0], source: 'dom-path', matchedCascadeId: null };
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
if (!summaries || typeof summaries !== 'object') return null;
|
|
918
|
+
|
|
919
|
+
const cascadeId = typeof options.cascadeId === 'string' ? options.cascadeId.trim() : '';
|
|
920
|
+
if (cascadeId && summaries[cascadeId]) {
|
|
921
|
+
const cands = extractWorkspacesFromTrajectory(summaries[cascadeId], options);
|
|
922
|
+
const chosen = pickBestCandidatePath(cands, nameHints, options);
|
|
923
|
+
if (chosen) {
|
|
924
|
+
return { cwd: chosen, source: 'rpc-cascade', matchedCascadeId: cascadeId };
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
const entries = Object.entries(summaries)
|
|
929
|
+
.map(([id, summary]) => ({
|
|
930
|
+
id,
|
|
931
|
+
summary: summary || {},
|
|
932
|
+
workspaces: extractWorkspacesFromTrajectory(summary, options),
|
|
933
|
+
...getTrajectoryTimestamps(summary)
|
|
934
|
+
}))
|
|
935
|
+
.filter((item) => item.workspaces.length > 0);
|
|
936
|
+
|
|
937
|
+
if (entries.length === 0) return null;
|
|
938
|
+
|
|
939
|
+
const sortByRecency = (a, b) => (b.viewTs - a.viewTs) || (b.modTs - a.modTs);
|
|
940
|
+
|
|
941
|
+
// 3. 点击时 DOM 标题匹配会话
|
|
942
|
+
const titleCandidates = [];
|
|
943
|
+
if (typeof hints.activeConversationTitle === 'string' && hints.activeConversationTitle.trim()) {
|
|
944
|
+
titleCandidates.push(hints.activeConversationTitle.trim());
|
|
945
|
+
}
|
|
946
|
+
if (Array.isArray(hints.titlebarTexts)) {
|
|
947
|
+
for (const t of hints.titlebarTexts) {
|
|
948
|
+
const s = String(t || '').trim();
|
|
949
|
+
if (s && s.length >= 2 && !GENERIC_HINT_TOKENS.has(s.toLowerCase()) && !titleCandidates.includes(s)) {
|
|
950
|
+
titleCandidates.push(s);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
if (typeof hints.pageTitle === 'string' && hints.pageTitle.trim()) {
|
|
955
|
+
for (const part of hints.pageTitle.split(/\s+[—–\-|·]\s+|\s+-\s+/)) {
|
|
956
|
+
const s = part.trim();
|
|
957
|
+
if (s && s.length >= 2 && !GENERIC_HINT_TOKENS.has(s.toLowerCase()) && !titleCandidates.includes(s)) {
|
|
958
|
+
titleCandidates.push(s);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
if (titleCandidates.length > 0) {
|
|
964
|
+
const scoredByTitle = [];
|
|
965
|
+
for (const item of entries) {
|
|
966
|
+
const titles = [item.summary?.annotations?.title, item.summary?.summary]
|
|
967
|
+
.map((t) => String(t || '').trim())
|
|
968
|
+
.filter(Boolean);
|
|
969
|
+
if (titles.length === 0) continue;
|
|
970
|
+
let bestScore = 0;
|
|
971
|
+
for (const domT of titleCandidates) {
|
|
972
|
+
const domLower = domT.toLowerCase();
|
|
973
|
+
for (const rpcT of titles) {
|
|
974
|
+
const rpcLower = rpcT.toLowerCase();
|
|
975
|
+
if (domLower === rpcLower) {
|
|
976
|
+
bestScore = Math.max(bestScore, 2);
|
|
977
|
+
} else if (domLower.length >= 4 && rpcLower.length >= 4 && (domLower.includes(rpcLower) || rpcLower.includes(domLower))) {
|
|
978
|
+
bestScore = Math.max(bestScore, 1);
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
if (bestScore > 0) {
|
|
983
|
+
scoredByTitle.push({ item, score: bestScore });
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
if (scoredByTitle.length > 0) {
|
|
987
|
+
scoredByTitle.sort((a, b) => (b.score - a.score) || sortByRecency(a.item, b.item));
|
|
988
|
+
const best = scoredByTitle[0].item;
|
|
989
|
+
const chosen = pickBestCandidatePath(best.workspaces, nameHints, options);
|
|
990
|
+
if (chosen) {
|
|
991
|
+
return { cwd: chosen, source: 'rpc-dom-title', matchedCascadeId: best.id };
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
// 4. 点击时 DOM 工作区/项目名匹配 basename
|
|
997
|
+
if (nameHints.length > 0) {
|
|
998
|
+
const lowerHints = new Set(nameHints.map((h) => h.toLowerCase()));
|
|
999
|
+
const byWsName = entries.filter((item) =>
|
|
1000
|
+
item.workspaces.some((ws) => lowerHints.has(pathBasenameCrossPlatform(ws).toLowerCase()))
|
|
1001
|
+
);
|
|
1002
|
+
if (byWsName.length > 0) {
|
|
1003
|
+
byWsName.sort(sortByRecency);
|
|
1004
|
+
const best = byWsName[0];
|
|
1005
|
+
const chosen = pickBestCandidatePath(best.workspaces, nameHints, options);
|
|
1006
|
+
if (chosen) {
|
|
1007
|
+
return { cwd: chosen, source: 'rpc-dom-workspace-name', matchedCascadeId: best.id };
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// 5. contextCascadeId 匹配
|
|
1013
|
+
const contextCascadeId = typeof options.contextCascadeId === 'string' ? options.contextCascadeId.trim() : '';
|
|
1014
|
+
if (contextCascadeId && summaries[contextCascadeId]) {
|
|
1015
|
+
const cands = extractWorkspacesFromTrajectory(summaries[contextCascadeId], options);
|
|
1016
|
+
const chosen = pickBestCandidatePath(cands, nameHints, options);
|
|
1017
|
+
if (chosen) {
|
|
1018
|
+
return { cwd: chosen, source: 'rpc-context-cascade', matchedCascadeId: contextCascadeId };
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
// 6. 最近查看 / 活跃会话回退
|
|
1023
|
+
entries.sort(sortByRecency);
|
|
1024
|
+
const latest = entries[0];
|
|
1025
|
+
const chosen = pickBestCandidatePath(latest.workspaces, nameHints, options);
|
|
1026
|
+
if (chosen) {
|
|
1027
|
+
return { cwd: chosen, source: 'rpc-latest', matchedCascadeId: latest.id };
|
|
1028
|
+
}
|
|
1029
|
+
return null;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
function extractWorkspaceFromBrainDir(brainDir, cascadeId, options = {}) {
|
|
1033
|
+
if (!brainDir || !cascadeId) return null;
|
|
1034
|
+
const sessDir = path.join(path.resolve(brainDir), String(cascadeId).trim());
|
|
1035
|
+
if (!fs.existsSync(sessDir)) return null;
|
|
1036
|
+
for (const name of ['metadata.json', 'session.json', 'workspace.json']) {
|
|
1037
|
+
const p = path.join(sessDir, name);
|
|
1038
|
+
if (!fs.existsSync(p)) continue;
|
|
1039
|
+
try {
|
|
1040
|
+
const parsed = JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
1041
|
+
const raw = parsed?.workspacePath || parsed?.cwd || parsed?.workspaceUri || '';
|
|
1042
|
+
if (!raw) continue;
|
|
1043
|
+
const norm = normalizeWorkspacePath(String(raw), options);
|
|
1044
|
+
if (norm) return norm;
|
|
1045
|
+
} catch {}
|
|
1046
|
+
}
|
|
1047
|
+
return null;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
module.exports = {
|
|
1051
|
+
TERMINAL_CATALOG,
|
|
1052
|
+
TERMINAL_LABELS,
|
|
1053
|
+
CLI_PERMISSION_MODES,
|
|
1054
|
+
resolvePermissionArgs,
|
|
1055
|
+
parseQuickCommands,
|
|
1056
|
+
getWindowsHelperPath,
|
|
1057
|
+
normalizeWorkspacePath,
|
|
1058
|
+
extractWorkspacesFromTrajectory,
|
|
1059
|
+
resolveWorkspaceFromTrajectories,
|
|
1060
|
+
extractWorkspaceFromBrainDir,
|
|
1061
|
+
escapePosixArg,
|
|
1062
|
+
formatCliArgToken,
|
|
1063
|
+
buildDefaultCliCommand,
|
|
1064
|
+
escapeAppleScriptString,
|
|
1065
|
+
escapePowerShellSingleQuoted,
|
|
1066
|
+
toWslPath,
|
|
1067
|
+
sanitizeMuxHost,
|
|
1068
|
+
findInPath,
|
|
1069
|
+
detectRexAppPath,
|
|
1070
|
+
detectAvailableTerminals,
|
|
1071
|
+
detectTerminalPath,
|
|
1072
|
+
verifyTerminalPath,
|
|
1073
|
+
listSshMuxHosts,
|
|
1074
|
+
buildLaunchPlan
|
|
1075
|
+
};
|