@rehpic/vcli 0.1.0-beta.6.1 → 0.1.0-beta.61.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -2
- package/dist/index.js +3393 -106
- package/dist/index.js.map +1 -1
- package/native/VectorMenuBar.app/Contents/Info.plist +26 -0
- package/native/VectorMenuBar.app/Contents/MacOS/VectorMenuBar +0 -0
- package/native/VectorMenuBar.app/Contents/Resources/vector-menubar.png +0 -0
- package/native/VectorMenuBar.app/Contents/Resources/vector-menubar@2x.png +0 -0
- package/package.json +5 -2
- package/scripts/build-menubar-app.js +117 -0
package/dist/index.js
CHANGED
|
@@ -1,10 +1,748 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __esm = (fn, res) => function __init() {
|
|
5
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
6
|
+
};
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
// ../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js
|
|
13
|
+
import fs from "fs";
|
|
14
|
+
function hasDockerEnv() {
|
|
15
|
+
try {
|
|
16
|
+
fs.statSync("/.dockerenv");
|
|
17
|
+
return true;
|
|
18
|
+
} catch {
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function hasDockerCGroup() {
|
|
23
|
+
try {
|
|
24
|
+
return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker");
|
|
25
|
+
} catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function isDocker() {
|
|
30
|
+
if (isDockerCached === void 0) {
|
|
31
|
+
isDockerCached = hasDockerEnv() || hasDockerCGroup();
|
|
32
|
+
}
|
|
33
|
+
return isDockerCached;
|
|
34
|
+
}
|
|
35
|
+
var isDockerCached;
|
|
36
|
+
var init_is_docker = __esm({
|
|
37
|
+
"../../node_modules/.pnpm/is-docker@3.0.0/node_modules/is-docker/index.js"() {
|
|
38
|
+
"use strict";
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// ../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js
|
|
43
|
+
import fs2 from "fs";
|
|
44
|
+
function isInsideContainer() {
|
|
45
|
+
if (cachedResult === void 0) {
|
|
46
|
+
cachedResult = hasContainerEnv() || isDocker();
|
|
47
|
+
}
|
|
48
|
+
return cachedResult;
|
|
49
|
+
}
|
|
50
|
+
var cachedResult, hasContainerEnv;
|
|
51
|
+
var init_is_inside_container = __esm({
|
|
52
|
+
"../../node_modules/.pnpm/is-inside-container@1.0.0/node_modules/is-inside-container/index.js"() {
|
|
53
|
+
"use strict";
|
|
54
|
+
init_is_docker();
|
|
55
|
+
hasContainerEnv = () => {
|
|
56
|
+
try {
|
|
57
|
+
fs2.statSync("/run/.containerenv");
|
|
58
|
+
return true;
|
|
59
|
+
} catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
// ../../node_modules/.pnpm/is-wsl@3.1.1/node_modules/is-wsl/index.js
|
|
67
|
+
import process2 from "process";
|
|
68
|
+
import os from "os";
|
|
69
|
+
import fs3 from "fs";
|
|
70
|
+
var isWsl, is_wsl_default;
|
|
71
|
+
var init_is_wsl = __esm({
|
|
72
|
+
"../../node_modules/.pnpm/is-wsl@3.1.1/node_modules/is-wsl/index.js"() {
|
|
73
|
+
"use strict";
|
|
74
|
+
init_is_inside_container();
|
|
75
|
+
isWsl = () => {
|
|
76
|
+
if (process2.platform !== "linux") {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
if (os.release().toLowerCase().includes("microsoft")) {
|
|
80
|
+
if (isInsideContainer()) {
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
if (fs3.readFileSync("/proc/version", "utf8").toLowerCase().includes("microsoft")) {
|
|
87
|
+
return !isInsideContainer();
|
|
88
|
+
}
|
|
89
|
+
} catch {
|
|
90
|
+
}
|
|
91
|
+
if (fs3.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop") || fs3.existsSync("/run/WSL")) {
|
|
92
|
+
return !isInsideContainer();
|
|
93
|
+
}
|
|
94
|
+
return false;
|
|
95
|
+
};
|
|
96
|
+
is_wsl_default = process2.env.__IS_WSL_TEST__ ? isWsl : isWsl();
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// ../../node_modules/.pnpm/powershell-utils@0.1.0/node_modules/powershell-utils/index.js
|
|
101
|
+
import process3 from "process";
|
|
102
|
+
import { Buffer as Buffer2 } from "buffer";
|
|
103
|
+
import { promisify } from "util";
|
|
104
|
+
import childProcess from "child_process";
|
|
105
|
+
import fs4, { constants as fsConstants } from "fs/promises";
|
|
106
|
+
var execFile, powerShellPath, executePowerShell;
|
|
107
|
+
var init_powershell_utils = __esm({
|
|
108
|
+
"../../node_modules/.pnpm/powershell-utils@0.1.0/node_modules/powershell-utils/index.js"() {
|
|
109
|
+
"use strict";
|
|
110
|
+
execFile = promisify(childProcess.execFile);
|
|
111
|
+
powerShellPath = () => `${process3.env.SYSTEMROOT || process3.env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
|
|
112
|
+
executePowerShell = async (command, options = {}) => {
|
|
113
|
+
const {
|
|
114
|
+
powerShellPath: psPath,
|
|
115
|
+
...execFileOptions
|
|
116
|
+
} = options;
|
|
117
|
+
const encodedCommand = executePowerShell.encodeCommand(command);
|
|
118
|
+
return execFile(
|
|
119
|
+
psPath ?? powerShellPath(),
|
|
120
|
+
[
|
|
121
|
+
...executePowerShell.argumentsPrefix,
|
|
122
|
+
encodedCommand
|
|
123
|
+
],
|
|
124
|
+
{
|
|
125
|
+
encoding: "utf8",
|
|
126
|
+
...execFileOptions
|
|
127
|
+
}
|
|
128
|
+
);
|
|
129
|
+
};
|
|
130
|
+
executePowerShell.argumentsPrefix = [
|
|
131
|
+
"-NoProfile",
|
|
132
|
+
"-NonInteractive",
|
|
133
|
+
"-ExecutionPolicy",
|
|
134
|
+
"Bypass",
|
|
135
|
+
"-EncodedCommand"
|
|
136
|
+
];
|
|
137
|
+
executePowerShell.encodeCommand = (command) => Buffer2.from(command, "utf16le").toString("base64");
|
|
138
|
+
executePowerShell.escapeArgument = (value) => `'${String(value).replaceAll("'", "''")}'`;
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// ../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/utilities.js
|
|
143
|
+
function parseMountPointFromConfig(content) {
|
|
144
|
+
for (const line of content.split("\n")) {
|
|
145
|
+
if (/^\s*#/.test(line)) {
|
|
146
|
+
continue;
|
|
147
|
+
}
|
|
148
|
+
const match = /^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(line);
|
|
149
|
+
if (!match) {
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
return match.groups.mountPoint.trim().replaceAll(/^["']|["']$/g, "");
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
var init_utilities = __esm({
|
|
156
|
+
"../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/utilities.js"() {
|
|
157
|
+
"use strict";
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
// ../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/index.js
|
|
162
|
+
import { promisify as promisify2 } from "util";
|
|
163
|
+
import childProcess2 from "child_process";
|
|
164
|
+
import fs5, { constants as fsConstants2 } from "fs/promises";
|
|
165
|
+
var execFile2, wslDrivesMountPoint, powerShellPathFromWsl, powerShellPath2, canAccessPowerShellPromise, canAccessPowerShell, wslDefaultBrowser, convertWslPathToWindows;
|
|
166
|
+
var init_wsl_utils = __esm({
|
|
167
|
+
"../../node_modules/.pnpm/wsl-utils@0.3.1/node_modules/wsl-utils/index.js"() {
|
|
168
|
+
"use strict";
|
|
169
|
+
init_is_wsl();
|
|
170
|
+
init_powershell_utils();
|
|
171
|
+
init_utilities();
|
|
172
|
+
init_is_wsl();
|
|
173
|
+
execFile2 = promisify2(childProcess2.execFile);
|
|
174
|
+
wslDrivesMountPoint = /* @__PURE__ */ (() => {
|
|
175
|
+
const defaultMountPoint = "/mnt/";
|
|
176
|
+
let mountPoint;
|
|
177
|
+
return async function() {
|
|
178
|
+
if (mountPoint) {
|
|
179
|
+
return mountPoint;
|
|
180
|
+
}
|
|
181
|
+
const configFilePath = "/etc/wsl.conf";
|
|
182
|
+
let isConfigFileExists = false;
|
|
183
|
+
try {
|
|
184
|
+
await fs5.access(configFilePath, fsConstants2.F_OK);
|
|
185
|
+
isConfigFileExists = true;
|
|
186
|
+
} catch {
|
|
187
|
+
}
|
|
188
|
+
if (!isConfigFileExists) {
|
|
189
|
+
return defaultMountPoint;
|
|
190
|
+
}
|
|
191
|
+
const configContent = await fs5.readFile(configFilePath, { encoding: "utf8" });
|
|
192
|
+
const parsedMountPoint = parseMountPointFromConfig(configContent);
|
|
193
|
+
if (parsedMountPoint === void 0) {
|
|
194
|
+
return defaultMountPoint;
|
|
195
|
+
}
|
|
196
|
+
mountPoint = parsedMountPoint;
|
|
197
|
+
mountPoint = mountPoint.endsWith("/") ? mountPoint : `${mountPoint}/`;
|
|
198
|
+
return mountPoint;
|
|
199
|
+
};
|
|
200
|
+
})();
|
|
201
|
+
powerShellPathFromWsl = async () => {
|
|
202
|
+
const mountPoint = await wslDrivesMountPoint();
|
|
203
|
+
return `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`;
|
|
204
|
+
};
|
|
205
|
+
powerShellPath2 = is_wsl_default ? powerShellPathFromWsl : powerShellPath;
|
|
206
|
+
canAccessPowerShell = async () => {
|
|
207
|
+
canAccessPowerShellPromise ??= (async () => {
|
|
208
|
+
try {
|
|
209
|
+
const psPath = await powerShellPath2();
|
|
210
|
+
await fs5.access(psPath, fsConstants2.X_OK);
|
|
211
|
+
return true;
|
|
212
|
+
} catch {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
})();
|
|
216
|
+
return canAccessPowerShellPromise;
|
|
217
|
+
};
|
|
218
|
+
wslDefaultBrowser = async () => {
|
|
219
|
+
const psPath = await powerShellPath2();
|
|
220
|
+
const command = String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`;
|
|
221
|
+
const { stdout } = await executePowerShell(command, { powerShellPath: psPath });
|
|
222
|
+
return stdout.trim();
|
|
223
|
+
};
|
|
224
|
+
convertWslPathToWindows = async (path3) => {
|
|
225
|
+
if (/^[a-z]+:\/\//i.test(path3)) {
|
|
226
|
+
return path3;
|
|
227
|
+
}
|
|
228
|
+
try {
|
|
229
|
+
const { stdout } = await execFile2("wslpath", ["-aw", path3], { encoding: "utf8" });
|
|
230
|
+
return stdout.trim();
|
|
231
|
+
} catch {
|
|
232
|
+
return path3;
|
|
233
|
+
}
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
// ../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js
|
|
239
|
+
function defineLazyProperty(object, propertyName, valueGetter) {
|
|
240
|
+
const define = (value) => Object.defineProperty(object, propertyName, { value, enumerable: true, writable: true });
|
|
241
|
+
Object.defineProperty(object, propertyName, {
|
|
242
|
+
configurable: true,
|
|
243
|
+
enumerable: true,
|
|
244
|
+
get() {
|
|
245
|
+
const result = valueGetter();
|
|
246
|
+
define(result);
|
|
247
|
+
return result;
|
|
248
|
+
},
|
|
249
|
+
set(value) {
|
|
250
|
+
define(value);
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
return object;
|
|
254
|
+
}
|
|
255
|
+
var init_define_lazy_prop = __esm({
|
|
256
|
+
"../../node_modules/.pnpm/define-lazy-prop@3.0.0/node_modules/define-lazy-prop/index.js"() {
|
|
257
|
+
"use strict";
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
// ../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js
|
|
262
|
+
import { promisify as promisify3 } from "util";
|
|
263
|
+
import process4 from "process";
|
|
264
|
+
import { execFile as execFile3 } from "child_process";
|
|
265
|
+
async function defaultBrowserId() {
|
|
266
|
+
if (process4.platform !== "darwin") {
|
|
267
|
+
throw new Error("macOS only");
|
|
268
|
+
}
|
|
269
|
+
const { stdout } = await execFileAsync("defaults", ["read", "com.apple.LaunchServices/com.apple.launchservices.secure", "LSHandlers"]);
|
|
270
|
+
const match = /LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout);
|
|
271
|
+
const browserId = match?.groups.id ?? "com.apple.Safari";
|
|
272
|
+
if (browserId === "com.apple.safari") {
|
|
273
|
+
return "com.apple.Safari";
|
|
274
|
+
}
|
|
275
|
+
return browserId;
|
|
276
|
+
}
|
|
277
|
+
var execFileAsync;
|
|
278
|
+
var init_default_browser_id = __esm({
|
|
279
|
+
"../../node_modules/.pnpm/default-browser-id@5.0.1/node_modules/default-browser-id/index.js"() {
|
|
280
|
+
"use strict";
|
|
281
|
+
execFileAsync = promisify3(execFile3);
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
// ../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js
|
|
286
|
+
import process5 from "process";
|
|
287
|
+
import { promisify as promisify4 } from "util";
|
|
288
|
+
import { execFile as execFile4, execFileSync as execFileSync2 } from "child_process";
|
|
289
|
+
async function runAppleScript(script, { humanReadableOutput = true, signal } = {}) {
|
|
290
|
+
if (process5.platform !== "darwin") {
|
|
291
|
+
throw new Error("macOS only");
|
|
292
|
+
}
|
|
293
|
+
const outputArguments = humanReadableOutput ? [] : ["-ss"];
|
|
294
|
+
const execOptions = {};
|
|
295
|
+
if (signal) {
|
|
296
|
+
execOptions.signal = signal;
|
|
297
|
+
}
|
|
298
|
+
const { stdout } = await execFileAsync2("osascript", ["-e", script, outputArguments], execOptions);
|
|
299
|
+
return stdout.trim();
|
|
300
|
+
}
|
|
301
|
+
var execFileAsync2;
|
|
302
|
+
var init_run_applescript = __esm({
|
|
303
|
+
"../../node_modules/.pnpm/run-applescript@7.1.0/node_modules/run-applescript/index.js"() {
|
|
304
|
+
"use strict";
|
|
305
|
+
execFileAsync2 = promisify4(execFile4);
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
// ../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js
|
|
310
|
+
async function bundleName(bundleId) {
|
|
311
|
+
return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string
|
|
312
|
+
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`);
|
|
313
|
+
}
|
|
314
|
+
var init_bundle_name = __esm({
|
|
315
|
+
"../../node_modules/.pnpm/bundle-name@4.1.0/node_modules/bundle-name/index.js"() {
|
|
316
|
+
"use strict";
|
|
317
|
+
init_run_applescript();
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
// ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js
|
|
322
|
+
import { promisify as promisify5 } from "util";
|
|
323
|
+
import { execFile as execFile5 } from "child_process";
|
|
324
|
+
async function defaultBrowser(_execFileAsync = execFileAsync3) {
|
|
325
|
+
const { stdout } = await _execFileAsync("reg", [
|
|
326
|
+
"QUERY",
|
|
327
|
+
" HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice",
|
|
328
|
+
"/v",
|
|
329
|
+
"ProgId"
|
|
330
|
+
]);
|
|
331
|
+
const match = /ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(stdout);
|
|
332
|
+
if (!match) {
|
|
333
|
+
throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`);
|
|
334
|
+
}
|
|
335
|
+
const { id } = match.groups;
|
|
336
|
+
const dotIndex = id.lastIndexOf(".");
|
|
337
|
+
const hyphenIndex = id.lastIndexOf("-");
|
|
338
|
+
const baseIdByDot = dotIndex === -1 ? void 0 : id.slice(0, dotIndex);
|
|
339
|
+
const baseIdByHyphen = hyphenIndex === -1 ? void 0 : id.slice(0, hyphenIndex);
|
|
340
|
+
return windowsBrowserProgIds[id] ?? windowsBrowserProgIds[baseIdByDot] ?? windowsBrowserProgIds[baseIdByHyphen] ?? { name: id, id };
|
|
341
|
+
}
|
|
342
|
+
var execFileAsync3, windowsBrowserProgIds, _windowsBrowserProgIdMap, UnknownBrowserError;
|
|
343
|
+
var init_windows = __esm({
|
|
344
|
+
"../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/windows.js"() {
|
|
345
|
+
"use strict";
|
|
346
|
+
execFileAsync3 = promisify5(execFile5);
|
|
347
|
+
windowsBrowserProgIds = {
|
|
348
|
+
MSEdgeHTM: { name: "Edge", id: "com.microsoft.edge" },
|
|
349
|
+
// The missing `L` is correct.
|
|
350
|
+
MSEdgeBHTML: { name: "Edge Beta", id: "com.microsoft.edge.beta" },
|
|
351
|
+
MSEdgeDHTML: { name: "Edge Dev", id: "com.microsoft.edge.dev" },
|
|
352
|
+
AppXq0fevzme2pys62n3e0fbqa7peapykr8v: { name: "Edge", id: "com.microsoft.edge.old" },
|
|
353
|
+
ChromeHTML: { name: "Chrome", id: "com.google.chrome" },
|
|
354
|
+
ChromeBHTML: { name: "Chrome Beta", id: "com.google.chrome.beta" },
|
|
355
|
+
ChromeDHTML: { name: "Chrome Dev", id: "com.google.chrome.dev" },
|
|
356
|
+
ChromiumHTM: { name: "Chromium", id: "org.chromium.Chromium" },
|
|
357
|
+
BraveHTML: { name: "Brave", id: "com.brave.Browser" },
|
|
358
|
+
BraveBHTML: { name: "Brave Beta", id: "com.brave.Browser.beta" },
|
|
359
|
+
BraveDHTML: { name: "Brave Dev", id: "com.brave.Browser.dev" },
|
|
360
|
+
BraveSSHTM: { name: "Brave Nightly", id: "com.brave.Browser.nightly" },
|
|
361
|
+
FirefoxURL: { name: "Firefox", id: "org.mozilla.firefox" },
|
|
362
|
+
OperaStable: { name: "Opera", id: "com.operasoftware.Opera" },
|
|
363
|
+
VivaldiHTM: { name: "Vivaldi", id: "com.vivaldi.Vivaldi" },
|
|
364
|
+
"IE.HTTP": { name: "Internet Explorer", id: "com.microsoft.ie" }
|
|
365
|
+
};
|
|
366
|
+
_windowsBrowserProgIdMap = new Map(Object.entries(windowsBrowserProgIds));
|
|
367
|
+
UnknownBrowserError = class extends Error {
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
// ../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js
|
|
373
|
+
import { promisify as promisify6 } from "util";
|
|
374
|
+
import process6 from "process";
|
|
375
|
+
import { execFile as execFile6 } from "child_process";
|
|
376
|
+
async function defaultBrowser2() {
|
|
377
|
+
if (process6.platform === "darwin") {
|
|
378
|
+
const id = await defaultBrowserId();
|
|
379
|
+
const name = await bundleName(id);
|
|
380
|
+
return { name, id };
|
|
381
|
+
}
|
|
382
|
+
if (process6.platform === "linux") {
|
|
383
|
+
const { stdout } = await execFileAsync4("xdg-mime", ["query", "default", "x-scheme-handler/http"]);
|
|
384
|
+
const id = stdout.trim();
|
|
385
|
+
const name = titleize(id.replace(/.desktop$/, "").replace("-", " "));
|
|
386
|
+
return { name, id };
|
|
387
|
+
}
|
|
388
|
+
if (process6.platform === "win32") {
|
|
389
|
+
return defaultBrowser();
|
|
390
|
+
}
|
|
391
|
+
throw new Error("Only macOS, Linux, and Windows are supported");
|
|
392
|
+
}
|
|
393
|
+
var execFileAsync4, titleize;
|
|
394
|
+
var init_default_browser = __esm({
|
|
395
|
+
"../../node_modules/.pnpm/default-browser@5.5.0/node_modules/default-browser/index.js"() {
|
|
396
|
+
"use strict";
|
|
397
|
+
init_default_browser_id();
|
|
398
|
+
init_bundle_name();
|
|
399
|
+
init_windows();
|
|
400
|
+
init_windows();
|
|
401
|
+
execFileAsync4 = promisify6(execFile6);
|
|
402
|
+
titleize = (string) => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, (x) => x.toUpperCase());
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
// ../../node_modules/.pnpm/is-in-ssh@1.0.0/node_modules/is-in-ssh/index.js
|
|
407
|
+
import process7 from "process";
|
|
408
|
+
var isInSsh, is_in_ssh_default;
|
|
409
|
+
var init_is_in_ssh = __esm({
|
|
410
|
+
"../../node_modules/.pnpm/is-in-ssh@1.0.0/node_modules/is-in-ssh/index.js"() {
|
|
411
|
+
"use strict";
|
|
412
|
+
isInSsh = Boolean(process7.env.SSH_CONNECTION || process7.env.SSH_CLIENT || process7.env.SSH_TTY);
|
|
413
|
+
is_in_ssh_default = isInSsh;
|
|
414
|
+
}
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
// ../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js
|
|
418
|
+
var open_exports = {};
|
|
419
|
+
__export(open_exports, {
|
|
420
|
+
apps: () => apps,
|
|
421
|
+
default: () => open_default,
|
|
422
|
+
openApp: () => openApp
|
|
423
|
+
});
|
|
424
|
+
import process8 from "process";
|
|
425
|
+
import path2 from "path";
|
|
426
|
+
import { fileURLToPath } from "url";
|
|
427
|
+
import childProcess3 from "child_process";
|
|
428
|
+
import fs6, { constants as fsConstants3 } from "fs/promises";
|
|
429
|
+
function detectArchBinary(binary) {
|
|
430
|
+
if (typeof binary === "string" || Array.isArray(binary)) {
|
|
431
|
+
return binary;
|
|
432
|
+
}
|
|
433
|
+
const { [arch]: archBinary } = binary;
|
|
434
|
+
if (!archBinary) {
|
|
435
|
+
throw new Error(`${arch} is not supported`);
|
|
436
|
+
}
|
|
437
|
+
return archBinary;
|
|
438
|
+
}
|
|
439
|
+
function detectPlatformBinary({ [platform2]: platformBinary }, { wsl } = {}) {
|
|
440
|
+
if (wsl && is_wsl_default) {
|
|
441
|
+
return detectArchBinary(wsl);
|
|
442
|
+
}
|
|
443
|
+
if (!platformBinary) {
|
|
444
|
+
throw new Error(`${platform2} is not supported`);
|
|
445
|
+
}
|
|
446
|
+
return detectArchBinary(platformBinary);
|
|
447
|
+
}
|
|
448
|
+
var fallbackAttemptSymbol, __dirname, localXdgOpenPath, platform2, arch, tryEachApp, baseOpen, open, openApp, apps, open_default;
|
|
449
|
+
var init_open = __esm({
|
|
450
|
+
"../../node_modules/.pnpm/open@11.0.0/node_modules/open/index.js"() {
|
|
451
|
+
"use strict";
|
|
452
|
+
init_wsl_utils();
|
|
453
|
+
init_powershell_utils();
|
|
454
|
+
init_define_lazy_prop();
|
|
455
|
+
init_default_browser();
|
|
456
|
+
init_is_inside_container();
|
|
457
|
+
init_is_in_ssh();
|
|
458
|
+
fallbackAttemptSymbol = Symbol("fallbackAttempt");
|
|
459
|
+
__dirname = import.meta.url ? path2.dirname(fileURLToPath(import.meta.url)) : "";
|
|
460
|
+
localXdgOpenPath = path2.join(__dirname, "xdg-open");
|
|
461
|
+
({ platform: platform2, arch } = process8);
|
|
462
|
+
tryEachApp = async (apps2, opener) => {
|
|
463
|
+
if (apps2.length === 0) {
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const errors = [];
|
|
467
|
+
for (const app of apps2) {
|
|
468
|
+
try {
|
|
469
|
+
return await opener(app);
|
|
470
|
+
} catch (error) {
|
|
471
|
+
errors.push(error);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
throw new AggregateError(errors, "Failed to open in all supported apps");
|
|
475
|
+
};
|
|
476
|
+
baseOpen = async (options) => {
|
|
477
|
+
options = {
|
|
478
|
+
wait: false,
|
|
479
|
+
background: false,
|
|
480
|
+
newInstance: false,
|
|
481
|
+
allowNonzeroExitCode: false,
|
|
482
|
+
...options
|
|
483
|
+
};
|
|
484
|
+
const isFallbackAttempt = options[fallbackAttemptSymbol] === true;
|
|
485
|
+
delete options[fallbackAttemptSymbol];
|
|
486
|
+
if (Array.isArray(options.app)) {
|
|
487
|
+
return tryEachApp(options.app, (singleApp) => baseOpen({
|
|
488
|
+
...options,
|
|
489
|
+
app: singleApp,
|
|
490
|
+
[fallbackAttemptSymbol]: true
|
|
491
|
+
}));
|
|
492
|
+
}
|
|
493
|
+
let { name: app, arguments: appArguments = [] } = options.app ?? {};
|
|
494
|
+
appArguments = [...appArguments];
|
|
495
|
+
if (Array.isArray(app)) {
|
|
496
|
+
return tryEachApp(app, (appName) => baseOpen({
|
|
497
|
+
...options,
|
|
498
|
+
app: {
|
|
499
|
+
name: appName,
|
|
500
|
+
arguments: appArguments
|
|
501
|
+
},
|
|
502
|
+
[fallbackAttemptSymbol]: true
|
|
503
|
+
}));
|
|
504
|
+
}
|
|
505
|
+
if (app === "browser" || app === "browserPrivate") {
|
|
506
|
+
const ids = {
|
|
507
|
+
"com.google.chrome": "chrome",
|
|
508
|
+
"google-chrome.desktop": "chrome",
|
|
509
|
+
"com.brave.browser": "brave",
|
|
510
|
+
"org.mozilla.firefox": "firefox",
|
|
511
|
+
"firefox.desktop": "firefox",
|
|
512
|
+
"com.microsoft.msedge": "edge",
|
|
513
|
+
"com.microsoft.edge": "edge",
|
|
514
|
+
"com.microsoft.edgemac": "edge",
|
|
515
|
+
"microsoft-edge.desktop": "edge",
|
|
516
|
+
"com.apple.safari": "safari"
|
|
517
|
+
};
|
|
518
|
+
const flags = {
|
|
519
|
+
chrome: "--incognito",
|
|
520
|
+
brave: "--incognito",
|
|
521
|
+
firefox: "--private-window",
|
|
522
|
+
edge: "--inPrivate"
|
|
523
|
+
// Safari doesn't support private mode via command line
|
|
524
|
+
};
|
|
525
|
+
let browser;
|
|
526
|
+
if (is_wsl_default) {
|
|
527
|
+
const progId = await wslDefaultBrowser();
|
|
528
|
+
const browserInfo = _windowsBrowserProgIdMap.get(progId);
|
|
529
|
+
browser = browserInfo ?? {};
|
|
530
|
+
} else {
|
|
531
|
+
browser = await defaultBrowser2();
|
|
532
|
+
}
|
|
533
|
+
if (browser.id in ids) {
|
|
534
|
+
const browserName = ids[browser.id.toLowerCase()];
|
|
535
|
+
if (app === "browserPrivate") {
|
|
536
|
+
if (browserName === "safari") {
|
|
537
|
+
throw new Error("Safari doesn't support opening in private mode via command line");
|
|
538
|
+
}
|
|
539
|
+
appArguments.push(flags[browserName]);
|
|
540
|
+
}
|
|
541
|
+
return baseOpen({
|
|
542
|
+
...options,
|
|
543
|
+
app: {
|
|
544
|
+
name: apps[browserName],
|
|
545
|
+
arguments: appArguments
|
|
546
|
+
}
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
throw new Error(`${browser.name} is not supported as a default browser`);
|
|
550
|
+
}
|
|
551
|
+
let command;
|
|
552
|
+
const cliArguments = [];
|
|
553
|
+
const childProcessOptions = {};
|
|
554
|
+
let shouldUseWindowsInWsl = false;
|
|
555
|
+
if (is_wsl_default && !isInsideContainer() && !is_in_ssh_default && !app) {
|
|
556
|
+
shouldUseWindowsInWsl = await canAccessPowerShell();
|
|
557
|
+
}
|
|
558
|
+
if (platform2 === "darwin") {
|
|
559
|
+
command = "open";
|
|
560
|
+
if (options.wait) {
|
|
561
|
+
cliArguments.push("--wait-apps");
|
|
562
|
+
}
|
|
563
|
+
if (options.background) {
|
|
564
|
+
cliArguments.push("--background");
|
|
565
|
+
}
|
|
566
|
+
if (options.newInstance) {
|
|
567
|
+
cliArguments.push("--new");
|
|
568
|
+
}
|
|
569
|
+
if (app) {
|
|
570
|
+
cliArguments.push("-a", app);
|
|
571
|
+
}
|
|
572
|
+
} else if (platform2 === "win32" || shouldUseWindowsInWsl) {
|
|
573
|
+
command = await powerShellPath2();
|
|
574
|
+
cliArguments.push(...executePowerShell.argumentsPrefix);
|
|
575
|
+
if (!is_wsl_default) {
|
|
576
|
+
childProcessOptions.windowsVerbatimArguments = true;
|
|
577
|
+
}
|
|
578
|
+
if (is_wsl_default && options.target) {
|
|
579
|
+
options.target = await convertWslPathToWindows(options.target);
|
|
580
|
+
}
|
|
581
|
+
const encodedArguments = ["$ProgressPreference = 'SilentlyContinue';", "Start"];
|
|
582
|
+
if (options.wait) {
|
|
583
|
+
encodedArguments.push("-Wait");
|
|
584
|
+
}
|
|
585
|
+
if (app) {
|
|
586
|
+
encodedArguments.push(executePowerShell.escapeArgument(app));
|
|
587
|
+
if (options.target) {
|
|
588
|
+
appArguments.push(options.target);
|
|
589
|
+
}
|
|
590
|
+
} else if (options.target) {
|
|
591
|
+
encodedArguments.push(executePowerShell.escapeArgument(options.target));
|
|
592
|
+
}
|
|
593
|
+
if (appArguments.length > 0) {
|
|
594
|
+
appArguments = appArguments.map((argument) => executePowerShell.escapeArgument(argument));
|
|
595
|
+
encodedArguments.push("-ArgumentList", appArguments.join(","));
|
|
596
|
+
}
|
|
597
|
+
options.target = executePowerShell.encodeCommand(encodedArguments.join(" "));
|
|
598
|
+
if (!options.wait) {
|
|
599
|
+
childProcessOptions.stdio = "ignore";
|
|
600
|
+
}
|
|
601
|
+
} else {
|
|
602
|
+
if (app) {
|
|
603
|
+
command = app;
|
|
604
|
+
} else {
|
|
605
|
+
const isBundled = !__dirname || __dirname === "/";
|
|
606
|
+
let exeLocalXdgOpen = false;
|
|
607
|
+
try {
|
|
608
|
+
await fs6.access(localXdgOpenPath, fsConstants3.X_OK);
|
|
609
|
+
exeLocalXdgOpen = true;
|
|
610
|
+
} catch {
|
|
611
|
+
}
|
|
612
|
+
const useSystemXdgOpen = process8.versions.electron ?? (platform2 === "android" || isBundled || !exeLocalXdgOpen);
|
|
613
|
+
command = useSystemXdgOpen ? "xdg-open" : localXdgOpenPath;
|
|
614
|
+
}
|
|
615
|
+
if (appArguments.length > 0) {
|
|
616
|
+
cliArguments.push(...appArguments);
|
|
617
|
+
}
|
|
618
|
+
if (!options.wait) {
|
|
619
|
+
childProcessOptions.stdio = "ignore";
|
|
620
|
+
childProcessOptions.detached = true;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
if (platform2 === "darwin" && appArguments.length > 0) {
|
|
624
|
+
cliArguments.push("--args", ...appArguments);
|
|
625
|
+
}
|
|
626
|
+
if (options.target) {
|
|
627
|
+
cliArguments.push(options.target);
|
|
628
|
+
}
|
|
629
|
+
const subprocess = childProcess3.spawn(command, cliArguments, childProcessOptions);
|
|
630
|
+
if (options.wait) {
|
|
631
|
+
return new Promise((resolve, reject) => {
|
|
632
|
+
subprocess.once("error", reject);
|
|
633
|
+
subprocess.once("close", (exitCode) => {
|
|
634
|
+
if (!options.allowNonzeroExitCode && exitCode !== 0) {
|
|
635
|
+
reject(new Error(`Exited with code ${exitCode}`));
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
resolve(subprocess);
|
|
639
|
+
});
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
if (isFallbackAttempt) {
|
|
643
|
+
return new Promise((resolve, reject) => {
|
|
644
|
+
subprocess.once("error", reject);
|
|
645
|
+
subprocess.once("spawn", () => {
|
|
646
|
+
subprocess.once("close", (exitCode) => {
|
|
647
|
+
subprocess.off("error", reject);
|
|
648
|
+
if (exitCode !== 0) {
|
|
649
|
+
reject(new Error(`Exited with code ${exitCode}`));
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
subprocess.unref();
|
|
653
|
+
resolve(subprocess);
|
|
654
|
+
});
|
|
655
|
+
});
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
subprocess.unref();
|
|
659
|
+
return new Promise((resolve, reject) => {
|
|
660
|
+
subprocess.once("error", reject);
|
|
661
|
+
subprocess.once("spawn", () => {
|
|
662
|
+
subprocess.off("error", reject);
|
|
663
|
+
resolve(subprocess);
|
|
664
|
+
});
|
|
665
|
+
});
|
|
666
|
+
};
|
|
667
|
+
open = (target, options) => {
|
|
668
|
+
if (typeof target !== "string") {
|
|
669
|
+
throw new TypeError("Expected a `target`");
|
|
670
|
+
}
|
|
671
|
+
return baseOpen({
|
|
672
|
+
...options,
|
|
673
|
+
target
|
|
674
|
+
});
|
|
675
|
+
};
|
|
676
|
+
openApp = (name, options) => {
|
|
677
|
+
if (typeof name !== "string" && !Array.isArray(name)) {
|
|
678
|
+
throw new TypeError("Expected a valid `name`");
|
|
679
|
+
}
|
|
680
|
+
const { arguments: appArguments = [] } = options ?? {};
|
|
681
|
+
if (appArguments !== void 0 && appArguments !== null && !Array.isArray(appArguments)) {
|
|
682
|
+
throw new TypeError("Expected `appArguments` as Array type");
|
|
683
|
+
}
|
|
684
|
+
return baseOpen({
|
|
685
|
+
...options,
|
|
686
|
+
app: {
|
|
687
|
+
name,
|
|
688
|
+
arguments: appArguments
|
|
689
|
+
}
|
|
690
|
+
});
|
|
691
|
+
};
|
|
692
|
+
apps = {
|
|
693
|
+
browser: "browser",
|
|
694
|
+
browserPrivate: "browserPrivate"
|
|
695
|
+
};
|
|
696
|
+
defineLazyProperty(apps, "chrome", () => detectPlatformBinary({
|
|
697
|
+
darwin: "google chrome",
|
|
698
|
+
win32: "chrome",
|
|
699
|
+
// `chromium-browser` is the older deb package name used by Ubuntu/Debian before snap.
|
|
700
|
+
linux: ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"]
|
|
701
|
+
}, {
|
|
702
|
+
wsl: {
|
|
703
|
+
ia32: "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",
|
|
704
|
+
x64: ["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe", "/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]
|
|
705
|
+
}
|
|
706
|
+
}));
|
|
707
|
+
defineLazyProperty(apps, "brave", () => detectPlatformBinary({
|
|
708
|
+
darwin: "brave browser",
|
|
709
|
+
win32: "brave",
|
|
710
|
+
linux: ["brave-browser", "brave"]
|
|
711
|
+
}, {
|
|
712
|
+
wsl: {
|
|
713
|
+
ia32: "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",
|
|
714
|
+
x64: ["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe", "/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]
|
|
715
|
+
}
|
|
716
|
+
}));
|
|
717
|
+
defineLazyProperty(apps, "firefox", () => detectPlatformBinary({
|
|
718
|
+
darwin: "firefox",
|
|
719
|
+
win32: String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,
|
|
720
|
+
linux: "firefox"
|
|
721
|
+
}, {
|
|
722
|
+
wsl: "/mnt/c/Program Files/Mozilla Firefox/firefox.exe"
|
|
723
|
+
}));
|
|
724
|
+
defineLazyProperty(apps, "edge", () => detectPlatformBinary({
|
|
725
|
+
darwin: "microsoft edge",
|
|
726
|
+
win32: "msedge",
|
|
727
|
+
linux: ["microsoft-edge", "microsoft-edge-dev"]
|
|
728
|
+
}, {
|
|
729
|
+
wsl: "/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
|
|
730
|
+
}));
|
|
731
|
+
defineLazyProperty(apps, "safari", () => detectPlatformBinary({
|
|
732
|
+
darwin: "Safari"
|
|
733
|
+
}));
|
|
734
|
+
open_default = open;
|
|
735
|
+
}
|
|
736
|
+
});
|
|
2
737
|
|
|
3
|
-
//
|
|
738
|
+
// src/index.ts
|
|
739
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
4
740
|
import { readFile as readFile2 } from "fs/promises";
|
|
5
|
-
import { extname } from "path";
|
|
741
|
+
import { dirname, extname, join as join3 } from "path";
|
|
742
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
6
743
|
import { config as loadEnv } from "dotenv";
|
|
7
744
|
import { Command } from "commander";
|
|
745
|
+
import { ConvexHttpClient as ConvexHttpClient3 } from "convex/browser";
|
|
8
746
|
import { makeFunctionReference } from "convex/server";
|
|
9
747
|
|
|
10
748
|
// ../../convex/_generated/api.js
|
|
@@ -12,7 +750,7 @@ import { anyApi, componentsGeneric } from "convex/server";
|
|
|
12
750
|
var api = anyApi;
|
|
13
751
|
var components = componentsGeneric();
|
|
14
752
|
|
|
15
|
-
//
|
|
753
|
+
// src/auth.ts
|
|
16
754
|
import { isCancel, password as passwordPrompt, text } from "@clack/prompts";
|
|
17
755
|
function buildUrl(appUrl, pathname) {
|
|
18
756
|
return new URL(pathname, appUrl).toString();
|
|
@@ -52,6 +790,9 @@ function applySetCookieHeaders(session, response) {
|
|
|
52
790
|
async function authRequest(session, appUrl, pathname, init = {}) {
|
|
53
791
|
const headers = new Headers(init.headers);
|
|
54
792
|
const origin = new URL(appUrl).origin;
|
|
793
|
+
if (session.bearerToken && !headers.has("authorization")) {
|
|
794
|
+
headers.set("authorization", `Bearer ${session.bearerToken}`);
|
|
795
|
+
}
|
|
55
796
|
if (Object.keys(session.cookies).length > 0) {
|
|
56
797
|
headers.set("cookie", cookieHeader(session.cookies));
|
|
57
798
|
}
|
|
@@ -146,7 +887,7 @@ async function fetchAuthSession(session, appUrl) {
|
|
|
146
887
|
const data = await response.json();
|
|
147
888
|
return {
|
|
148
889
|
session: nextSession,
|
|
149
|
-
user: data
|
|
890
|
+
user: data?.user ?? null
|
|
150
891
|
};
|
|
151
892
|
}
|
|
152
893
|
async function fetchConvexToken(session, appUrl) {
|
|
@@ -170,6 +911,65 @@ async function fetchConvexToken(session, appUrl) {
|
|
|
170
911
|
token: data.token
|
|
171
912
|
};
|
|
172
913
|
}
|
|
914
|
+
async function requestDeviceCode(appUrl, clientId) {
|
|
915
|
+
const response = await fetch(buildUrl(appUrl, "/api/auth/device/code"), {
|
|
916
|
+
method: "POST",
|
|
917
|
+
headers: { "content-type": "application/json" },
|
|
918
|
+
body: JSON.stringify({ client_id: clientId })
|
|
919
|
+
});
|
|
920
|
+
if (!response.ok) {
|
|
921
|
+
throw new Error(`Failed to request device code: HTTP ${response.status}`);
|
|
922
|
+
}
|
|
923
|
+
return await response.json();
|
|
924
|
+
}
|
|
925
|
+
async function pollDeviceToken(session, appUrl, deviceCode, clientId, interval, expiresIn) {
|
|
926
|
+
const deadline = Date.now() + expiresIn * 1e3;
|
|
927
|
+
let pollInterval = interval * 1e3;
|
|
928
|
+
while (Date.now() < deadline) {
|
|
929
|
+
await new Promise((resolve) => setTimeout(resolve, pollInterval));
|
|
930
|
+
const { response, session: nextSession } = await authRequest(
|
|
931
|
+
session,
|
|
932
|
+
appUrl,
|
|
933
|
+
"/api/auth/device/token",
|
|
934
|
+
{
|
|
935
|
+
method: "POST",
|
|
936
|
+
body: JSON.stringify({
|
|
937
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
938
|
+
device_code: deviceCode,
|
|
939
|
+
client_id: clientId
|
|
940
|
+
})
|
|
941
|
+
}
|
|
942
|
+
);
|
|
943
|
+
session = nextSession;
|
|
944
|
+
if (response.ok) {
|
|
945
|
+
const data = await response.json();
|
|
946
|
+
if (data.access_token) {
|
|
947
|
+
session.bearerToken = data.access_token;
|
|
948
|
+
return session;
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
let errorData;
|
|
952
|
+
try {
|
|
953
|
+
errorData = await response.json();
|
|
954
|
+
} catch {
|
|
955
|
+
errorData = { error: `HTTP ${response.status}` };
|
|
956
|
+
}
|
|
957
|
+
switch (errorData.error) {
|
|
958
|
+
case "authorization_pending":
|
|
959
|
+
break;
|
|
960
|
+
case "slow_down":
|
|
961
|
+
pollInterval += 5e3;
|
|
962
|
+
break;
|
|
963
|
+
case "access_denied":
|
|
964
|
+
throw new Error("Authorization denied by user.");
|
|
965
|
+
case "expired_token":
|
|
966
|
+
throw new Error("Device code expired. Please try again.");
|
|
967
|
+
default:
|
|
968
|
+
throw new Error(`Device auth error: ${errorData.error}`);
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
throw new Error("Device code expired. Please try again.");
|
|
972
|
+
}
|
|
173
973
|
async function prompt(question) {
|
|
174
974
|
const value = await text({
|
|
175
975
|
message: question.replace(/:\s*$/, "")
|
|
@@ -190,7 +990,7 @@ async function promptSecret(question) {
|
|
|
190
990
|
return String(value);
|
|
191
991
|
}
|
|
192
992
|
|
|
193
|
-
//
|
|
993
|
+
// src/convex.ts
|
|
194
994
|
import { ConvexHttpClient } from "convex/browser";
|
|
195
995
|
async function createConvexClient(session, appUrl, convexUrl) {
|
|
196
996
|
const { token } = await fetchConvexToken(session, appUrl);
|
|
@@ -207,95 +1007,1982 @@ async function runMutation(client, ref, ...args) {
|
|
|
207
1007
|
async function runAction(client, ref, ...args) {
|
|
208
1008
|
return await client.action(ref, ...args);
|
|
209
1009
|
}
|
|
210
|
-
|
|
211
|
-
//
|
|
212
|
-
function simplify(value) {
|
|
213
|
-
if (value === null || value === void 0) {
|
|
214
|
-
return value;
|
|
1010
|
+
|
|
1011
|
+
// src/output.ts
|
|
1012
|
+
function simplify(value) {
|
|
1013
|
+
if (value === null || value === void 0) {
|
|
1014
|
+
return value;
|
|
1015
|
+
}
|
|
1016
|
+
if (Array.isArray(value)) {
|
|
1017
|
+
if (value.length === 0) {
|
|
1018
|
+
return [];
|
|
1019
|
+
}
|
|
1020
|
+
if (value.every((item) => typeof item !== "object" || item === null)) {
|
|
1021
|
+
return value.join(", ");
|
|
1022
|
+
}
|
|
1023
|
+
return JSON.stringify(value);
|
|
1024
|
+
}
|
|
1025
|
+
if (typeof value === "object") {
|
|
1026
|
+
return JSON.stringify(value);
|
|
1027
|
+
}
|
|
1028
|
+
return value;
|
|
1029
|
+
}
|
|
1030
|
+
function printOutput(data, json = false) {
|
|
1031
|
+
if (json) {
|
|
1032
|
+
console.log(JSON.stringify(data, null, 2));
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
if (Array.isArray(data)) {
|
|
1036
|
+
if (data.length === 0) {
|
|
1037
|
+
console.log("No results.");
|
|
1038
|
+
return;
|
|
1039
|
+
}
|
|
1040
|
+
if (data.every((item) => typeof item === "object" && item !== null)) {
|
|
1041
|
+
console.table(
|
|
1042
|
+
data.map(
|
|
1043
|
+
(item) => Object.fromEntries(
|
|
1044
|
+
Object.entries(item).map(([key, value]) => [key, simplify(value)])
|
|
1045
|
+
)
|
|
1046
|
+
)
|
|
1047
|
+
);
|
|
1048
|
+
return;
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
if (typeof data === "object" && data !== null) {
|
|
1052
|
+
console.dir(data, { depth: null, colors: true });
|
|
1053
|
+
return;
|
|
1054
|
+
}
|
|
1055
|
+
console.log(String(data));
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
// src/session.ts
|
|
1059
|
+
import { mkdir, readFile, rm, writeFile } from "fs/promises";
|
|
1060
|
+
import { homedir } from "os";
|
|
1061
|
+
import path from "path";
|
|
1062
|
+
function getSessionRoot() {
|
|
1063
|
+
return process.env.VECTOR_HOME?.trim() || path.join(homedir(), ".vector");
|
|
1064
|
+
}
|
|
1065
|
+
function getSessionPath(profile = "default") {
|
|
1066
|
+
return path.join(getSessionRoot(), `cli-${profile}.json`);
|
|
1067
|
+
}
|
|
1068
|
+
async function readSession(profile = "default") {
|
|
1069
|
+
try {
|
|
1070
|
+
const raw = await readFile(getSessionPath(profile), "utf8");
|
|
1071
|
+
const parsed = JSON.parse(raw);
|
|
1072
|
+
return {
|
|
1073
|
+
version: 1,
|
|
1074
|
+
cookies: {},
|
|
1075
|
+
...parsed
|
|
1076
|
+
};
|
|
1077
|
+
} catch {
|
|
1078
|
+
return null;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
async function writeSession(session, profile = "default") {
|
|
1082
|
+
await mkdir(getSessionRoot(), { recursive: true });
|
|
1083
|
+
await writeFile(
|
|
1084
|
+
getSessionPath(profile),
|
|
1085
|
+
`${JSON.stringify(session, null, 2)}
|
|
1086
|
+
`,
|
|
1087
|
+
"utf8"
|
|
1088
|
+
);
|
|
1089
|
+
}
|
|
1090
|
+
async function clearSession(profile = "default") {
|
|
1091
|
+
await rm(getSessionPath(profile), { force: true });
|
|
1092
|
+
}
|
|
1093
|
+
function createEmptySession() {
|
|
1094
|
+
return {
|
|
1095
|
+
version: 1,
|
|
1096
|
+
cookies: {}
|
|
1097
|
+
};
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
// src/bridge-service.ts
|
|
1101
|
+
import { ConvexHttpClient as ConvexHttpClient2 } from "convex/browser";
|
|
1102
|
+
import { execFileSync, execSync as execSync2 } from "child_process";
|
|
1103
|
+
import {
|
|
1104
|
+
existsSync as existsSync2,
|
|
1105
|
+
mkdirSync,
|
|
1106
|
+
readFileSync as readFileSync2,
|
|
1107
|
+
writeFileSync,
|
|
1108
|
+
unlinkSync
|
|
1109
|
+
} from "fs";
|
|
1110
|
+
import { homedir as homedir3, hostname, platform } from "os";
|
|
1111
|
+
import { join as join2 } from "path";
|
|
1112
|
+
import { randomUUID } from "crypto";
|
|
1113
|
+
|
|
1114
|
+
// src/agent-adapters.ts
|
|
1115
|
+
import { execSync, spawn } from "child_process";
|
|
1116
|
+
import { existsSync, readFileSync, readdirSync } from "fs";
|
|
1117
|
+
import { homedir as homedir2, userInfo } from "os";
|
|
1118
|
+
import { basename, join } from "path";
|
|
1119
|
+
var LSOF_PATHS = ["/usr/sbin/lsof", "/usr/bin/lsof"];
|
|
1120
|
+
var VECTOR_BRIDGE_CLIENT_VERSION = "0.1.0";
|
|
1121
|
+
function discoverAttachableSessions() {
|
|
1122
|
+
return dedupeSessions([
|
|
1123
|
+
...discoverCodexSessions(),
|
|
1124
|
+
...discoverClaudeSessions()
|
|
1125
|
+
]);
|
|
1126
|
+
}
|
|
1127
|
+
async function resumeProviderSession(provider, sessionKey, cwd, prompt2) {
|
|
1128
|
+
if (provider === "codex") {
|
|
1129
|
+
return runCodexAppServerTurn({
|
|
1130
|
+
cwd,
|
|
1131
|
+
prompt: prompt2,
|
|
1132
|
+
sessionKey,
|
|
1133
|
+
launchCommand: "codex app-server (thread/resume)"
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
return runClaudeSdkTurn({
|
|
1137
|
+
cwd,
|
|
1138
|
+
prompt: prompt2,
|
|
1139
|
+
sessionKey,
|
|
1140
|
+
launchCommand: "@anthropic-ai/claude-agent-sdk query(resume)"
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
async function runCodexAppServerTurn(args) {
|
|
1144
|
+
const child = spawn("codex", ["app-server"], {
|
|
1145
|
+
cwd: args.cwd,
|
|
1146
|
+
env: { ...process.env },
|
|
1147
|
+
stdio: ["pipe", "pipe", "pipe"]
|
|
1148
|
+
});
|
|
1149
|
+
let stderr = "";
|
|
1150
|
+
let stdoutBuffer = "";
|
|
1151
|
+
let sessionKey = args.sessionKey;
|
|
1152
|
+
let finalAssistantText = "";
|
|
1153
|
+
let completed = false;
|
|
1154
|
+
let nextRequestId = 1;
|
|
1155
|
+
const pending = /* @__PURE__ */ new Map();
|
|
1156
|
+
let completeTurn;
|
|
1157
|
+
let failTurn;
|
|
1158
|
+
const turnCompleted = new Promise((resolve, reject) => {
|
|
1159
|
+
completeTurn = () => {
|
|
1160
|
+
completed = true;
|
|
1161
|
+
resolve();
|
|
1162
|
+
};
|
|
1163
|
+
failTurn = (error) => {
|
|
1164
|
+
completed = true;
|
|
1165
|
+
reject(error);
|
|
1166
|
+
};
|
|
1167
|
+
});
|
|
1168
|
+
child.stdout.on("data", (chunk) => {
|
|
1169
|
+
stdoutBuffer += chunk.toString();
|
|
1170
|
+
while (true) {
|
|
1171
|
+
const newlineIndex = stdoutBuffer.indexOf("\n");
|
|
1172
|
+
if (newlineIndex < 0) {
|
|
1173
|
+
break;
|
|
1174
|
+
}
|
|
1175
|
+
const line = stdoutBuffer.slice(0, newlineIndex).trim();
|
|
1176
|
+
stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1);
|
|
1177
|
+
if (!line) {
|
|
1178
|
+
continue;
|
|
1179
|
+
}
|
|
1180
|
+
const payload = tryParseJson(line);
|
|
1181
|
+
if (!payload || typeof payload !== "object") {
|
|
1182
|
+
continue;
|
|
1183
|
+
}
|
|
1184
|
+
const responseId = payload.id;
|
|
1185
|
+
if (typeof responseId === "number" && pending.has(responseId)) {
|
|
1186
|
+
const entry = pending.get(responseId);
|
|
1187
|
+
pending.delete(responseId);
|
|
1188
|
+
const errorRecord = asObject(payload.error);
|
|
1189
|
+
if (errorRecord) {
|
|
1190
|
+
entry.reject(
|
|
1191
|
+
new Error(
|
|
1192
|
+
`codex app-server error: ${asString(errorRecord.message) ?? "Unknown JSON-RPC error"}`
|
|
1193
|
+
)
|
|
1194
|
+
);
|
|
1195
|
+
continue;
|
|
1196
|
+
}
|
|
1197
|
+
entry.resolve(payload.result);
|
|
1198
|
+
continue;
|
|
1199
|
+
}
|
|
1200
|
+
const method = asString(payload.method);
|
|
1201
|
+
const params = asObject(payload.params);
|
|
1202
|
+
if (!method || !params) {
|
|
1203
|
+
continue;
|
|
1204
|
+
}
|
|
1205
|
+
if (method === "thread/started") {
|
|
1206
|
+
sessionKey = asString(asObject(params.thread)?.id) ?? asString(asObject(params.thread)?.threadId) ?? sessionKey;
|
|
1207
|
+
continue;
|
|
1208
|
+
}
|
|
1209
|
+
if (method === "item/agentMessage/delta") {
|
|
1210
|
+
finalAssistantText += asString(params.delta) ?? "";
|
|
1211
|
+
continue;
|
|
1212
|
+
}
|
|
1213
|
+
if (method === "item/completed") {
|
|
1214
|
+
const item = asObject(params.item);
|
|
1215
|
+
if (asString(item?.type) === "agentMessage") {
|
|
1216
|
+
finalAssistantText = asString(item?.text) ?? finalAssistantText;
|
|
1217
|
+
}
|
|
1218
|
+
continue;
|
|
1219
|
+
}
|
|
1220
|
+
if (method === "turn/completed") {
|
|
1221
|
+
const turn = asObject(params.turn);
|
|
1222
|
+
const status = asString(turn?.status);
|
|
1223
|
+
if (status === "failed") {
|
|
1224
|
+
const turnError = asObject(turn?.error);
|
|
1225
|
+
failTurn?.(
|
|
1226
|
+
new Error(
|
|
1227
|
+
asString(turnError?.message) ?? "Codex turn failed without an error message"
|
|
1228
|
+
)
|
|
1229
|
+
);
|
|
1230
|
+
} else if (status === "interrupted") {
|
|
1231
|
+
failTurn?.(new Error("Codex turn was interrupted"));
|
|
1232
|
+
} else {
|
|
1233
|
+
completeTurn?.();
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
});
|
|
1238
|
+
child.stderr.on("data", (chunk) => {
|
|
1239
|
+
stderr += chunk.toString();
|
|
1240
|
+
});
|
|
1241
|
+
const request = (method, params) => new Promise((resolve, reject) => {
|
|
1242
|
+
const id = nextRequestId++;
|
|
1243
|
+
pending.set(id, { resolve, reject });
|
|
1244
|
+
child.stdin.write(`${JSON.stringify({ method, id, params })}
|
|
1245
|
+
`);
|
|
1246
|
+
});
|
|
1247
|
+
const notify = (method, params) => {
|
|
1248
|
+
child.stdin.write(`${JSON.stringify({ method, params })}
|
|
1249
|
+
`);
|
|
1250
|
+
};
|
|
1251
|
+
const waitForExit = new Promise((_, reject) => {
|
|
1252
|
+
child.on("error", (error) => reject(error));
|
|
1253
|
+
child.on("close", (code) => {
|
|
1254
|
+
if (!completed) {
|
|
1255
|
+
const detail = stderr.trim() || `codex app-server exited with code ${code}`;
|
|
1256
|
+
reject(new Error(detail));
|
|
1257
|
+
}
|
|
1258
|
+
});
|
|
1259
|
+
});
|
|
1260
|
+
try {
|
|
1261
|
+
await Promise.race([
|
|
1262
|
+
request("initialize", {
|
|
1263
|
+
clientInfo: {
|
|
1264
|
+
name: "vector_bridge",
|
|
1265
|
+
title: "Vector Bridge",
|
|
1266
|
+
version: VECTOR_BRIDGE_CLIENT_VERSION
|
|
1267
|
+
}
|
|
1268
|
+
}),
|
|
1269
|
+
waitForExit
|
|
1270
|
+
]);
|
|
1271
|
+
notify("initialized", {});
|
|
1272
|
+
const threadResult = await Promise.race([
|
|
1273
|
+
args.sessionKey ? request("thread/resume", {
|
|
1274
|
+
threadId: args.sessionKey,
|
|
1275
|
+
cwd: args.cwd,
|
|
1276
|
+
approvalPolicy: "never",
|
|
1277
|
+
personality: "pragmatic"
|
|
1278
|
+
}) : request("thread/start", {
|
|
1279
|
+
cwd: args.cwd,
|
|
1280
|
+
approvalPolicy: "never",
|
|
1281
|
+
personality: "pragmatic",
|
|
1282
|
+
serviceName: "vector_bridge"
|
|
1283
|
+
}),
|
|
1284
|
+
waitForExit
|
|
1285
|
+
]);
|
|
1286
|
+
sessionKey = asString(asObject(threadResult.thread)?.id) ?? asString(asObject(threadResult.thread)?.threadId) ?? sessionKey;
|
|
1287
|
+
if (!sessionKey) {
|
|
1288
|
+
throw new Error("Codex app-server did not return a thread id");
|
|
1289
|
+
}
|
|
1290
|
+
await Promise.race([
|
|
1291
|
+
request("turn/start", {
|
|
1292
|
+
threadId: sessionKey,
|
|
1293
|
+
input: [{ type: "text", text: args.prompt }],
|
|
1294
|
+
cwd: args.cwd,
|
|
1295
|
+
approvalPolicy: "never",
|
|
1296
|
+
personality: "pragmatic"
|
|
1297
|
+
}),
|
|
1298
|
+
waitForExit
|
|
1299
|
+
]);
|
|
1300
|
+
await Promise.race([turnCompleted, waitForExit]);
|
|
1301
|
+
const gitInfo = getGitInfo(args.cwd);
|
|
1302
|
+
return {
|
|
1303
|
+
provider: "codex",
|
|
1304
|
+
providerLabel: "Codex",
|
|
1305
|
+
sessionKey,
|
|
1306
|
+
cwd: args.cwd,
|
|
1307
|
+
...gitInfo,
|
|
1308
|
+
title: summarizeTitle(void 0, args.cwd),
|
|
1309
|
+
mode: "managed",
|
|
1310
|
+
status: "waiting",
|
|
1311
|
+
supportsInboundMessages: true,
|
|
1312
|
+
responseText: finalAssistantText.trim() || void 0,
|
|
1313
|
+
launchCommand: args.launchCommand
|
|
1314
|
+
};
|
|
1315
|
+
} finally {
|
|
1316
|
+
for (const entry of pending.values()) {
|
|
1317
|
+
entry.reject(
|
|
1318
|
+
new Error("codex app-server closed before request resolved")
|
|
1319
|
+
);
|
|
1320
|
+
}
|
|
1321
|
+
pending.clear();
|
|
1322
|
+
child.kill();
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
async function runClaudeSdkTurn(args) {
|
|
1326
|
+
const { query } = await import("@anthropic-ai/claude-agent-sdk");
|
|
1327
|
+
const stream = query({
|
|
1328
|
+
prompt: args.prompt,
|
|
1329
|
+
options: {
|
|
1330
|
+
cwd: args.cwd,
|
|
1331
|
+
resume: args.sessionKey,
|
|
1332
|
+
persistSession: true,
|
|
1333
|
+
permissionMode: "bypassPermissions",
|
|
1334
|
+
allowDangerouslySkipPermissions: true,
|
|
1335
|
+
env: {
|
|
1336
|
+
...process.env,
|
|
1337
|
+
CLAUDE_AGENT_SDK_CLIENT_APP: `vector-bridge/${VECTOR_BRIDGE_CLIENT_VERSION}`
|
|
1338
|
+
}
|
|
1339
|
+
}
|
|
1340
|
+
});
|
|
1341
|
+
let sessionKey = args.sessionKey;
|
|
1342
|
+
let responseText = "";
|
|
1343
|
+
let model;
|
|
1344
|
+
try {
|
|
1345
|
+
for await (const message of stream) {
|
|
1346
|
+
if (!message || typeof message !== "object") {
|
|
1347
|
+
continue;
|
|
1348
|
+
}
|
|
1349
|
+
sessionKey = asString(message.session_id) ?? sessionKey;
|
|
1350
|
+
if (message.type === "assistant") {
|
|
1351
|
+
const assistantText = extractClaudeMessageTexts(
|
|
1352
|
+
message.message
|
|
1353
|
+
).join("\n\n").trim();
|
|
1354
|
+
if (assistantText) {
|
|
1355
|
+
responseText = assistantText;
|
|
1356
|
+
}
|
|
1357
|
+
continue;
|
|
1358
|
+
}
|
|
1359
|
+
if (message.type !== "result") {
|
|
1360
|
+
continue;
|
|
1361
|
+
}
|
|
1362
|
+
if (message.subtype === "success") {
|
|
1363
|
+
const resultText = asString(message.result);
|
|
1364
|
+
if (resultText) {
|
|
1365
|
+
responseText = resultText;
|
|
1366
|
+
}
|
|
1367
|
+
model = firstObjectKey(
|
|
1368
|
+
message.modelUsage
|
|
1369
|
+
);
|
|
1370
|
+
continue;
|
|
1371
|
+
}
|
|
1372
|
+
const errors = message.errors;
|
|
1373
|
+
const detail = Array.isArray(errors) && errors.length > 0 ? errors.join("\n") : "Claude execution failed";
|
|
1374
|
+
throw new Error(detail);
|
|
1375
|
+
}
|
|
1376
|
+
} finally {
|
|
1377
|
+
stream.close();
|
|
1378
|
+
}
|
|
1379
|
+
if (!sessionKey) {
|
|
1380
|
+
throw new Error("Claude Agent SDK did not return a session id");
|
|
1381
|
+
}
|
|
1382
|
+
const gitInfo = getGitInfo(args.cwd);
|
|
1383
|
+
return {
|
|
1384
|
+
provider: "claude_code",
|
|
1385
|
+
providerLabel: "Claude",
|
|
1386
|
+
sessionKey,
|
|
1387
|
+
cwd: args.cwd,
|
|
1388
|
+
...gitInfo,
|
|
1389
|
+
title: summarizeTitle(void 0, args.cwd),
|
|
1390
|
+
model,
|
|
1391
|
+
mode: "managed",
|
|
1392
|
+
status: "waiting",
|
|
1393
|
+
supportsInboundMessages: true,
|
|
1394
|
+
responseText: responseText.trim() || void 0,
|
|
1395
|
+
launchCommand: args.launchCommand
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
function discoverCodexSessions() {
|
|
1399
|
+
const historyBySession = buildCodexHistoryIndex();
|
|
1400
|
+
return listLiveProcessIds("codex").flatMap((pid) => {
|
|
1401
|
+
const transcriptPath = getCodexTranscriptPath(pid);
|
|
1402
|
+
if (!transcriptPath) {
|
|
1403
|
+
return [];
|
|
1404
|
+
}
|
|
1405
|
+
const processCwd = getProcessCwd(pid);
|
|
1406
|
+
const parsed = parseObservedCodexSession(
|
|
1407
|
+
pid,
|
|
1408
|
+
transcriptPath,
|
|
1409
|
+
processCwd,
|
|
1410
|
+
historyBySession
|
|
1411
|
+
);
|
|
1412
|
+
return parsed ? [parsed] : [];
|
|
1413
|
+
}).sort(compareObservedSessions);
|
|
1414
|
+
}
|
|
1415
|
+
function discoverClaudeSessions() {
|
|
1416
|
+
const historyBySession = buildClaudeHistoryIndex();
|
|
1417
|
+
return listLiveProcessIds("claude").flatMap((pid) => {
|
|
1418
|
+
const sessionMeta = readClaudePidSession(pid);
|
|
1419
|
+
if (!sessionMeta?.sessionId) {
|
|
1420
|
+
return [];
|
|
1421
|
+
}
|
|
1422
|
+
const transcriptPath = findClaudeTranscriptPath(sessionMeta.sessionId);
|
|
1423
|
+
const parsed = parseObservedClaudeSession(
|
|
1424
|
+
pid,
|
|
1425
|
+
sessionMeta,
|
|
1426
|
+
transcriptPath,
|
|
1427
|
+
historyBySession
|
|
1428
|
+
);
|
|
1429
|
+
return parsed ? [parsed] : [];
|
|
1430
|
+
}).sort(compareObservedSessions);
|
|
1431
|
+
}
|
|
1432
|
+
function getCodexHistoryFile() {
|
|
1433
|
+
return join(getRealHomeDir(), ".codex", "history.jsonl");
|
|
1434
|
+
}
|
|
1435
|
+
function getClaudeProjectsDir() {
|
|
1436
|
+
return join(getRealHomeDir(), ".claude", "projects");
|
|
1437
|
+
}
|
|
1438
|
+
function getClaudeSessionStateDir() {
|
|
1439
|
+
return join(getRealHomeDir(), ".claude", "sessions");
|
|
1440
|
+
}
|
|
1441
|
+
function getClaudeHistoryFile() {
|
|
1442
|
+
return join(getRealHomeDir(), ".claude", "history.jsonl");
|
|
1443
|
+
}
|
|
1444
|
+
function getRealHomeDir() {
|
|
1445
|
+
try {
|
|
1446
|
+
const realHome = userInfo().homedir?.trim();
|
|
1447
|
+
if (realHome) {
|
|
1448
|
+
return realHome;
|
|
1449
|
+
}
|
|
1450
|
+
} catch {
|
|
1451
|
+
}
|
|
1452
|
+
return homedir2();
|
|
1453
|
+
}
|
|
1454
|
+
function resolveExecutable(fallbackCommand, absoluteCandidates) {
|
|
1455
|
+
for (const candidate of absoluteCandidates) {
|
|
1456
|
+
if (existsSync(candidate)) {
|
|
1457
|
+
return candidate;
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
try {
|
|
1461
|
+
const output = execSync(`command -v ${fallbackCommand}`, {
|
|
1462
|
+
encoding: "utf-8",
|
|
1463
|
+
timeout: 1e3
|
|
1464
|
+
}).trim();
|
|
1465
|
+
return output || void 0;
|
|
1466
|
+
} catch {
|
|
1467
|
+
return void 0;
|
|
1468
|
+
}
|
|
1469
|
+
}
|
|
1470
|
+
function listLiveProcessIds(commandName) {
|
|
1471
|
+
try {
|
|
1472
|
+
const output = execSync("ps -axo pid=,comm=", {
|
|
1473
|
+
encoding: "utf-8",
|
|
1474
|
+
timeout: 3e3
|
|
1475
|
+
});
|
|
1476
|
+
return output.split("\n").map((line) => line.trim()).filter(Boolean).map((line) => line.split(/\s+/, 2)).filter(([, command]) => command === commandName).map(([pid]) => pid).filter(Boolean);
|
|
1477
|
+
} catch {
|
|
1478
|
+
return [];
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
function getProcessCwd(pid) {
|
|
1482
|
+
const lsofCommand = resolveExecutable("lsof", LSOF_PATHS);
|
|
1483
|
+
if (!lsofCommand) {
|
|
1484
|
+
return void 0;
|
|
1485
|
+
}
|
|
1486
|
+
try {
|
|
1487
|
+
const output = execSync(`${lsofCommand} -a -p ${pid} -Fn -d cwd`, {
|
|
1488
|
+
encoding: "utf-8",
|
|
1489
|
+
timeout: 3e3
|
|
1490
|
+
});
|
|
1491
|
+
return output.split("\n").map((line) => line.trim()).find((line) => line.startsWith("n"))?.slice(1);
|
|
1492
|
+
} catch {
|
|
1493
|
+
return void 0;
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
function getCodexTranscriptPath(pid) {
|
|
1497
|
+
const lsofCommand = resolveExecutable("lsof", LSOF_PATHS);
|
|
1498
|
+
if (!lsofCommand) {
|
|
1499
|
+
return void 0;
|
|
1500
|
+
}
|
|
1501
|
+
try {
|
|
1502
|
+
const output = execSync(`${lsofCommand} -p ${pid} -Fn`, {
|
|
1503
|
+
encoding: "utf-8",
|
|
1504
|
+
timeout: 3e3
|
|
1505
|
+
});
|
|
1506
|
+
return output.split("\n").map((line) => line.trim()).find(
|
|
1507
|
+
(line) => line.startsWith("n") && line.includes("/.codex/sessions/") && line.endsWith(".jsonl")
|
|
1508
|
+
)?.slice(1);
|
|
1509
|
+
} catch {
|
|
1510
|
+
return void 0;
|
|
1511
|
+
}
|
|
1512
|
+
}
|
|
1513
|
+
function readClaudePidSession(pid) {
|
|
1514
|
+
const path3 = join(getClaudeSessionStateDir(), `${pid}.json`);
|
|
1515
|
+
if (!existsSync(path3)) {
|
|
1516
|
+
return null;
|
|
1517
|
+
}
|
|
1518
|
+
try {
|
|
1519
|
+
const payload = JSON.parse(readFileSync(path3, "utf-8"));
|
|
1520
|
+
const sessionId = asString(payload.sessionId);
|
|
1521
|
+
if (!sessionId) {
|
|
1522
|
+
return null;
|
|
1523
|
+
}
|
|
1524
|
+
return {
|
|
1525
|
+
sessionId,
|
|
1526
|
+
cwd: asString(payload.cwd),
|
|
1527
|
+
startedAt: typeof payload.startedAt === "number" ? payload.startedAt : void 0
|
|
1528
|
+
};
|
|
1529
|
+
} catch {
|
|
1530
|
+
return null;
|
|
1531
|
+
}
|
|
1532
|
+
}
|
|
1533
|
+
function findClaudeTranscriptPath(sessionId) {
|
|
1534
|
+
return findJsonlFileByStem(getClaudeProjectsDir(), sessionId);
|
|
1535
|
+
}
|
|
1536
|
+
function findJsonlFileByStem(root, stem) {
|
|
1537
|
+
if (!existsSync(root)) {
|
|
1538
|
+
return void 0;
|
|
1539
|
+
}
|
|
1540
|
+
for (const entry of readdirSync(root, { withFileTypes: true })) {
|
|
1541
|
+
const path3 = join(root, entry.name);
|
|
1542
|
+
if (entry.isDirectory()) {
|
|
1543
|
+
const nested = findJsonlFileByStem(path3, stem);
|
|
1544
|
+
if (nested) {
|
|
1545
|
+
return nested;
|
|
1546
|
+
}
|
|
1547
|
+
continue;
|
|
1548
|
+
}
|
|
1549
|
+
if (entry.isFile() && entry.name === `${stem}.jsonl`) {
|
|
1550
|
+
return path3;
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
return void 0;
|
|
1554
|
+
}
|
|
1555
|
+
function readJsonLines(path3) {
|
|
1556
|
+
try {
|
|
1557
|
+
return readFileSync(path3, "utf-8").split("\n").map((line) => line.trim()).filter(Boolean).map(tryParseJson).filter(Boolean);
|
|
1558
|
+
} catch {
|
|
1559
|
+
return [];
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
function tryParseJson(value) {
|
|
1563
|
+
try {
|
|
1564
|
+
return JSON.parse(value);
|
|
1565
|
+
} catch {
|
|
1566
|
+
return null;
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
function dedupeSessions(sessions) {
|
|
1570
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1571
|
+
return sessions.filter((session) => {
|
|
1572
|
+
const key = `${session.provider}:${session.localProcessId ?? session.sessionKey}`;
|
|
1573
|
+
if (seen.has(key)) {
|
|
1574
|
+
return false;
|
|
1575
|
+
}
|
|
1576
|
+
seen.add(key);
|
|
1577
|
+
return true;
|
|
1578
|
+
});
|
|
1579
|
+
}
|
|
1580
|
+
function compareObservedSessions(a, b) {
|
|
1581
|
+
return Number(b.localProcessId ?? 0) - Number(a.localProcessId ?? 0);
|
|
1582
|
+
}
|
|
1583
|
+
function parseObservedCodexSession(pid, transcriptPath, processCwd, historyBySession) {
|
|
1584
|
+
const entries = readJsonLines(transcriptPath);
|
|
1585
|
+
let sessionKey;
|
|
1586
|
+
let cwd = processCwd;
|
|
1587
|
+
const userMessages = [];
|
|
1588
|
+
const assistantMessages = [];
|
|
1589
|
+
for (const rawEntry of entries) {
|
|
1590
|
+
const entry = asObject(rawEntry);
|
|
1591
|
+
if (!entry) {
|
|
1592
|
+
continue;
|
|
1593
|
+
}
|
|
1594
|
+
if (entry.type === "session_meta") {
|
|
1595
|
+
const payload = asObject(entry.payload);
|
|
1596
|
+
sessionKey = asString(payload?.id) ?? sessionKey;
|
|
1597
|
+
cwd = asString(payload?.cwd) ?? cwd;
|
|
1598
|
+
}
|
|
1599
|
+
if (entry.type === "event_msg") {
|
|
1600
|
+
const payload = asObject(entry.payload);
|
|
1601
|
+
if (payload?.type === "user_message") {
|
|
1602
|
+
pushIfPresent(userMessages, payload.message);
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
if (entry.type === "response_item" && asObject(entry.payload)?.type === "message" && asObject(entry.payload)?.role === "user") {
|
|
1606
|
+
userMessages.push(
|
|
1607
|
+
...extractTextSegments(asObject(entry.payload)?.content)
|
|
1608
|
+
);
|
|
1609
|
+
}
|
|
1610
|
+
if (entry.type === "event_msg") {
|
|
1611
|
+
const payload = asObject(entry.payload);
|
|
1612
|
+
if (payload?.type === "agent_message") {
|
|
1613
|
+
pushIfPresent(assistantMessages, payload.message);
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
if (entry.type === "response_item" && asObject(entry.payload)?.type === "message" && asObject(entry.payload)?.role === "assistant") {
|
|
1617
|
+
assistantMessages.push(
|
|
1618
|
+
...extractTextSegments(asObject(entry.payload)?.content)
|
|
1619
|
+
);
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
if (!sessionKey) {
|
|
1623
|
+
return null;
|
|
1624
|
+
}
|
|
1625
|
+
const gitInfo = cwd ? getGitInfo(cwd) : {};
|
|
1626
|
+
const historyTitle = sessionKey ? selectSessionTitle(historyBySession?.get(sessionKey) ?? []) : void 0;
|
|
1627
|
+
return {
|
|
1628
|
+
provider: "codex",
|
|
1629
|
+
providerLabel: "Codex",
|
|
1630
|
+
localProcessId: pid,
|
|
1631
|
+
sessionKey,
|
|
1632
|
+
cwd,
|
|
1633
|
+
...gitInfo,
|
|
1634
|
+
title: summarizeTitle(
|
|
1635
|
+
historyTitle ?? selectSessionTitle(userMessages) ?? selectSessionTitle(assistantMessages),
|
|
1636
|
+
cwd
|
|
1637
|
+
),
|
|
1638
|
+
mode: "observed",
|
|
1639
|
+
status: "observed",
|
|
1640
|
+
supportsInboundMessages: true
|
|
1641
|
+
};
|
|
1642
|
+
}
|
|
1643
|
+
function parseObservedClaudeSession(pid, sessionMeta, transcriptPath, historyBySession) {
|
|
1644
|
+
const entries = transcriptPath ? readJsonLines(transcriptPath) : [];
|
|
1645
|
+
let cwd = sessionMeta.cwd;
|
|
1646
|
+
let branch;
|
|
1647
|
+
let model;
|
|
1648
|
+
const userMessages = [];
|
|
1649
|
+
const assistantMessages = [];
|
|
1650
|
+
for (const rawEntry of entries) {
|
|
1651
|
+
const entry = asObject(rawEntry);
|
|
1652
|
+
if (!entry) {
|
|
1653
|
+
continue;
|
|
1654
|
+
}
|
|
1655
|
+
cwd = asString(entry.cwd) ?? cwd;
|
|
1656
|
+
branch = asString(entry.gitBranch) ?? branch;
|
|
1657
|
+
if (entry.type === "user") {
|
|
1658
|
+
userMessages.push(...extractClaudeMessageTexts(entry.message));
|
|
1659
|
+
}
|
|
1660
|
+
if (entry.type === "assistant") {
|
|
1661
|
+
const message = asObject(entry.message);
|
|
1662
|
+
model = asString(message?.model) ?? model;
|
|
1663
|
+
assistantMessages.push(...extractClaudeMessageTexts(entry.message));
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
const gitInfo = cwd ? getGitInfo(cwd) : {};
|
|
1667
|
+
const historyTitle = selectSessionTitle(
|
|
1668
|
+
historyBySession?.get(sessionMeta.sessionId) ?? []
|
|
1669
|
+
);
|
|
1670
|
+
return {
|
|
1671
|
+
provider: "claude_code",
|
|
1672
|
+
providerLabel: "Claude",
|
|
1673
|
+
localProcessId: pid,
|
|
1674
|
+
sessionKey: sessionMeta.sessionId,
|
|
1675
|
+
cwd,
|
|
1676
|
+
repoRoot: gitInfo.repoRoot,
|
|
1677
|
+
branch: branch ?? gitInfo.branch,
|
|
1678
|
+
title: summarizeTitle(
|
|
1679
|
+
historyTitle ?? selectSessionTitle(userMessages) ?? selectSessionTitle(assistantMessages),
|
|
1680
|
+
cwd
|
|
1681
|
+
),
|
|
1682
|
+
model,
|
|
1683
|
+
mode: "observed",
|
|
1684
|
+
status: "observed",
|
|
1685
|
+
supportsInboundMessages: true
|
|
1686
|
+
};
|
|
1687
|
+
}
|
|
1688
|
+
function summarizeTitle(message, cwd) {
|
|
1689
|
+
if (message) {
|
|
1690
|
+
return truncate(message.replace(/\s+/g, " ").trim(), 96);
|
|
1691
|
+
}
|
|
1692
|
+
if (cwd) {
|
|
1693
|
+
return basename(cwd);
|
|
1694
|
+
}
|
|
1695
|
+
return "Local session";
|
|
1696
|
+
}
|
|
1697
|
+
function truncate(value, maxLength) {
|
|
1698
|
+
return value.length > maxLength ? `${value.slice(0, maxLength - 3).trimEnd()}...` : value;
|
|
1699
|
+
}
|
|
1700
|
+
function firstObjectKey(value) {
|
|
1701
|
+
if (!value || typeof value !== "object") {
|
|
1702
|
+
return void 0;
|
|
1703
|
+
}
|
|
1704
|
+
const [firstKey] = Object.keys(value);
|
|
1705
|
+
return firstKey ? normalizeModelKey(firstKey) : void 0;
|
|
1706
|
+
}
|
|
1707
|
+
function normalizeModelKey(value) {
|
|
1708
|
+
const normalized = stripAnsi(value).replace(/\[\d+(?:;\d+)*m$/g, "").trim();
|
|
1709
|
+
return normalized || void 0;
|
|
1710
|
+
}
|
|
1711
|
+
function asObject(value) {
|
|
1712
|
+
return value && typeof value === "object" ? value : void 0;
|
|
1713
|
+
}
|
|
1714
|
+
function asString(value) {
|
|
1715
|
+
return typeof value === "string" && value.trim() ? value : void 0;
|
|
1716
|
+
}
|
|
1717
|
+
function pushIfPresent(target, value) {
|
|
1718
|
+
const text2 = asString(value);
|
|
1719
|
+
if (text2) {
|
|
1720
|
+
target.push(text2);
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
function extractClaudeMessageTexts(message) {
|
|
1724
|
+
if (!message || typeof message !== "object") {
|
|
1725
|
+
return [];
|
|
1726
|
+
}
|
|
1727
|
+
return extractTextSegments(message.content);
|
|
1728
|
+
}
|
|
1729
|
+
function extractTextSegments(value) {
|
|
1730
|
+
if (typeof value === "string") {
|
|
1731
|
+
return [value];
|
|
1732
|
+
}
|
|
1733
|
+
if (!Array.isArray(value)) {
|
|
1734
|
+
return [];
|
|
1735
|
+
}
|
|
1736
|
+
return value.flatMap(extractTextSegmentFromBlock).filter(Boolean);
|
|
1737
|
+
}
|
|
1738
|
+
function extractTextSegmentFromBlock(block) {
|
|
1739
|
+
if (!block || typeof block !== "object") {
|
|
1740
|
+
return [];
|
|
1741
|
+
}
|
|
1742
|
+
const typedBlock = block;
|
|
1743
|
+
const blockType = asString(typedBlock.type);
|
|
1744
|
+
if (blockType && isIgnoredContentBlockType(blockType)) {
|
|
1745
|
+
return [];
|
|
1746
|
+
}
|
|
1747
|
+
const directText = asString(typedBlock.text);
|
|
1748
|
+
if (directText) {
|
|
1749
|
+
return [directText];
|
|
1750
|
+
}
|
|
1751
|
+
if (typeof typedBlock.content === "string") {
|
|
1752
|
+
return [typedBlock.content];
|
|
1753
|
+
}
|
|
1754
|
+
return [];
|
|
1755
|
+
}
|
|
1756
|
+
function isIgnoredContentBlockType(blockType) {
|
|
1757
|
+
return [
|
|
1758
|
+
"tool_result",
|
|
1759
|
+
"tool_use",
|
|
1760
|
+
"image",
|
|
1761
|
+
"thinking",
|
|
1762
|
+
"reasoning",
|
|
1763
|
+
"contextCompaction"
|
|
1764
|
+
].includes(blockType);
|
|
1765
|
+
}
|
|
1766
|
+
function buildCodexHistoryIndex() {
|
|
1767
|
+
const historyBySession = /* @__PURE__ */ new Map();
|
|
1768
|
+
for (const rawEntry of readJsonLines(getCodexHistoryFile())) {
|
|
1769
|
+
const entry = asObject(rawEntry);
|
|
1770
|
+
if (!entry) {
|
|
1771
|
+
continue;
|
|
1772
|
+
}
|
|
1773
|
+
const sessionId = asString(entry.session_id);
|
|
1774
|
+
const text2 = asString(entry.text);
|
|
1775
|
+
if (!sessionId || !text2) {
|
|
1776
|
+
continue;
|
|
1777
|
+
}
|
|
1778
|
+
appendHistoryEntry(historyBySession, sessionId, text2);
|
|
1779
|
+
}
|
|
1780
|
+
return historyBySession;
|
|
1781
|
+
}
|
|
1782
|
+
function buildClaudeHistoryIndex() {
|
|
1783
|
+
const historyBySession = /* @__PURE__ */ new Map();
|
|
1784
|
+
for (const rawEntry of readJsonLines(getClaudeHistoryFile())) {
|
|
1785
|
+
const entry = asObject(rawEntry);
|
|
1786
|
+
if (!entry) {
|
|
1787
|
+
continue;
|
|
1788
|
+
}
|
|
1789
|
+
const sessionId = asString(entry.sessionId);
|
|
1790
|
+
if (!sessionId) {
|
|
1791
|
+
continue;
|
|
1792
|
+
}
|
|
1793
|
+
const texts = extractClaudeHistoryTexts(entry);
|
|
1794
|
+
for (const text2 of texts) {
|
|
1795
|
+
appendHistoryEntry(historyBySession, sessionId, text2);
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
return historyBySession;
|
|
1799
|
+
}
|
|
1800
|
+
function appendHistoryEntry(historyBySession, sessionId, text2) {
|
|
1801
|
+
const existing = historyBySession.get(sessionId);
|
|
1802
|
+
if (existing) {
|
|
1803
|
+
existing.push(text2);
|
|
1804
|
+
return;
|
|
1805
|
+
}
|
|
1806
|
+
historyBySession.set(sessionId, [text2]);
|
|
1807
|
+
}
|
|
1808
|
+
function extractClaudeHistoryTexts(entry) {
|
|
1809
|
+
if (!entry || typeof entry !== "object") {
|
|
1810
|
+
return [];
|
|
1811
|
+
}
|
|
1812
|
+
const record = entry;
|
|
1813
|
+
const pastedTexts = extractClaudePastedTexts(record.pastedContents);
|
|
1814
|
+
if (pastedTexts.length > 0) {
|
|
1815
|
+
return pastedTexts;
|
|
1816
|
+
}
|
|
1817
|
+
const display = asString(record.display);
|
|
1818
|
+
return display ? [display] : [];
|
|
1819
|
+
}
|
|
1820
|
+
function extractClaudePastedTexts(value) {
|
|
1821
|
+
if (!value || typeof value !== "object") {
|
|
1822
|
+
return [];
|
|
1823
|
+
}
|
|
1824
|
+
return Object.values(value).flatMap((item) => {
|
|
1825
|
+
if (!item || typeof item !== "object") {
|
|
1826
|
+
return [];
|
|
1827
|
+
}
|
|
1828
|
+
const record = item;
|
|
1829
|
+
return record.type === "text" && typeof record.content === "string" ? [record.content] : [];
|
|
1830
|
+
}).filter(Boolean);
|
|
1831
|
+
}
|
|
1832
|
+
function selectSessionTitle(messages) {
|
|
1833
|
+
for (const message of messages) {
|
|
1834
|
+
const cleaned = cleanSessionTitleCandidate(message);
|
|
1835
|
+
if (cleaned) {
|
|
1836
|
+
return cleaned;
|
|
1837
|
+
}
|
|
1838
|
+
}
|
|
1839
|
+
return void 0;
|
|
1840
|
+
}
|
|
1841
|
+
function cleanSessionTitleCandidate(message) {
|
|
1842
|
+
const normalized = stripAnsi(message).replace(/\s+/g, " ").trim();
|
|
1843
|
+
if (!normalized) {
|
|
1844
|
+
return void 0;
|
|
1845
|
+
}
|
|
1846
|
+
if (normalized.length < 4) {
|
|
1847
|
+
return void 0;
|
|
1848
|
+
}
|
|
1849
|
+
if (normalized.startsWith("/") || looksLikeGeneratedTagEnvelope(normalized) || looksLikeGeneratedImageSummary(normalized) || looksLikeStandaloneImagePath(normalized) || looksLikeInstructionScaffold(normalized)) {
|
|
1850
|
+
return void 0;
|
|
1851
|
+
}
|
|
1852
|
+
return normalized;
|
|
1853
|
+
}
|
|
1854
|
+
function looksLikeGeneratedTagEnvelope(value) {
|
|
1855
|
+
return /^<[\w:-]+>[\s\S]*<\/[\w:-]+>$/.test(value);
|
|
1856
|
+
}
|
|
1857
|
+
function looksLikeGeneratedImageSummary(value) {
|
|
1858
|
+
return /^\[image:/i.test(value) || /displayed at/i.test(value) && /coordinates/i.test(value);
|
|
1859
|
+
}
|
|
1860
|
+
function looksLikeStandaloneImagePath(value) {
|
|
1861
|
+
return /^\/\S+\.(png|jpe?g|gif|webp|heic|bmp)$/i.test(value) || /^file:\S+\.(png|jpe?g|gif|webp|heic|bmp)$/i.test(value);
|
|
1862
|
+
}
|
|
1863
|
+
function looksLikeInstructionScaffold(value) {
|
|
1864
|
+
if (value.length < 700) {
|
|
1865
|
+
return false;
|
|
1866
|
+
}
|
|
1867
|
+
const headingCount = value.match(/^#{1,3}\s/gm)?.length ?? 0;
|
|
1868
|
+
const tagCount = value.match(/<\/?[\w:-]+>/g)?.length ?? 0;
|
|
1869
|
+
const bulletCount = value.match(/^\s*[-*]\s/gm)?.length ?? 0;
|
|
1870
|
+
return headingCount + tagCount + bulletCount >= 6;
|
|
1871
|
+
}
|
|
1872
|
+
function stripAnsi(value) {
|
|
1873
|
+
return value.replace(/\u001B\[[0-9;]*m/g, "");
|
|
1874
|
+
}
|
|
1875
|
+
function getGitInfo(cwd) {
|
|
1876
|
+
try {
|
|
1877
|
+
const repoRoot = execSync("git rev-parse --show-toplevel", {
|
|
1878
|
+
encoding: "utf-8",
|
|
1879
|
+
cwd,
|
|
1880
|
+
timeout: 3e3
|
|
1881
|
+
}).trim();
|
|
1882
|
+
const branch = execSync("git rev-parse --abbrev-ref HEAD", {
|
|
1883
|
+
encoding: "utf-8",
|
|
1884
|
+
cwd,
|
|
1885
|
+
timeout: 3e3
|
|
1886
|
+
}).trim();
|
|
1887
|
+
return {
|
|
1888
|
+
repoRoot: repoRoot || void 0,
|
|
1889
|
+
branch: branch || void 0
|
|
1890
|
+
};
|
|
1891
|
+
} catch {
|
|
1892
|
+
return {};
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
|
|
1896
|
+
// src/bridge-service.ts
|
|
1897
|
+
var CONFIG_DIR = process.env.VECTOR_HOME?.trim() || join2(homedir3(), ".vector");
|
|
1898
|
+
var BRIDGE_CONFIG_FILE = join2(CONFIG_DIR, "bridge.json");
|
|
1899
|
+
var DEVICE_KEY_FILE = join2(CONFIG_DIR, "device-key");
|
|
1900
|
+
var PID_FILE = join2(CONFIG_DIR, "bridge.pid");
|
|
1901
|
+
var LIVE_ACTIVITIES_CACHE = join2(CONFIG_DIR, "live-activities.json");
|
|
1902
|
+
var LAUNCHAGENT_DIR = join2(homedir3(), "Library", "LaunchAgents");
|
|
1903
|
+
var LAUNCHAGENT_PLIST = join2(LAUNCHAGENT_DIR, "com.vector.bridge.plist");
|
|
1904
|
+
var LAUNCHAGENT_LABEL = "com.vector.bridge";
|
|
1905
|
+
var LEGACY_MENUBAR_LAUNCHAGENT_LABEL = "com.vector.menubar";
|
|
1906
|
+
var LEGACY_MENUBAR_LAUNCHAGENT_PLIST = join2(
|
|
1907
|
+
LAUNCHAGENT_DIR,
|
|
1908
|
+
`${LEGACY_MENUBAR_LAUNCHAGENT_LABEL}.plist`
|
|
1909
|
+
);
|
|
1910
|
+
var HEARTBEAT_INTERVAL_MS = 3e4;
|
|
1911
|
+
var COMMAND_POLL_INTERVAL_MS = 5e3;
|
|
1912
|
+
var LIVE_ACTIVITY_SYNC_INTERVAL_MS = 5e3;
|
|
1913
|
+
var PROCESS_DISCOVERY_INTERVAL_MS = 6e4;
|
|
1914
|
+
function loadBridgeConfig() {
|
|
1915
|
+
if (!existsSync2(BRIDGE_CONFIG_FILE)) return null;
|
|
1916
|
+
try {
|
|
1917
|
+
return JSON.parse(readFileSync2(BRIDGE_CONFIG_FILE, "utf-8"));
|
|
1918
|
+
} catch {
|
|
1919
|
+
return null;
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
function saveBridgeConfig(config) {
|
|
1923
|
+
if (!existsSync2(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
|
|
1924
|
+
writeFileSync(BRIDGE_CONFIG_FILE, JSON.stringify(config, null, 2));
|
|
1925
|
+
persistDeviceKey(config.deviceKey);
|
|
1926
|
+
}
|
|
1927
|
+
function writeLiveActivitiesCache(activities) {
|
|
1928
|
+
if (!existsSync2(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
|
|
1929
|
+
writeFileSync(LIVE_ACTIVITIES_CACHE, JSON.stringify(activities, null, 2));
|
|
1930
|
+
}
|
|
1931
|
+
var BridgeService = class {
|
|
1932
|
+
constructor(config) {
|
|
1933
|
+
this.timers = [];
|
|
1934
|
+
this.config = config;
|
|
1935
|
+
this.client = new ConvexHttpClient2(config.convexUrl);
|
|
1936
|
+
}
|
|
1937
|
+
async heartbeat() {
|
|
1938
|
+
await this.client.mutation(api.agentBridge.bridgePublic.heartbeat, {
|
|
1939
|
+
deviceId: this.config.deviceId,
|
|
1940
|
+
deviceSecret: this.config.deviceSecret
|
|
1941
|
+
});
|
|
1942
|
+
}
|
|
1943
|
+
async pollCommands() {
|
|
1944
|
+
const commands = await this.client.query(
|
|
1945
|
+
api.agentBridge.bridgePublic.getPendingCommands,
|
|
1946
|
+
{
|
|
1947
|
+
deviceId: this.config.deviceId,
|
|
1948
|
+
deviceSecret: this.config.deviceSecret
|
|
1949
|
+
}
|
|
1950
|
+
);
|
|
1951
|
+
if (commands.length > 0) {
|
|
1952
|
+
console.log(`[${ts()}] ${commands.length} pending command(s)`);
|
|
1953
|
+
}
|
|
1954
|
+
for (const cmd of commands) {
|
|
1955
|
+
await this.handleCommand(cmd);
|
|
1956
|
+
}
|
|
1957
|
+
}
|
|
1958
|
+
async handleCommand(cmd) {
|
|
1959
|
+
const claimed = await this.client.mutation(
|
|
1960
|
+
api.agentBridge.bridgePublic.claimCommand,
|
|
1961
|
+
{
|
|
1962
|
+
deviceId: this.config.deviceId,
|
|
1963
|
+
deviceSecret: this.config.deviceSecret,
|
|
1964
|
+
commandId: cmd._id
|
|
1965
|
+
}
|
|
1966
|
+
);
|
|
1967
|
+
if (!claimed) {
|
|
1968
|
+
return;
|
|
1969
|
+
}
|
|
1970
|
+
console.log(` ${cmd.kind}: ${cmd._id}`);
|
|
1971
|
+
try {
|
|
1972
|
+
switch (cmd.kind) {
|
|
1973
|
+
case "message":
|
|
1974
|
+
await this.handleMessageCommand(cmd);
|
|
1975
|
+
await this.completeCommand(cmd._id, "delivered");
|
|
1976
|
+
return;
|
|
1977
|
+
case "launch":
|
|
1978
|
+
await this.handleLaunchCommand(cmd);
|
|
1979
|
+
await this.completeCommand(cmd._id, "delivered");
|
|
1980
|
+
return;
|
|
1981
|
+
default:
|
|
1982
|
+
throw new Error(`Unsupported bridge command: ${cmd.kind}`);
|
|
1983
|
+
}
|
|
1984
|
+
} catch (error) {
|
|
1985
|
+
const message = error instanceof Error ? error.message : "Unknown bridge error";
|
|
1986
|
+
console.error(` ! ${message}`);
|
|
1987
|
+
await this.postCommandError(cmd, message);
|
|
1988
|
+
await this.completeCommand(cmd._id, "failed");
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
async reportProcesses() {
|
|
1992
|
+
const processes = discoverAttachableSessions();
|
|
1993
|
+
const activeSessionKeys = processes.map((proc) => proc.sessionKey).filter((value) => Boolean(value));
|
|
1994
|
+
const activeLocalProcessIds = processes.map((proc) => proc.localProcessId).filter((value) => Boolean(value));
|
|
1995
|
+
for (const proc of processes) {
|
|
1996
|
+
try {
|
|
1997
|
+
await this.reportProcess(proc);
|
|
1998
|
+
} catch {
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
try {
|
|
2002
|
+
await this.client.mutation(
|
|
2003
|
+
api.agentBridge.bridgePublic.reconcileObservedProcesses,
|
|
2004
|
+
{
|
|
2005
|
+
deviceId: this.config.deviceId,
|
|
2006
|
+
deviceSecret: this.config.deviceSecret,
|
|
2007
|
+
activeSessionKeys,
|
|
2008
|
+
activeLocalProcessIds
|
|
2009
|
+
}
|
|
2010
|
+
);
|
|
2011
|
+
} catch {
|
|
2012
|
+
}
|
|
2013
|
+
if (processes.length > 0) {
|
|
2014
|
+
console.log(
|
|
2015
|
+
`[${ts()}] Discovered ${processes.length} attachable session(s)`
|
|
2016
|
+
);
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
async refreshLiveActivities() {
|
|
2020
|
+
try {
|
|
2021
|
+
const activities = await this.client.query(
|
|
2022
|
+
api.agentBridge.bridgePublic.getDeviceLiveActivities,
|
|
2023
|
+
{
|
|
2024
|
+
deviceId: this.config.deviceId,
|
|
2025
|
+
deviceSecret: this.config.deviceSecret
|
|
2026
|
+
}
|
|
2027
|
+
);
|
|
2028
|
+
writeLiveActivitiesCache(activities);
|
|
2029
|
+
await this.syncWorkSessionTerminals(activities);
|
|
2030
|
+
} catch {
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
async syncWorkSessionTerminals(activities) {
|
|
2034
|
+
for (const activity of activities) {
|
|
2035
|
+
if (!activity.workSessionId || !activity.tmuxPaneId) {
|
|
2036
|
+
continue;
|
|
2037
|
+
}
|
|
2038
|
+
try {
|
|
2039
|
+
await this.refreshWorkSessionTerminal(activity.workSessionId, {
|
|
2040
|
+
tmuxPaneId: activity.tmuxPaneId,
|
|
2041
|
+
cwd: activity.cwd,
|
|
2042
|
+
repoRoot: activity.repoRoot,
|
|
2043
|
+
branch: activity.branch,
|
|
2044
|
+
agentProvider: activity.agentProvider,
|
|
2045
|
+
agentSessionKey: activity.agentSessionKey
|
|
2046
|
+
});
|
|
2047
|
+
await this.verifyManagedWorkSession(activity);
|
|
2048
|
+
} catch {
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
}
|
|
2052
|
+
async verifyManagedWorkSession(activity) {
|
|
2053
|
+
if (!activity.workSessionId || !activity.tmuxPaneId || !activity.agentProvider || !isBridgeProvider(activity.agentProvider) || activity.agentProcessId) {
|
|
2054
|
+
return;
|
|
2055
|
+
}
|
|
2056
|
+
const workspacePath = activity.workspacePath ?? activity.cwd ?? activity.repoRoot;
|
|
2057
|
+
if (!workspacePath) {
|
|
2058
|
+
return;
|
|
2059
|
+
}
|
|
2060
|
+
const attachedSession = await this.attachObservedAgentSession(
|
|
2061
|
+
activity.agentProvider,
|
|
2062
|
+
workspacePath
|
|
2063
|
+
);
|
|
2064
|
+
if (!attachedSession) {
|
|
2065
|
+
return;
|
|
2066
|
+
}
|
|
2067
|
+
await this.refreshWorkSessionTerminal(activity.workSessionId, {
|
|
2068
|
+
tmuxPaneId: activity.tmuxPaneId,
|
|
2069
|
+
cwd: attachedSession.process.cwd ?? activity.cwd ?? workspacePath,
|
|
2070
|
+
repoRoot: attachedSession.process.repoRoot ?? activity.repoRoot ?? workspacePath,
|
|
2071
|
+
branch: attachedSession.process.branch ?? activity.branch,
|
|
2072
|
+
agentProvider: attachedSession.process.provider,
|
|
2073
|
+
agentSessionKey: attachedSession.process.sessionKey
|
|
2074
|
+
});
|
|
2075
|
+
await this.postAgentMessage(
|
|
2076
|
+
activity._id,
|
|
2077
|
+
"status",
|
|
2078
|
+
`Verified ${providerLabel(attachedSession.process.provider)} in ${activity.tmuxPaneId}`
|
|
2079
|
+
);
|
|
2080
|
+
await this.updateLiveActivity(activity._id, {
|
|
2081
|
+
status: "waiting_for_input",
|
|
2082
|
+
latestSummary: `Verified ${providerLabel(attachedSession.process.provider)} in ${activity.tmuxPaneId}`,
|
|
2083
|
+
processId: attachedSession.processId,
|
|
2084
|
+
title: activity.title
|
|
2085
|
+
});
|
|
2086
|
+
}
|
|
2087
|
+
async refreshWorkSessionTerminal(workSessionId, metadata) {
|
|
2088
|
+
if (!workSessionId || !metadata.tmuxPaneId) {
|
|
2089
|
+
return;
|
|
2090
|
+
}
|
|
2091
|
+
const terminalSnapshot = captureTmuxPane(metadata.tmuxPaneId);
|
|
2092
|
+
await this.client.mutation(
|
|
2093
|
+
api.agentBridge.bridgePublic.updateWorkSessionTerminal,
|
|
2094
|
+
{
|
|
2095
|
+
deviceId: this.config.deviceId,
|
|
2096
|
+
deviceSecret: this.config.deviceSecret,
|
|
2097
|
+
workSessionId,
|
|
2098
|
+
terminalSnapshot,
|
|
2099
|
+
tmuxSessionName: metadata.tmuxSessionName,
|
|
2100
|
+
tmuxWindowName: metadata.tmuxWindowName,
|
|
2101
|
+
tmuxPaneId: metadata.tmuxPaneId,
|
|
2102
|
+
cwd: metadata.cwd,
|
|
2103
|
+
repoRoot: metadata.repoRoot,
|
|
2104
|
+
branch: metadata.branch,
|
|
2105
|
+
agentProvider: metadata.agentProvider,
|
|
2106
|
+
agentSessionKey: metadata.agentSessionKey
|
|
2107
|
+
}
|
|
2108
|
+
);
|
|
2109
|
+
}
|
|
2110
|
+
async run() {
|
|
2111
|
+
console.log("Vector Bridge Service");
|
|
2112
|
+
console.log(
|
|
2113
|
+
` Device: ${this.config.displayName} (${this.config.deviceId})`
|
|
2114
|
+
);
|
|
2115
|
+
console.log(` Convex: ${this.config.convexUrl}`);
|
|
2116
|
+
console.log(` PID: ${process.pid}`);
|
|
2117
|
+
console.log("");
|
|
2118
|
+
if (!existsSync2(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
|
|
2119
|
+
writeFileSync(PID_FILE, String(process.pid));
|
|
2120
|
+
await this.heartbeat();
|
|
2121
|
+
await this.reportProcesses();
|
|
2122
|
+
await this.refreshLiveActivities();
|
|
2123
|
+
console.log(`[${ts()}] Service running. Ctrl+C to stop.
|
|
2124
|
+
`);
|
|
2125
|
+
this.timers.push(
|
|
2126
|
+
setInterval(() => {
|
|
2127
|
+
this.heartbeat().catch(
|
|
2128
|
+
(e) => console.error(`[${ts()}] Heartbeat error:`, e.message)
|
|
2129
|
+
);
|
|
2130
|
+
}, HEARTBEAT_INTERVAL_MS)
|
|
2131
|
+
);
|
|
2132
|
+
this.timers.push(
|
|
2133
|
+
setInterval(() => {
|
|
2134
|
+
this.pollCommands().catch(
|
|
2135
|
+
(e) => console.error(`[${ts()}] Command poll error:`, e.message)
|
|
2136
|
+
);
|
|
2137
|
+
}, COMMAND_POLL_INTERVAL_MS)
|
|
2138
|
+
);
|
|
2139
|
+
this.timers.push(
|
|
2140
|
+
setInterval(() => {
|
|
2141
|
+
this.refreshLiveActivities().catch(
|
|
2142
|
+
(e) => console.error(`[${ts()}] Live activity sync error:`, e.message)
|
|
2143
|
+
);
|
|
2144
|
+
}, LIVE_ACTIVITY_SYNC_INTERVAL_MS)
|
|
2145
|
+
);
|
|
2146
|
+
this.timers.push(
|
|
2147
|
+
setInterval(() => {
|
|
2148
|
+
this.reportProcesses().catch(
|
|
2149
|
+
(e) => console.error(`[${ts()}] Discovery error:`, e.message)
|
|
2150
|
+
);
|
|
2151
|
+
}, PROCESS_DISCOVERY_INTERVAL_MS)
|
|
2152
|
+
);
|
|
2153
|
+
const shutdown = () => {
|
|
2154
|
+
console.log(`
|
|
2155
|
+
[${ts()}] Shutting down...`);
|
|
2156
|
+
for (const t of this.timers) clearInterval(t);
|
|
2157
|
+
try {
|
|
2158
|
+
unlinkSync(PID_FILE);
|
|
2159
|
+
} catch {
|
|
2160
|
+
}
|
|
2161
|
+
try {
|
|
2162
|
+
writeLiveActivitiesCache([]);
|
|
2163
|
+
} catch {
|
|
2164
|
+
}
|
|
2165
|
+
process.exit(0);
|
|
2166
|
+
};
|
|
2167
|
+
process.on("SIGINT", shutdown);
|
|
2168
|
+
process.on("SIGTERM", shutdown);
|
|
2169
|
+
await new Promise(() => {
|
|
2170
|
+
});
|
|
2171
|
+
}
|
|
2172
|
+
async handleMessageCommand(cmd) {
|
|
2173
|
+
if (!cmd.liveActivityId) {
|
|
2174
|
+
throw new Error("Message command is missing liveActivityId");
|
|
2175
|
+
}
|
|
2176
|
+
const payload = cmd.payload;
|
|
2177
|
+
const body = payload?.body?.trim();
|
|
2178
|
+
if (!body) {
|
|
2179
|
+
throw new Error("Message command is missing a body");
|
|
2180
|
+
}
|
|
2181
|
+
const process9 = cmd.process;
|
|
2182
|
+
console.log(` > "${truncateForLog(body)}"`);
|
|
2183
|
+
if (cmd.workSession?.tmuxPaneId) {
|
|
2184
|
+
sendTextToTmuxPane(cmd.workSession.tmuxPaneId, body);
|
|
2185
|
+
const attachedSession = cmd.workSession.agentProvider && isBridgeProvider(cmd.workSession.agentProvider) ? await this.attachObservedAgentSession(
|
|
2186
|
+
cmd.workSession.agentProvider,
|
|
2187
|
+
cmd.workSession.workspacePath ?? cmd.workSession.cwd ?? process9?.cwd
|
|
2188
|
+
) : null;
|
|
2189
|
+
await this.postAgentMessage(
|
|
2190
|
+
cmd.liveActivityId,
|
|
2191
|
+
"status",
|
|
2192
|
+
"Sent input to work session terminal"
|
|
2193
|
+
);
|
|
2194
|
+
await this.refreshWorkSessionTerminal(cmd.workSession._id, {
|
|
2195
|
+
tmuxSessionName: cmd.workSession.tmuxSessionName,
|
|
2196
|
+
tmuxWindowName: cmd.workSession.tmuxWindowName,
|
|
2197
|
+
tmuxPaneId: cmd.workSession.tmuxPaneId,
|
|
2198
|
+
cwd: cmd.workSession.cwd,
|
|
2199
|
+
repoRoot: cmd.workSession.repoRoot,
|
|
2200
|
+
branch: cmd.workSession.branch,
|
|
2201
|
+
agentProvider: attachedSession?.process.provider ?? cmd.workSession.agentProvider,
|
|
2202
|
+
agentSessionKey: attachedSession?.process.sessionKey ?? cmd.workSession.agentSessionKey
|
|
2203
|
+
});
|
|
2204
|
+
await this.updateLiveActivity(cmd.liveActivityId, {
|
|
2205
|
+
status: "waiting_for_input",
|
|
2206
|
+
latestSummary: `Input sent to ${cmd.workSession.tmuxPaneId}`,
|
|
2207
|
+
title: cmd.liveActivity?.title,
|
|
2208
|
+
processId: attachedSession?.processId ?? process9?._id
|
|
2209
|
+
});
|
|
2210
|
+
return;
|
|
2211
|
+
}
|
|
2212
|
+
if (!process9 || !process9.supportsInboundMessages || !process9.sessionKey || !process9.cwd || !isBridgeProvider(process9.provider)) {
|
|
2213
|
+
throw new Error("No resumable local session is attached to this issue");
|
|
2214
|
+
}
|
|
2215
|
+
await this.reportProcess({
|
|
2216
|
+
provider: process9.provider,
|
|
2217
|
+
providerLabel: process9.providerLabel ?? providerLabel(process9.provider),
|
|
2218
|
+
sessionKey: process9.sessionKey,
|
|
2219
|
+
cwd: process9.cwd,
|
|
2220
|
+
repoRoot: process9.repoRoot,
|
|
2221
|
+
branch: process9.branch,
|
|
2222
|
+
title: process9.title,
|
|
2223
|
+
model: process9.model,
|
|
2224
|
+
mode: "managed",
|
|
2225
|
+
status: "waiting",
|
|
2226
|
+
supportsInboundMessages: true
|
|
2227
|
+
});
|
|
2228
|
+
await this.updateLiveActivity(cmd.liveActivityId, {
|
|
2229
|
+
status: "active",
|
|
2230
|
+
processId: process9._id,
|
|
2231
|
+
title: cmd.liveActivity?.title ?? process9.title
|
|
2232
|
+
});
|
|
2233
|
+
const result = await resumeProviderSession(
|
|
2234
|
+
process9.provider,
|
|
2235
|
+
process9.sessionKey,
|
|
2236
|
+
process9.cwd,
|
|
2237
|
+
body
|
|
2238
|
+
);
|
|
2239
|
+
const processId = await this.reportProcess(result);
|
|
2240
|
+
if (result.responseText) {
|
|
2241
|
+
await this.postAgentMessage(
|
|
2242
|
+
cmd.liveActivityId,
|
|
2243
|
+
"assistant",
|
|
2244
|
+
result.responseText
|
|
2245
|
+
);
|
|
2246
|
+
console.log(` < "${truncateForLog(result.responseText)}"`);
|
|
2247
|
+
}
|
|
2248
|
+
await this.updateLiveActivity(cmd.liveActivityId, {
|
|
2249
|
+
processId,
|
|
2250
|
+
status: "waiting_for_input",
|
|
2251
|
+
latestSummary: summarizeMessage(result.responseText),
|
|
2252
|
+
title: cmd.liveActivity?.title ?? process9.title
|
|
2253
|
+
});
|
|
2254
|
+
}
|
|
2255
|
+
async handleLaunchCommand(cmd) {
|
|
2256
|
+
if (!cmd.liveActivityId) {
|
|
2257
|
+
throw new Error("Launch command is missing liveActivityId");
|
|
2258
|
+
}
|
|
2259
|
+
const payload = cmd.payload;
|
|
2260
|
+
const workspacePath = payload?.workspacePath?.trim();
|
|
2261
|
+
if (!workspacePath) {
|
|
2262
|
+
throw new Error("Launch command is missing workspacePath");
|
|
2263
|
+
}
|
|
2264
|
+
const requestedProvider = payload?.provider;
|
|
2265
|
+
const provider = requestedProvider && isBridgeProvider(requestedProvider) ? requestedProvider : void 0;
|
|
2266
|
+
const issueKey = payload?.issueKey ?? cmd.liveActivity?.issueKey ?? "ISSUE";
|
|
2267
|
+
const issueTitle = payload?.issueTitle ?? cmd.liveActivity?.issueTitle ?? "Untitled issue";
|
|
2268
|
+
const prompt2 = buildLaunchPrompt(issueKey, issueTitle, workspacePath);
|
|
2269
|
+
const launchLabel = provider ? providerLabel(provider) : "shell session";
|
|
2270
|
+
const workSessionTitle = `${issueKey}: ${issueTitle}`;
|
|
2271
|
+
const sessionsBeforeLaunch = provider ? listObservedSessionsForWorkspace(provider, workspacePath) : [];
|
|
2272
|
+
await this.updateLiveActivity(cmd.liveActivityId, {
|
|
2273
|
+
status: "active",
|
|
2274
|
+
latestSummary: `Launching ${launchLabel} in ${workspacePath}`,
|
|
2275
|
+
delegatedRunId: payload?.delegatedRunId,
|
|
2276
|
+
launchStatus: "launching",
|
|
2277
|
+
title: workSessionTitle
|
|
2278
|
+
});
|
|
2279
|
+
await this.postAgentMessage(
|
|
2280
|
+
cmd.liveActivityId,
|
|
2281
|
+
"status",
|
|
2282
|
+
`Launching ${launchLabel} in ${workspacePath}`
|
|
2283
|
+
);
|
|
2284
|
+
const tmuxSession = createTmuxWorkSession({
|
|
2285
|
+
workspacePath,
|
|
2286
|
+
issueKey,
|
|
2287
|
+
issueTitle,
|
|
2288
|
+
provider,
|
|
2289
|
+
prompt: prompt2
|
|
2290
|
+
});
|
|
2291
|
+
const attachedSession = provider ? await this.attachObservedAgentSession(
|
|
2292
|
+
provider,
|
|
2293
|
+
workspacePath,
|
|
2294
|
+
sessionsBeforeLaunch,
|
|
2295
|
+
tmuxSession.paneProcessId
|
|
2296
|
+
) : null;
|
|
2297
|
+
await this.refreshWorkSessionTerminal(cmd.workSession?._id, {
|
|
2298
|
+
tmuxSessionName: tmuxSession.sessionName,
|
|
2299
|
+
tmuxWindowName: tmuxSession.windowName,
|
|
2300
|
+
tmuxPaneId: tmuxSession.paneId,
|
|
2301
|
+
cwd: workspacePath,
|
|
2302
|
+
repoRoot: workspacePath,
|
|
2303
|
+
branch: currentGitBranch(workspacePath),
|
|
2304
|
+
agentProvider: provider,
|
|
2305
|
+
agentSessionKey: attachedSession?.process.sessionKey
|
|
2306
|
+
});
|
|
2307
|
+
if (provider && !attachedSession) {
|
|
2308
|
+
await this.postAgentMessage(
|
|
2309
|
+
cmd.liveActivityId,
|
|
2310
|
+
"status",
|
|
2311
|
+
`Started tmux session ${tmuxSession.sessionName}:${tmuxSession.windowName}. Waiting to verify ${providerLabel(provider)} in ${tmuxSession.paneId}.`
|
|
2312
|
+
);
|
|
2313
|
+
await this.updateLiveActivity(cmd.liveActivityId, {
|
|
2314
|
+
status: "waiting_for_input",
|
|
2315
|
+
latestSummary: `Running in ${tmuxSession.sessionName}:${tmuxSession.windowName}; waiting to verify ${providerLabel(provider)}`,
|
|
2316
|
+
delegatedRunId: payload?.delegatedRunId,
|
|
2317
|
+
launchStatus: "running",
|
|
2318
|
+
title: `${providerLabel(provider)} on ${this.config.displayName}`
|
|
2319
|
+
});
|
|
2320
|
+
return;
|
|
2321
|
+
}
|
|
2322
|
+
await this.updateLiveActivity(cmd.liveActivityId, {
|
|
2323
|
+
status: "waiting_for_input",
|
|
2324
|
+
latestSummary: `Running in ${tmuxSession.sessionName}:${tmuxSession.windowName}`,
|
|
2325
|
+
delegatedRunId: payload?.delegatedRunId,
|
|
2326
|
+
launchStatus: "running",
|
|
2327
|
+
processId: attachedSession?.processId,
|
|
2328
|
+
title: workSessionTitle
|
|
2329
|
+
});
|
|
2330
|
+
}
|
|
2331
|
+
async attachObservedAgentSession(provider, workspacePath, sessionsBeforeLaunch = [], paneProcessId) {
|
|
2332
|
+
if (!workspacePath) {
|
|
2333
|
+
return null;
|
|
2334
|
+
}
|
|
2335
|
+
const existingKeys = new Set(
|
|
2336
|
+
sessionsBeforeLaunch.map(sessionIdentityKey).filter(Boolean)
|
|
2337
|
+
);
|
|
2338
|
+
for (let attempt = 0; attempt < 10; attempt += 1) {
|
|
2339
|
+
const observedSessions = listObservedSessionsForWorkspace(
|
|
2340
|
+
provider,
|
|
2341
|
+
workspacePath
|
|
2342
|
+
);
|
|
2343
|
+
const candidate = (paneProcessId ? findObservedSessionInProcessTree(observedSessions, paneProcessId) : void 0) ?? observedSessions.find(
|
|
2344
|
+
(session) => !existingKeys.has(sessionIdentityKey(session))
|
|
2345
|
+
) ?? (attempt === 9 ? observedSessions[0] : void 0);
|
|
2346
|
+
if (candidate) {
|
|
2347
|
+
const processId = await this.reportProcess(candidate);
|
|
2348
|
+
return {
|
|
2349
|
+
process: candidate,
|
|
2350
|
+
processId
|
|
2351
|
+
};
|
|
2352
|
+
}
|
|
2353
|
+
await sleep(750);
|
|
2354
|
+
}
|
|
2355
|
+
return null;
|
|
2356
|
+
}
|
|
2357
|
+
async reportProcess(process9) {
|
|
2358
|
+
const {
|
|
2359
|
+
provider,
|
|
2360
|
+
providerLabel: providerLabel2,
|
|
2361
|
+
localProcessId,
|
|
2362
|
+
sessionKey,
|
|
2363
|
+
cwd,
|
|
2364
|
+
repoRoot,
|
|
2365
|
+
branch,
|
|
2366
|
+
title,
|
|
2367
|
+
model,
|
|
2368
|
+
mode,
|
|
2369
|
+
status,
|
|
2370
|
+
supportsInboundMessages
|
|
2371
|
+
} = process9;
|
|
2372
|
+
return await this.client.mutation(
|
|
2373
|
+
api.agentBridge.bridgePublic.reportProcess,
|
|
2374
|
+
{
|
|
2375
|
+
deviceId: this.config.deviceId,
|
|
2376
|
+
deviceSecret: this.config.deviceSecret,
|
|
2377
|
+
provider,
|
|
2378
|
+
providerLabel: providerLabel2,
|
|
2379
|
+
localProcessId,
|
|
2380
|
+
sessionKey,
|
|
2381
|
+
cwd,
|
|
2382
|
+
repoRoot,
|
|
2383
|
+
branch,
|
|
2384
|
+
title,
|
|
2385
|
+
model,
|
|
2386
|
+
mode,
|
|
2387
|
+
status,
|
|
2388
|
+
supportsInboundMessages
|
|
2389
|
+
}
|
|
2390
|
+
);
|
|
2391
|
+
}
|
|
2392
|
+
async updateLiveActivity(liveActivityId, args) {
|
|
2393
|
+
await this.client.mutation(
|
|
2394
|
+
api.agentBridge.bridgePublic.updateLiveActivityState,
|
|
2395
|
+
{
|
|
2396
|
+
deviceId: this.config.deviceId,
|
|
2397
|
+
deviceSecret: this.config.deviceSecret,
|
|
2398
|
+
liveActivityId,
|
|
2399
|
+
...args
|
|
2400
|
+
}
|
|
2401
|
+
);
|
|
2402
|
+
}
|
|
2403
|
+
async postAgentMessage(liveActivityId, role, body) {
|
|
2404
|
+
await this.client.mutation(api.agentBridge.bridgePublic.postAgentMessage, {
|
|
2405
|
+
deviceId: this.config.deviceId,
|
|
2406
|
+
deviceSecret: this.config.deviceSecret,
|
|
2407
|
+
liveActivityId,
|
|
2408
|
+
role,
|
|
2409
|
+
body
|
|
2410
|
+
});
|
|
2411
|
+
}
|
|
2412
|
+
async completeCommand(commandId, status) {
|
|
2413
|
+
await this.client.mutation(api.agentBridge.bridgePublic.completeCommand, {
|
|
2414
|
+
deviceId: this.config.deviceId,
|
|
2415
|
+
deviceSecret: this.config.deviceSecret,
|
|
2416
|
+
commandId,
|
|
2417
|
+
status
|
|
2418
|
+
});
|
|
2419
|
+
}
|
|
2420
|
+
async postCommandError(cmd, errorMessage) {
|
|
2421
|
+
if (cmd.kind === "launch" && cmd.liveActivityId) {
|
|
2422
|
+
const payload = cmd.payload;
|
|
2423
|
+
await this.updateLiveActivity(cmd.liveActivityId, {
|
|
2424
|
+
status: "failed",
|
|
2425
|
+
latestSummary: errorMessage,
|
|
2426
|
+
delegatedRunId: payload?.delegatedRunId,
|
|
2427
|
+
launchStatus: "failed"
|
|
2428
|
+
});
|
|
2429
|
+
await this.postAgentMessage(cmd.liveActivityId, "status", errorMessage);
|
|
2430
|
+
return;
|
|
2431
|
+
}
|
|
2432
|
+
if (cmd.kind === "message" && cmd.liveActivityId) {
|
|
2433
|
+
await this.postAgentMessage(cmd.liveActivityId, "status", errorMessage);
|
|
2434
|
+
await this.updateLiveActivity(cmd.liveActivityId, {
|
|
2435
|
+
status: "waiting_for_input",
|
|
2436
|
+
latestSummary: errorMessage
|
|
2437
|
+
});
|
|
2438
|
+
}
|
|
2439
|
+
}
|
|
2440
|
+
};
|
|
2441
|
+
function createTmuxWorkSession(args) {
|
|
2442
|
+
const slug = sanitizeTmuxName(args.issueKey.toLowerCase());
|
|
2443
|
+
const sessionName = `vector-${slug}-${randomUUID().slice(0, 8)}`;
|
|
2444
|
+
const windowName = sanitizeTmuxName(
|
|
2445
|
+
args.provider === "codex" ? "codex" : args.provider === "claude_code" ? "claude" : "shell"
|
|
2446
|
+
);
|
|
2447
|
+
execFileSync("tmux", [
|
|
2448
|
+
"new-session",
|
|
2449
|
+
"-d",
|
|
2450
|
+
"-s",
|
|
2451
|
+
sessionName,
|
|
2452
|
+
"-n",
|
|
2453
|
+
windowName,
|
|
2454
|
+
"-c",
|
|
2455
|
+
args.workspacePath
|
|
2456
|
+
]);
|
|
2457
|
+
const paneId = execFileSync(
|
|
2458
|
+
"tmux",
|
|
2459
|
+
[
|
|
2460
|
+
"display-message",
|
|
2461
|
+
"-p",
|
|
2462
|
+
"-t",
|
|
2463
|
+
`${sessionName}:${windowName}.0`,
|
|
2464
|
+
"#{pane_id}"
|
|
2465
|
+
],
|
|
2466
|
+
{ encoding: "utf-8" }
|
|
2467
|
+
).trim();
|
|
2468
|
+
const paneProcessId = execFileSync(
|
|
2469
|
+
"tmux",
|
|
2470
|
+
["display-message", "-p", "-t", paneId, "#{pane_pid}"],
|
|
2471
|
+
{ encoding: "utf-8" }
|
|
2472
|
+
).trim();
|
|
2473
|
+
if (args.provider) {
|
|
2474
|
+
execFileSync("tmux", [
|
|
2475
|
+
"send-keys",
|
|
2476
|
+
"-t",
|
|
2477
|
+
paneId,
|
|
2478
|
+
buildManagedLaunchCommand(args.provider, args.prompt),
|
|
2479
|
+
"Enter"
|
|
2480
|
+
]);
|
|
2481
|
+
} else {
|
|
2482
|
+
execFileSync("tmux", [
|
|
2483
|
+
"send-keys",
|
|
2484
|
+
"-t",
|
|
2485
|
+
paneId,
|
|
2486
|
+
`printf '%s\\n\\n' ${shellQuote(args.prompt)}`,
|
|
2487
|
+
"Enter"
|
|
2488
|
+
]);
|
|
2489
|
+
}
|
|
2490
|
+
return {
|
|
2491
|
+
sessionName,
|
|
2492
|
+
windowName,
|
|
2493
|
+
paneId,
|
|
2494
|
+
paneProcessId
|
|
2495
|
+
};
|
|
2496
|
+
}
|
|
2497
|
+
function sendTextToTmuxPane(paneId, text2) {
|
|
2498
|
+
execFileSync("tmux", ["set-buffer", "--", text2]);
|
|
2499
|
+
execFileSync("tmux", ["paste-buffer", "-t", paneId]);
|
|
2500
|
+
execFileSync("tmux", ["send-keys", "-t", paneId, "Enter"]);
|
|
2501
|
+
execFileSync("tmux", ["delete-buffer"]);
|
|
2502
|
+
}
|
|
2503
|
+
function captureTmuxPane(paneId) {
|
|
2504
|
+
return execFileSync(
|
|
2505
|
+
"tmux",
|
|
2506
|
+
["capture-pane", "-p", "-t", paneId, "-S", "-120"],
|
|
2507
|
+
{ encoding: "utf-8" }
|
|
2508
|
+
).replace(/\u001B\[[0-9;?]*[A-Za-z]/g, "").trimEnd();
|
|
2509
|
+
}
|
|
2510
|
+
function currentGitBranch(cwd) {
|
|
2511
|
+
try {
|
|
2512
|
+
return execSync2("git rev-parse --abbrev-ref HEAD", {
|
|
2513
|
+
encoding: "utf-8",
|
|
2514
|
+
cwd,
|
|
2515
|
+
timeout: 3e3
|
|
2516
|
+
}).trim();
|
|
2517
|
+
} catch {
|
|
2518
|
+
return void 0;
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
2521
|
+
function buildManagedLaunchCommand(provider, prompt2) {
|
|
2522
|
+
if (provider === "codex") {
|
|
2523
|
+
return `codex --no-alt-screen -a never ${shellQuote(prompt2)}`;
|
|
2524
|
+
}
|
|
2525
|
+
return `claude --permission-mode bypassPermissions --dangerously-skip-permissions ${shellQuote(prompt2)}`;
|
|
2526
|
+
}
|
|
2527
|
+
function sanitizeTmuxName(value) {
|
|
2528
|
+
return value.replace(/[^a-z0-9_-]+/gi, "-").replace(/^-+|-+$/g, "") || "work";
|
|
2529
|
+
}
|
|
2530
|
+
function shellQuote(value) {
|
|
2531
|
+
return `'${value.replace(/'/g, `'"'"'`)}'`;
|
|
2532
|
+
}
|
|
2533
|
+
async function setupBridgeDevice(client, convexUrl) {
|
|
2534
|
+
const deviceKey = getStableDeviceKey();
|
|
2535
|
+
const displayName = `${process.env.USER ?? "user"}'s ${platform() === "darwin" ? "Mac" : "machine"}`;
|
|
2536
|
+
const result = await client.mutation(
|
|
2537
|
+
api.agentBridge.mutations.registerBridgeDevice,
|
|
2538
|
+
{
|
|
2539
|
+
deviceKey,
|
|
2540
|
+
displayName,
|
|
2541
|
+
hostname: hostname(),
|
|
2542
|
+
platform: platform(),
|
|
2543
|
+
serviceType: "foreground",
|
|
2544
|
+
cliVersion: "0.1.0",
|
|
2545
|
+
capabilities: ["codex", "claude_code"]
|
|
2546
|
+
}
|
|
2547
|
+
);
|
|
2548
|
+
const config = {
|
|
2549
|
+
deviceId: result.deviceId,
|
|
2550
|
+
deviceKey,
|
|
2551
|
+
deviceSecret: result.deviceSecret,
|
|
2552
|
+
userId: result.userId,
|
|
2553
|
+
displayName,
|
|
2554
|
+
convexUrl,
|
|
2555
|
+
registeredAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2556
|
+
};
|
|
2557
|
+
saveBridgeConfig(config);
|
|
2558
|
+
return config;
|
|
2559
|
+
}
|
|
2560
|
+
function getStableDeviceKey() {
|
|
2561
|
+
const existingConfig = loadBridgeConfig();
|
|
2562
|
+
const existingKey = existingConfig?.deviceKey?.trim();
|
|
2563
|
+
if (existingKey) {
|
|
2564
|
+
persistDeviceKey(existingKey);
|
|
2565
|
+
return existingKey;
|
|
2566
|
+
}
|
|
2567
|
+
if (existsSync2(DEVICE_KEY_FILE)) {
|
|
2568
|
+
const savedKey = readFileSync2(DEVICE_KEY_FILE, "utf-8").trim();
|
|
2569
|
+
if (savedKey) {
|
|
2570
|
+
return savedKey;
|
|
2571
|
+
}
|
|
2572
|
+
}
|
|
2573
|
+
const generatedKey = `${hostname()}-${randomUUID().slice(0, 8)}`;
|
|
2574
|
+
persistDeviceKey(generatedKey);
|
|
2575
|
+
return generatedKey;
|
|
2576
|
+
}
|
|
2577
|
+
function persistDeviceKey(deviceKey) {
|
|
2578
|
+
if (!existsSync2(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
|
|
2579
|
+
writeFileSync(DEVICE_KEY_FILE, `${deviceKey}
|
|
2580
|
+
`);
|
|
2581
|
+
}
|
|
2582
|
+
function buildLaunchPrompt(issueKey, issueTitle, workspacePath) {
|
|
2583
|
+
return [
|
|
2584
|
+
`You are working on Vector issue ${issueKey}: ${issueTitle}.`,
|
|
2585
|
+
`The repository is already checked out at ${workspacePath}.`,
|
|
2586
|
+
"Inspect the codebase, identify the relevant implementation area, and start the work.",
|
|
2587
|
+
"In your first reply, summarize your plan and the first concrete step you are taking."
|
|
2588
|
+
].join("\n\n");
|
|
2589
|
+
}
|
|
2590
|
+
function summarizeMessage(message) {
|
|
2591
|
+
if (!message) {
|
|
2592
|
+
return void 0;
|
|
2593
|
+
}
|
|
2594
|
+
return message.length > 120 ? `${message.slice(0, 117).trimEnd()}...` : message;
|
|
2595
|
+
}
|
|
2596
|
+
function truncateForLog(message) {
|
|
2597
|
+
return message.length > 80 ? `${message.slice(0, 77).trimEnd()}...` : message;
|
|
2598
|
+
}
|
|
2599
|
+
function listObservedSessionsForWorkspace(provider, workspacePath) {
|
|
2600
|
+
return discoverAttachableSessions().filter(
|
|
2601
|
+
(session) => session.provider === provider && matchesWorkspacePath(session, workspacePath)
|
|
2602
|
+
).sort(compareLocalSessionRecency);
|
|
2603
|
+
}
|
|
2604
|
+
function findObservedSessionInProcessTree(sessions, paneProcessId) {
|
|
2605
|
+
const descendantIds = listDescendantProcessIds(paneProcessId);
|
|
2606
|
+
if (descendantIds.size === 0) {
|
|
2607
|
+
return void 0;
|
|
2608
|
+
}
|
|
2609
|
+
return sessions.find(
|
|
2610
|
+
(session) => session.localProcessId ? descendantIds.has(session.localProcessId) : false
|
|
2611
|
+
);
|
|
2612
|
+
}
|
|
2613
|
+
function listDescendantProcessIds(rootPid) {
|
|
2614
|
+
const descendants = /* @__PURE__ */ new Set([rootPid]);
|
|
2615
|
+
try {
|
|
2616
|
+
const output = execSync2("ps -axo pid=,ppid=", {
|
|
2617
|
+
encoding: "utf-8",
|
|
2618
|
+
timeout: 3e3
|
|
2619
|
+
});
|
|
2620
|
+
const parentToChildren = /* @__PURE__ */ new Map();
|
|
2621
|
+
for (const line of output.split("\n").map((value) => value.trim()).filter(Boolean)) {
|
|
2622
|
+
const [pid, ppid] = line.split(/\s+/, 2);
|
|
2623
|
+
if (!pid || !ppid) {
|
|
2624
|
+
continue;
|
|
2625
|
+
}
|
|
2626
|
+
const children = parentToChildren.get(ppid) ?? [];
|
|
2627
|
+
children.push(pid);
|
|
2628
|
+
parentToChildren.set(ppid, children);
|
|
2629
|
+
}
|
|
2630
|
+
const queue = [rootPid];
|
|
2631
|
+
while (queue.length > 0) {
|
|
2632
|
+
const currentPid = queue.shift();
|
|
2633
|
+
if (!currentPid) {
|
|
2634
|
+
continue;
|
|
2635
|
+
}
|
|
2636
|
+
for (const childPid of parentToChildren.get(currentPid) ?? []) {
|
|
2637
|
+
if (descendants.has(childPid)) {
|
|
2638
|
+
continue;
|
|
2639
|
+
}
|
|
2640
|
+
descendants.add(childPid);
|
|
2641
|
+
queue.push(childPid);
|
|
2642
|
+
}
|
|
2643
|
+
}
|
|
2644
|
+
} catch {
|
|
2645
|
+
return descendants;
|
|
2646
|
+
}
|
|
2647
|
+
return descendants;
|
|
2648
|
+
}
|
|
2649
|
+
function matchesWorkspacePath(session, workspacePath) {
|
|
2650
|
+
const normalizedWorkspace = normalizePath(workspacePath);
|
|
2651
|
+
const candidatePaths = [session.cwd, session.repoRoot].filter((value) => Boolean(value)).map(normalizePath);
|
|
2652
|
+
return candidatePaths.some((path3) => path3 === normalizedWorkspace);
|
|
2653
|
+
}
|
|
2654
|
+
function normalizePath(value) {
|
|
2655
|
+
return value.replace(/\/+$/, "");
|
|
2656
|
+
}
|
|
2657
|
+
function sessionIdentityKey(session) {
|
|
2658
|
+
return [
|
|
2659
|
+
session.provider,
|
|
2660
|
+
session.sessionKey,
|
|
2661
|
+
session.localProcessId,
|
|
2662
|
+
session.cwd
|
|
2663
|
+
].filter(Boolean).join("::");
|
|
2664
|
+
}
|
|
2665
|
+
function compareLocalSessionRecency(a, b) {
|
|
2666
|
+
return Number(b.localProcessId ?? 0) - Number(a.localProcessId ?? 0);
|
|
2667
|
+
}
|
|
2668
|
+
function sleep(ms) {
|
|
2669
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
2670
|
+
}
|
|
2671
|
+
function isBridgeProvider(provider) {
|
|
2672
|
+
return provider === "codex" || provider === "claude_code";
|
|
2673
|
+
}
|
|
2674
|
+
function providerLabel(provider) {
|
|
2675
|
+
return provider === "codex" ? "Codex" : "Claude";
|
|
2676
|
+
}
|
|
2677
|
+
function installLaunchAgent(vcliPath) {
|
|
2678
|
+
if (platform() !== "darwin") {
|
|
2679
|
+
console.error("LaunchAgent is macOS only. Use systemd on Linux.");
|
|
2680
|
+
return;
|
|
2681
|
+
}
|
|
2682
|
+
const programArguments = getLaunchAgentProgramArguments(vcliPath);
|
|
2683
|
+
const environmentVariables = [
|
|
2684
|
+
" <key>PATH</key>",
|
|
2685
|
+
" <string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>",
|
|
2686
|
+
...process.env.VECTOR_HOME?.trim() ? [
|
|
2687
|
+
" <key>VECTOR_HOME</key>",
|
|
2688
|
+
` <string>${process.env.VECTOR_HOME.trim()}</string>`
|
|
2689
|
+
] : []
|
|
2690
|
+
].join("\n");
|
|
2691
|
+
const plist = `<?xml version="1.0" encoding="UTF-8"?>
|
|
2692
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
2693
|
+
<plist version="1.0">
|
|
2694
|
+
<dict>
|
|
2695
|
+
<key>Label</key>
|
|
2696
|
+
<string>${LAUNCHAGENT_LABEL}</string>
|
|
2697
|
+
<key>ProgramArguments</key>
|
|
2698
|
+
${programArguments}
|
|
2699
|
+
<key>RunAtLoad</key>
|
|
2700
|
+
<true/>
|
|
2701
|
+
<key>KeepAlive</key>
|
|
2702
|
+
<true/>
|
|
2703
|
+
<key>StandardOutPath</key>
|
|
2704
|
+
<string>${CONFIG_DIR}/bridge.log</string>
|
|
2705
|
+
<key>StandardErrorPath</key>
|
|
2706
|
+
<string>${CONFIG_DIR}/bridge.err.log</string>
|
|
2707
|
+
<key>EnvironmentVariables</key>
|
|
2708
|
+
<dict>
|
|
2709
|
+
${environmentVariables}
|
|
2710
|
+
</dict>
|
|
2711
|
+
</dict>
|
|
2712
|
+
</plist>`;
|
|
2713
|
+
if (!existsSync2(LAUNCHAGENT_DIR)) {
|
|
2714
|
+
mkdirSync(LAUNCHAGENT_DIR, { recursive: true });
|
|
2715
|
+
}
|
|
2716
|
+
removeLegacyMenuBarLaunchAgent();
|
|
2717
|
+
writeFileSync(LAUNCHAGENT_PLIST, plist);
|
|
2718
|
+
console.log(`Installed LaunchAgent: ${LAUNCHAGENT_PLIST}`);
|
|
2719
|
+
}
|
|
2720
|
+
function getLaunchAgentProgramArguments(vcliPath) {
|
|
2721
|
+
const args = resolveCliInvocation(vcliPath);
|
|
2722
|
+
return [
|
|
2723
|
+
"<array>",
|
|
2724
|
+
...args.map((arg) => ` <string>${arg}</string>`),
|
|
2725
|
+
" <string>service</string>",
|
|
2726
|
+
" <string>run</string>",
|
|
2727
|
+
" </array>"
|
|
2728
|
+
].join("\n");
|
|
2729
|
+
}
|
|
2730
|
+
function resolveCliInvocation(vcliPath) {
|
|
2731
|
+
if (vcliPath.endsWith(".js")) {
|
|
2732
|
+
return [process.execPath, vcliPath];
|
|
2733
|
+
}
|
|
2734
|
+
if (vcliPath.endsWith(".ts")) {
|
|
2735
|
+
const tsxPath = join2(
|
|
2736
|
+
import.meta.dirname ?? process.cwd(),
|
|
2737
|
+
"..",
|
|
2738
|
+
"..",
|
|
2739
|
+
"..",
|
|
2740
|
+
"node_modules",
|
|
2741
|
+
".bin",
|
|
2742
|
+
"tsx"
|
|
2743
|
+
);
|
|
2744
|
+
if (existsSync2(tsxPath)) {
|
|
2745
|
+
return [tsxPath, vcliPath];
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2748
|
+
return [vcliPath];
|
|
2749
|
+
}
|
|
2750
|
+
function loadLaunchAgent() {
|
|
2751
|
+
if (runLaunchctl(["bootstrap", launchctlGuiDomain(), LAUNCHAGENT_PLIST])) {
|
|
2752
|
+
runLaunchctl([
|
|
2753
|
+
"kickstart",
|
|
2754
|
+
"-k",
|
|
2755
|
+
`${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`
|
|
2756
|
+
]);
|
|
2757
|
+
console.log(
|
|
2758
|
+
"LaunchAgent loaded. Bridge will start automatically on login."
|
|
2759
|
+
);
|
|
2760
|
+
return;
|
|
2761
|
+
}
|
|
2762
|
+
if (runLaunchctl([
|
|
2763
|
+
"kickstart",
|
|
2764
|
+
"-k",
|
|
2765
|
+
`${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`
|
|
2766
|
+
]) || runLaunchctl(["load", LAUNCHAGENT_PLIST])) {
|
|
2767
|
+
console.log(
|
|
2768
|
+
"LaunchAgent loaded. Bridge will start automatically on login."
|
|
2769
|
+
);
|
|
2770
|
+
return;
|
|
2771
|
+
}
|
|
2772
|
+
console.error("Failed to load LaunchAgent");
|
|
2773
|
+
}
|
|
2774
|
+
function unloadLaunchAgent() {
|
|
2775
|
+
if (runLaunchctl(["bootout", `${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`]) || runLaunchctl(["bootout", launchctlGuiDomain(), LAUNCHAGENT_PLIST]) || runLaunchctl(["unload", LAUNCHAGENT_PLIST])) {
|
|
2776
|
+
console.log("LaunchAgent unloaded.");
|
|
2777
|
+
return true;
|
|
2778
|
+
}
|
|
2779
|
+
console.error("Failed to unload LaunchAgent (may not be loaded)");
|
|
2780
|
+
return false;
|
|
2781
|
+
}
|
|
2782
|
+
function uninstallLaunchAgent() {
|
|
2783
|
+
unloadLaunchAgent();
|
|
2784
|
+
removeLegacyMenuBarLaunchAgent();
|
|
2785
|
+
try {
|
|
2786
|
+
unlinkSync(LAUNCHAGENT_PLIST);
|
|
2787
|
+
console.log("LaunchAgent removed.");
|
|
2788
|
+
} catch {
|
|
2789
|
+
}
|
|
2790
|
+
}
|
|
2791
|
+
var MENUBAR_PID_FILE = join2(CONFIG_DIR, "menubar.pid");
|
|
2792
|
+
function removeLegacyMenuBarLaunchAgent() {
|
|
2793
|
+
if (platform() !== "darwin" || !existsSync2(LEGACY_MENUBAR_LAUNCHAGENT_PLIST)) {
|
|
2794
|
+
return;
|
|
2795
|
+
}
|
|
2796
|
+
try {
|
|
2797
|
+
execSync2(`launchctl unload ${LEGACY_MENUBAR_LAUNCHAGENT_PLIST}`, {
|
|
2798
|
+
stdio: "pipe"
|
|
2799
|
+
});
|
|
2800
|
+
} catch {
|
|
2801
|
+
}
|
|
2802
|
+
try {
|
|
2803
|
+
unlinkSync(LEGACY_MENUBAR_LAUNCHAGENT_PLIST);
|
|
2804
|
+
} catch {
|
|
2805
|
+
}
|
|
2806
|
+
}
|
|
2807
|
+
function launchctlGuiDomain() {
|
|
2808
|
+
const uid = typeof process.getuid === "function" ? process.getuid() : typeof process.geteuid === "function" ? process.geteuid() : 0;
|
|
2809
|
+
return `gui/${uid}`;
|
|
2810
|
+
}
|
|
2811
|
+
function runLaunchctl(args) {
|
|
2812
|
+
try {
|
|
2813
|
+
execFileSync("launchctl", args, {
|
|
2814
|
+
stdio: "ignore"
|
|
2815
|
+
});
|
|
2816
|
+
return true;
|
|
2817
|
+
} catch {
|
|
2818
|
+
return false;
|
|
2819
|
+
}
|
|
2820
|
+
}
|
|
2821
|
+
function findCliEntrypoint() {
|
|
2822
|
+
const candidates = [
|
|
2823
|
+
join2(import.meta.dirname ?? "", "index.js"),
|
|
2824
|
+
join2(import.meta.dirname ?? "", "index.ts"),
|
|
2825
|
+
join2(import.meta.dirname ?? "", "..", "dist", "index.js")
|
|
2826
|
+
];
|
|
2827
|
+
for (const p of candidates) {
|
|
2828
|
+
if (existsSync2(p)) return p;
|
|
2829
|
+
}
|
|
2830
|
+
return null;
|
|
2831
|
+
}
|
|
2832
|
+
function getCurrentCliInvocation() {
|
|
2833
|
+
const entrypoint = findCliEntrypoint();
|
|
2834
|
+
if (!entrypoint) {
|
|
2835
|
+
return null;
|
|
2836
|
+
}
|
|
2837
|
+
return resolveCliInvocation(entrypoint);
|
|
2838
|
+
}
|
|
2839
|
+
function findMenuBarExecutable() {
|
|
2840
|
+
const candidates = [
|
|
2841
|
+
join2(
|
|
2842
|
+
import.meta.dirname ?? "",
|
|
2843
|
+
"..",
|
|
2844
|
+
"native",
|
|
2845
|
+
"VectorMenuBar.app",
|
|
2846
|
+
"Contents",
|
|
2847
|
+
"MacOS",
|
|
2848
|
+
"VectorMenuBar"
|
|
2849
|
+
),
|
|
2850
|
+
join2(
|
|
2851
|
+
import.meta.dirname ?? "",
|
|
2852
|
+
"native",
|
|
2853
|
+
"VectorMenuBar.app",
|
|
2854
|
+
"Contents",
|
|
2855
|
+
"MacOS",
|
|
2856
|
+
"VectorMenuBar"
|
|
2857
|
+
)
|
|
2858
|
+
];
|
|
2859
|
+
for (const p of candidates) {
|
|
2860
|
+
if (existsSync2(p)) {
|
|
2861
|
+
return p;
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2864
|
+
return null;
|
|
2865
|
+
}
|
|
2866
|
+
function isKnownMenuBarProcess(pid) {
|
|
2867
|
+
try {
|
|
2868
|
+
const command = execSync2(`ps -p ${pid} -o args=`, {
|
|
2869
|
+
encoding: "utf-8",
|
|
2870
|
+
timeout: 3e3
|
|
2871
|
+
});
|
|
2872
|
+
return command.includes("menubar.js") || command.includes("menubar.ts") || command.includes("VectorMenuBar");
|
|
2873
|
+
} catch {
|
|
2874
|
+
return false;
|
|
2875
|
+
}
|
|
2876
|
+
}
|
|
2877
|
+
function killExistingMenuBar() {
|
|
2878
|
+
if (existsSync2(MENUBAR_PID_FILE)) {
|
|
2879
|
+
try {
|
|
2880
|
+
const pid = Number(readFileSync2(MENUBAR_PID_FILE, "utf-8").trim());
|
|
2881
|
+
if (Number.isFinite(pid) && pid > 0 && isKnownMenuBarProcess(pid)) {
|
|
2882
|
+
process.kill(pid, "SIGTERM");
|
|
2883
|
+
}
|
|
2884
|
+
} catch {
|
|
2885
|
+
}
|
|
2886
|
+
try {
|
|
2887
|
+
unlinkSync(MENUBAR_PID_FILE);
|
|
2888
|
+
} catch {
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
}
|
|
2892
|
+
function getRunningMenuBarPid() {
|
|
2893
|
+
if (!existsSync2(MENUBAR_PID_FILE)) {
|
|
2894
|
+
return null;
|
|
215
2895
|
}
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
return value.join(", ");
|
|
2896
|
+
try {
|
|
2897
|
+
const pid = Number(readFileSync2(MENUBAR_PID_FILE, "utf-8").trim());
|
|
2898
|
+
if (Number.isFinite(pid) && pid > 0 && isKnownMenuBarProcess(pid)) {
|
|
2899
|
+
process.kill(pid, 0);
|
|
2900
|
+
return pid;
|
|
222
2901
|
}
|
|
223
|
-
|
|
2902
|
+
} catch {
|
|
224
2903
|
}
|
|
225
|
-
|
|
226
|
-
|
|
2904
|
+
try {
|
|
2905
|
+
unlinkSync(MENUBAR_PID_FILE);
|
|
2906
|
+
} catch {
|
|
227
2907
|
}
|
|
228
|
-
return
|
|
2908
|
+
return null;
|
|
229
2909
|
}
|
|
230
|
-
function
|
|
231
|
-
if (
|
|
232
|
-
|
|
2910
|
+
async function launchMenuBar() {
|
|
2911
|
+
if (platform() !== "darwin") return;
|
|
2912
|
+
removeLegacyMenuBarLaunchAgent();
|
|
2913
|
+
const executable = findMenuBarExecutable();
|
|
2914
|
+
const cliInvocation = getCurrentCliInvocation();
|
|
2915
|
+
if (!executable || !cliInvocation) return;
|
|
2916
|
+
const existingPid = getRunningMenuBarPid();
|
|
2917
|
+
if (existingPid) {
|
|
233
2918
|
return;
|
|
234
2919
|
}
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
2920
|
+
killExistingMenuBar();
|
|
2921
|
+
try {
|
|
2922
|
+
const { spawn: spawnChild } = await import("child_process");
|
|
2923
|
+
const child = spawnChild(executable, [], {
|
|
2924
|
+
detached: true,
|
|
2925
|
+
stdio: "ignore",
|
|
2926
|
+
env: {
|
|
2927
|
+
...process.env,
|
|
2928
|
+
VECTOR_CLI_COMMAND: cliInvocation[0],
|
|
2929
|
+
VECTOR_CLI_ARGS_JSON: JSON.stringify(cliInvocation.slice(1))
|
|
2930
|
+
}
|
|
2931
|
+
});
|
|
2932
|
+
child.unref();
|
|
2933
|
+
if (child.pid) {
|
|
2934
|
+
writeFileSync(MENUBAR_PID_FILE, String(child.pid));
|
|
239
2935
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
2936
|
+
} catch {
|
|
2937
|
+
}
|
|
2938
|
+
}
|
|
2939
|
+
function stopMenuBar() {
|
|
2940
|
+
killExistingMenuBar();
|
|
2941
|
+
}
|
|
2942
|
+
function getBridgeStatus() {
|
|
2943
|
+
const config = loadBridgeConfig();
|
|
2944
|
+
if (!config) return { configured: false, running: false, starting: false };
|
|
2945
|
+
let running = false;
|
|
2946
|
+
let starting = false;
|
|
2947
|
+
let pid;
|
|
2948
|
+
if (existsSync2(PID_FILE)) {
|
|
2949
|
+
const pidStr = readFileSync2(PID_FILE, "utf-8").trim();
|
|
2950
|
+
pid = Number(pidStr);
|
|
2951
|
+
try {
|
|
2952
|
+
process.kill(pid, 0);
|
|
2953
|
+
running = true;
|
|
2954
|
+
} catch {
|
|
2955
|
+
running = false;
|
|
249
2956
|
}
|
|
250
2957
|
}
|
|
251
|
-
if (
|
|
252
|
-
|
|
253
|
-
return;
|
|
2958
|
+
if (!running && platform() === "darwin") {
|
|
2959
|
+
starting = runLaunchctl(["print", `${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`]) || runLaunchctl(["list", LAUNCHAGENT_LABEL]);
|
|
254
2960
|
}
|
|
255
|
-
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// ../../src/cli/session.ts
|
|
259
|
-
import { mkdir, readFile, rm, writeFile } from "fs/promises";
|
|
260
|
-
import { homedir } from "os";
|
|
261
|
-
import path from "path";
|
|
262
|
-
var SESSION_ROOT = path.join(homedir(), ".vector");
|
|
263
|
-
function getSessionPath(profile = "default") {
|
|
264
|
-
return path.join(SESSION_ROOT, `cli-${profile}.json`);
|
|
2961
|
+
return { configured: true, running, starting, pid, config };
|
|
265
2962
|
}
|
|
266
|
-
|
|
2963
|
+
function stopBridge(options) {
|
|
2964
|
+
if (options?.includeMenuBar) {
|
|
2965
|
+
killExistingMenuBar();
|
|
2966
|
+
}
|
|
267
2967
|
try {
|
|
268
|
-
|
|
269
|
-
const parsed = JSON.parse(raw);
|
|
270
|
-
return {
|
|
271
|
-
version: 1,
|
|
272
|
-
cookies: {},
|
|
273
|
-
...parsed
|
|
274
|
-
};
|
|
2968
|
+
writeLiveActivitiesCache([]);
|
|
275
2969
|
} catch {
|
|
276
|
-
|
|
2970
|
+
}
|
|
2971
|
+
if (!existsSync2(PID_FILE)) return false;
|
|
2972
|
+
const pid = Number(readFileSync2(PID_FILE, "utf-8").trim());
|
|
2973
|
+
try {
|
|
2974
|
+
process.kill(pid, "SIGTERM");
|
|
2975
|
+
return true;
|
|
2976
|
+
} catch {
|
|
2977
|
+
return false;
|
|
277
2978
|
}
|
|
278
2979
|
}
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
await writeFile(
|
|
282
|
-
getSessionPath(profile),
|
|
283
|
-
`${JSON.stringify(session, null, 2)}
|
|
284
|
-
`,
|
|
285
|
-
"utf8"
|
|
286
|
-
);
|
|
287
|
-
}
|
|
288
|
-
async function clearSession(profile = "default") {
|
|
289
|
-
await rm(getSessionPath(profile), { force: true });
|
|
290
|
-
}
|
|
291
|
-
function createEmptySession() {
|
|
292
|
-
return {
|
|
293
|
-
version: 1,
|
|
294
|
-
cookies: {}
|
|
295
|
-
};
|
|
2980
|
+
function ts() {
|
|
2981
|
+
return (/* @__PURE__ */ new Date()).toLocaleTimeString();
|
|
296
2982
|
}
|
|
297
2983
|
|
|
298
|
-
//
|
|
2984
|
+
// src/index.ts
|
|
2985
|
+
import { platform as osPlatform } from "os";
|
|
299
2986
|
loadEnv({ path: ".env.local", override: false });
|
|
300
2987
|
loadEnv({ path: ".env", override: false });
|
|
301
2988
|
var cliApi = {
|
|
@@ -404,13 +3091,128 @@ function buildPaginationOptions(limit, cursor) {
|
|
|
404
3091
|
function normalizeMatch(value) {
|
|
405
3092
|
return value?.trim().toLowerCase();
|
|
406
3093
|
}
|
|
3094
|
+
function parseDate(value) {
|
|
3095
|
+
const ms = Date.parse(value);
|
|
3096
|
+
if (!Number.isFinite(ms)) {
|
|
3097
|
+
throw new Error(`Invalid date: ${value}`);
|
|
3098
|
+
}
|
|
3099
|
+
return ms;
|
|
3100
|
+
}
|
|
3101
|
+
function applyListFilters(items, options) {
|
|
3102
|
+
let result = [...items];
|
|
3103
|
+
if (options.createdAfter) {
|
|
3104
|
+
const threshold = parseDate(options.createdAfter);
|
|
3105
|
+
result = result.filter(
|
|
3106
|
+
(item) => typeof item.createdAt === "number" && item.createdAt >= threshold
|
|
3107
|
+
);
|
|
3108
|
+
}
|
|
3109
|
+
if (options.createdBefore) {
|
|
3110
|
+
const threshold = parseDate(options.createdBefore);
|
|
3111
|
+
result = result.filter(
|
|
3112
|
+
(item) => typeof item.createdAt === "number" && item.createdAt <= threshold
|
|
3113
|
+
);
|
|
3114
|
+
}
|
|
3115
|
+
if (options.updatedAfter) {
|
|
3116
|
+
const threshold = parseDate(options.updatedAfter);
|
|
3117
|
+
result = result.filter(
|
|
3118
|
+
(item) => typeof item.lastEditedAt === "number" && item.lastEditedAt >= threshold
|
|
3119
|
+
);
|
|
3120
|
+
}
|
|
3121
|
+
if (options.updatedBefore) {
|
|
3122
|
+
const threshold = parseDate(options.updatedBefore);
|
|
3123
|
+
result = result.filter(
|
|
3124
|
+
(item) => typeof item.lastEditedAt === "number" && item.lastEditedAt <= threshold
|
|
3125
|
+
);
|
|
3126
|
+
}
|
|
3127
|
+
if (options.sort) {
|
|
3128
|
+
const field = options.sort;
|
|
3129
|
+
const desc = options.order?.toLowerCase() === "desc";
|
|
3130
|
+
result.sort((a, b) => {
|
|
3131
|
+
const aVal = a[field];
|
|
3132
|
+
const bVal = b[field];
|
|
3133
|
+
if (aVal == null && bVal == null) return 0;
|
|
3134
|
+
if (aVal == null) return 1;
|
|
3135
|
+
if (bVal == null) return -1;
|
|
3136
|
+
if (typeof aVal === "number" && typeof bVal === "number")
|
|
3137
|
+
return desc ? bVal - aVal : aVal - bVal;
|
|
3138
|
+
return desc ? String(bVal).localeCompare(String(aVal)) : String(aVal).localeCompare(String(bVal));
|
|
3139
|
+
});
|
|
3140
|
+
}
|
|
3141
|
+
if (options.limit) {
|
|
3142
|
+
const limit = Number(options.limit);
|
|
3143
|
+
if (Number.isFinite(limit) && limit > 0) {
|
|
3144
|
+
result = result.slice(0, limit);
|
|
3145
|
+
}
|
|
3146
|
+
}
|
|
3147
|
+
return result;
|
|
3148
|
+
}
|
|
3149
|
+
function addEntityUrls(items, appUrl, orgSlug, entityType) {
|
|
3150
|
+
return items.map((item) => {
|
|
3151
|
+
let path3;
|
|
3152
|
+
switch (entityType) {
|
|
3153
|
+
case "issues":
|
|
3154
|
+
path3 = `/${orgSlug}/issues/${item.key}`;
|
|
3155
|
+
break;
|
|
3156
|
+
case "projects":
|
|
3157
|
+
path3 = `/${orgSlug}/projects/${item.key}`;
|
|
3158
|
+
break;
|
|
3159
|
+
case "teams":
|
|
3160
|
+
path3 = `/${orgSlug}/teams/${item.key}`;
|
|
3161
|
+
break;
|
|
3162
|
+
case "documents":
|
|
3163
|
+
path3 = `/${orgSlug}/documents/${item.id}`;
|
|
3164
|
+
break;
|
|
3165
|
+
case "folders":
|
|
3166
|
+
path3 = `/${orgSlug}/documents/folders/${item.id}`;
|
|
3167
|
+
break;
|
|
3168
|
+
}
|
|
3169
|
+
return { ...item, url: `${appUrl}${path3}` };
|
|
3170
|
+
});
|
|
3171
|
+
}
|
|
3172
|
+
function normalizeAppUrl(raw) {
|
|
3173
|
+
let url = raw.trim();
|
|
3174
|
+
if (!/^https?:\/\//i.test(url)) {
|
|
3175
|
+
const isLocal = /^localhost(:\d+)?/i.test(url) || /^127\.0\.0\.1(:\d+)?/.test(url);
|
|
3176
|
+
url = isLocal ? `http://${url}` : `https://${url}`;
|
|
3177
|
+
}
|
|
3178
|
+
return url.replace(/\/+$/, "");
|
|
3179
|
+
}
|
|
3180
|
+
async function resolveAppUrl(raw) {
|
|
3181
|
+
const url = normalizeAppUrl(raw);
|
|
3182
|
+
try {
|
|
3183
|
+
const response = await fetch(url, { method: "HEAD", redirect: "follow" });
|
|
3184
|
+
const resolved = new URL(response.url).origin;
|
|
3185
|
+
return resolved;
|
|
3186
|
+
} catch {
|
|
3187
|
+
return url;
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
async function fetchConvexUrl(appUrl) {
|
|
3191
|
+
try {
|
|
3192
|
+
const url = new URL("/api/config", appUrl).toString();
|
|
3193
|
+
const response = await fetch(url);
|
|
3194
|
+
if (!response.ok) {
|
|
3195
|
+
throw new Error(`HTTP ${response.status}`);
|
|
3196
|
+
}
|
|
3197
|
+
const data = await response.json();
|
|
3198
|
+
if (data.convexUrl) {
|
|
3199
|
+
return data.convexUrl;
|
|
3200
|
+
}
|
|
3201
|
+
} catch {
|
|
3202
|
+
}
|
|
3203
|
+
return "http://127.0.0.1:3210";
|
|
3204
|
+
}
|
|
407
3205
|
async function getRuntime(command) {
|
|
408
3206
|
const options = command.optsWithGlobals();
|
|
409
3207
|
const profile = options.profile ?? "default";
|
|
410
3208
|
const session = await readSession(profile);
|
|
411
3209
|
const appUrlSource = options.appUrl ?? session?.appUrl ?? process.env.NEXT_PUBLIC_APP_URL;
|
|
412
|
-
const appUrl = requiredString(appUrlSource, "app URL");
|
|
413
|
-
|
|
3210
|
+
const appUrl = await resolveAppUrl(requiredString(appUrlSource, "app URL"));
|
|
3211
|
+
let convexUrl = options.convexUrl ?? session?.convexUrl;
|
|
3212
|
+
if (!convexUrl) {
|
|
3213
|
+
const fetchedUrl = await fetchConvexUrl(appUrl);
|
|
3214
|
+
convexUrl = fetchedUrl !== "http://127.0.0.1:3210" ? fetchedUrl : process.env.NEXT_PUBLIC_CONVEX_URL ?? process.env.CONVEX_URL ?? fetchedUrl;
|
|
3215
|
+
}
|
|
414
3216
|
return {
|
|
415
3217
|
appUrl,
|
|
416
3218
|
convexUrl,
|
|
@@ -421,7 +3223,7 @@ async function getRuntime(command) {
|
|
|
421
3223
|
};
|
|
422
3224
|
}
|
|
423
3225
|
function requireSession(runtime) {
|
|
424
|
-
if (!runtime.session || Object.keys(runtime.session.cookies).length === 0) {
|
|
3226
|
+
if (!runtime.session || Object.keys(runtime.session.cookies).length === 0 && !runtime.session.bearerToken) {
|
|
425
3227
|
throw new Error("Not logged in. Run `vcli auth login` first.");
|
|
426
3228
|
}
|
|
427
3229
|
return runtime.session;
|
|
@@ -435,6 +3237,80 @@ function requireOrg(runtime, explicit) {
|
|
|
435
3237
|
}
|
|
436
3238
|
return orgSlug;
|
|
437
3239
|
}
|
|
3240
|
+
function hostForAppUrl(appUrl) {
|
|
3241
|
+
if (!appUrl) {
|
|
3242
|
+
return void 0;
|
|
3243
|
+
}
|
|
3244
|
+
try {
|
|
3245
|
+
const url = new URL(appUrl);
|
|
3246
|
+
return url.port ? `${url.hostname}:${url.port}` : url.hostname;
|
|
3247
|
+
} catch {
|
|
3248
|
+
return void 0;
|
|
3249
|
+
}
|
|
3250
|
+
}
|
|
3251
|
+
function decodeSessionClaims(session) {
|
|
3252
|
+
const jwt = session?.cookies?.["__Secure-better-auth.convex_jwt"];
|
|
3253
|
+
if (!jwt) {
|
|
3254
|
+
return {};
|
|
3255
|
+
}
|
|
3256
|
+
const parts = jwt.split(".");
|
|
3257
|
+
if (parts.length < 2) {
|
|
3258
|
+
return {};
|
|
3259
|
+
}
|
|
3260
|
+
let payload = parts[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
3261
|
+
while (payload.length % 4 !== 0) {
|
|
3262
|
+
payload += "=";
|
|
3263
|
+
}
|
|
3264
|
+
try {
|
|
3265
|
+
const decoded = JSON.parse(
|
|
3266
|
+
Buffer.from(payload, "base64").toString("utf8")
|
|
3267
|
+
);
|
|
3268
|
+
return {
|
|
3269
|
+
email: decoded.email,
|
|
3270
|
+
userId: decoded.sub ?? decoded.userId
|
|
3271
|
+
};
|
|
3272
|
+
} catch {
|
|
3273
|
+
return {};
|
|
3274
|
+
}
|
|
3275
|
+
}
|
|
3276
|
+
function buildMenuSessionInfo(session) {
|
|
3277
|
+
const claims = decodeSessionClaims(session);
|
|
3278
|
+
return {
|
|
3279
|
+
orgSlug: session?.activeOrgSlug ?? "oss-lab",
|
|
3280
|
+
appUrl: session?.appUrl,
|
|
3281
|
+
appDomain: hostForAppUrl(session?.appUrl),
|
|
3282
|
+
email: claims.email,
|
|
3283
|
+
userId: claims.userId
|
|
3284
|
+
};
|
|
3285
|
+
}
|
|
3286
|
+
function parseAgentProvider(value) {
|
|
3287
|
+
if (value === "codex" || value === "claude_code" || value === "vector_cli") {
|
|
3288
|
+
return value;
|
|
3289
|
+
}
|
|
3290
|
+
throw new Error("provider must be one of: codex, claude_code, vector_cli");
|
|
3291
|
+
}
|
|
3292
|
+
function isBridgeDeviceAuthError(error) {
|
|
3293
|
+
if (!error || typeof error !== "object") {
|
|
3294
|
+
return false;
|
|
3295
|
+
}
|
|
3296
|
+
const maybeData = error.data;
|
|
3297
|
+
return maybeData === "INVALID_DEVICE_SECRET" || maybeData === "DEVICE_NOT_FOUND";
|
|
3298
|
+
}
|
|
3299
|
+
async function validateStoredBridgeConfig(config) {
|
|
3300
|
+
const client = new ConvexHttpClient3(config.convexUrl);
|
|
3301
|
+
try {
|
|
3302
|
+
await client.mutation(api.agentBridge.bridgePublic.heartbeat, {
|
|
3303
|
+
deviceId: config.deviceId,
|
|
3304
|
+
deviceSecret: config.deviceSecret
|
|
3305
|
+
});
|
|
3306
|
+
return true;
|
|
3307
|
+
} catch (error) {
|
|
3308
|
+
if (isBridgeDeviceAuthError(error)) {
|
|
3309
|
+
return false;
|
|
3310
|
+
}
|
|
3311
|
+
throw error;
|
|
3312
|
+
}
|
|
3313
|
+
}
|
|
438
3314
|
async function getClient(command) {
|
|
439
3315
|
const runtime = await getRuntime(command);
|
|
440
3316
|
const session = requireSession(runtime);
|
|
@@ -445,6 +3321,39 @@ async function getClient(command) {
|
|
|
445
3321
|
);
|
|
446
3322
|
return { client, runtime, session };
|
|
447
3323
|
}
|
|
3324
|
+
async function ensureBridgeConfig(command) {
|
|
3325
|
+
let config = loadBridgeConfig();
|
|
3326
|
+
try {
|
|
3327
|
+
const runtime = await getRuntime(command);
|
|
3328
|
+
const session = requireSession(runtime);
|
|
3329
|
+
const client = await createConvexClient(
|
|
3330
|
+
session,
|
|
3331
|
+
runtime.appUrl,
|
|
3332
|
+
runtime.convexUrl
|
|
3333
|
+
);
|
|
3334
|
+
const user = await runQuery(client, api.users.currentUser);
|
|
3335
|
+
if (!user) {
|
|
3336
|
+
throw new Error("Not logged in. Run `vcli auth login` first.");
|
|
3337
|
+
}
|
|
3338
|
+
const backendDevice = config ? await runQuery(client, api.agentBridge.queries.getDevice, {
|
|
3339
|
+
deviceId: config.deviceId
|
|
3340
|
+
}) : null;
|
|
3341
|
+
const needsRegistration = !config || config.userId !== user._id || config.convexUrl !== runtime.convexUrl || !backendDevice || !await validateStoredBridgeConfig(config);
|
|
3342
|
+
if (needsRegistration) {
|
|
3343
|
+
config = await setupBridgeDevice(client, runtime.convexUrl);
|
|
3344
|
+
}
|
|
3345
|
+
if (!config) {
|
|
3346
|
+
throw new Error("Bridge device is not configured.");
|
|
3347
|
+
}
|
|
3348
|
+
saveBridgeConfig(config);
|
|
3349
|
+
return config;
|
|
3350
|
+
} catch (error) {
|
|
3351
|
+
if (config) {
|
|
3352
|
+
return config;
|
|
3353
|
+
}
|
|
3354
|
+
throw error;
|
|
3355
|
+
}
|
|
3356
|
+
}
|
|
448
3357
|
async function resolveMemberId(client, orgSlug, ref) {
|
|
449
3358
|
const members = await runQuery(
|
|
450
3359
|
client,
|
|
@@ -620,7 +3529,16 @@ async function parseEstimatedTimes(client, orgSlug, value) {
|
|
|
620
3529
|
return estimatedTimes;
|
|
621
3530
|
}
|
|
622
3531
|
var program = new Command();
|
|
623
|
-
|
|
3532
|
+
function readPackageVersionSync() {
|
|
3533
|
+
try {
|
|
3534
|
+
const dir = import.meta.dirname ?? dirname(fileURLToPath2(import.meta.url));
|
|
3535
|
+
const raw = readFileSync3(join3(dir, "..", "package.json"), "utf8");
|
|
3536
|
+
return JSON.parse(raw).version ?? "unknown";
|
|
3537
|
+
} catch {
|
|
3538
|
+
return "unknown";
|
|
3539
|
+
}
|
|
3540
|
+
}
|
|
3541
|
+
program.name("vcli").description("Vector CLI").version(readPackageVersionSync(), "-v, --version").showHelpAfterError().option(
|
|
624
3542
|
"--app-url <url>",
|
|
625
3543
|
"Vector app URL. Required unless saved in the profile or NEXT_PUBLIC_APP_URL is set."
|
|
626
3544
|
).option("--convex-url <url>", "Convex deployment URL").option("--org <slug>", "Organization slug override").option("--profile <name>", "CLI profile name", "default").option("--json", "Output JSON");
|
|
@@ -664,19 +3582,48 @@ authCommand.command("signup").option("--email <email>", "Email address").option(
|
|
|
664
3582
|
runtime.json
|
|
665
3583
|
);
|
|
666
3584
|
});
|
|
667
|
-
authCommand.command("login [identifier]").option("--password <password>", "Password").action(async (identifier, options, command) => {
|
|
3585
|
+
authCommand.command("login [identifier]").option("--password <password>", "Password (uses device flow if omitted)").action(async (identifier, options, command) => {
|
|
668
3586
|
const runtime = await getRuntime(command);
|
|
669
|
-
const loginId = identifier?.trim() || await prompt("Email or username: ");
|
|
670
|
-
const password = options.password?.trim() || await promptSecret("Password: ");
|
|
671
3587
|
let session = createEmptySession();
|
|
672
3588
|
session.appUrl = runtime.appUrl;
|
|
673
3589
|
session.convexUrl = runtime.convexUrl;
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
3590
|
+
const usePassword = Boolean(identifier || options.password);
|
|
3591
|
+
if (usePassword) {
|
|
3592
|
+
const loginId = identifier?.trim() || await prompt("Email or username: ");
|
|
3593
|
+
const password = options.password?.trim() || await promptSecret("Password: ");
|
|
3594
|
+
session = await loginWithPassword(
|
|
3595
|
+
session,
|
|
3596
|
+
runtime.appUrl,
|
|
3597
|
+
loginId,
|
|
3598
|
+
password
|
|
3599
|
+
);
|
|
3600
|
+
} else {
|
|
3601
|
+
const deviceResp = await requestDeviceCode(runtime.appUrl, "vcli");
|
|
3602
|
+
const verifyUrl = `${runtime.appUrl}/device?user_code=${deviceResp.user_code}`;
|
|
3603
|
+
console.log();
|
|
3604
|
+
console.log(` Open this URL in your browser to log in:`);
|
|
3605
|
+
console.log();
|
|
3606
|
+
console.log(` ${verifyUrl}`);
|
|
3607
|
+
console.log();
|
|
3608
|
+
console.log(` Or go to ${runtime.appUrl}/device and enter code:`);
|
|
3609
|
+
console.log();
|
|
3610
|
+
console.log(` ${deviceResp.user_code}`);
|
|
3611
|
+
console.log();
|
|
3612
|
+
const open2 = await Promise.resolve().then(() => (init_open(), open_exports)).then((m) => m.default).catch(() => null);
|
|
3613
|
+
if (open2) {
|
|
3614
|
+
await open2(verifyUrl).catch(() => {
|
|
3615
|
+
});
|
|
3616
|
+
}
|
|
3617
|
+
console.log(" Waiting for authorization...");
|
|
3618
|
+
session = await pollDeviceToken(
|
|
3619
|
+
session,
|
|
3620
|
+
runtime.appUrl,
|
|
3621
|
+
deviceResp.device_code,
|
|
3622
|
+
"vcli",
|
|
3623
|
+
deviceResp.interval,
|
|
3624
|
+
deviceResp.expires_in
|
|
3625
|
+
);
|
|
3626
|
+
}
|
|
680
3627
|
const authState = await fetchAuthSession(session, runtime.appUrl);
|
|
681
3628
|
session = authState.session;
|
|
682
3629
|
const client = await createConvexClient(
|
|
@@ -1047,6 +3994,75 @@ permissionCommand.command("check-many <permissions>").option("--team <teamKey>")
|
|
|
1047
3994
|
printOutput(result, runtime.json);
|
|
1048
3995
|
});
|
|
1049
3996
|
var activityCommand = program.command("activity").description("Activity feed");
|
|
3997
|
+
activityCommand.command("list").description(
|
|
3998
|
+
"List org-wide activity with optional filters by entity type, event type, and time range"
|
|
3999
|
+
).option(
|
|
4000
|
+
"--entity-type <type>",
|
|
4001
|
+
"Filter by entity type: issue, project, team, document"
|
|
4002
|
+
).option(
|
|
4003
|
+
"--event-type <type>",
|
|
4004
|
+
"Filter by event type (e.g. issue_created, issue_priority_changed)"
|
|
4005
|
+
).option(
|
|
4006
|
+
"--since <datetime>",
|
|
4007
|
+
"Start of time range (ISO date or shorthand: today, yesterday, 7d, 30d)"
|
|
4008
|
+
).option(
|
|
4009
|
+
"--until <datetime>",
|
|
4010
|
+
"End of time range (ISO date or shorthand: today, now)"
|
|
4011
|
+
).option("--limit <n>").option("--cursor <cursor>").action(async (options, command) => {
|
|
4012
|
+
const { client, runtime } = await getClient(command);
|
|
4013
|
+
const orgSlug = requireOrg(runtime);
|
|
4014
|
+
function parseTimeArg(value, bound) {
|
|
4015
|
+
if (!value) return void 0;
|
|
4016
|
+
const now = /* @__PURE__ */ new Date();
|
|
4017
|
+
const startOfToday = new Date(
|
|
4018
|
+
now.getFullYear(),
|
|
4019
|
+
now.getMonth(),
|
|
4020
|
+
now.getDate()
|
|
4021
|
+
);
|
|
4022
|
+
const endOfToday = new Date(
|
|
4023
|
+
now.getFullYear(),
|
|
4024
|
+
now.getMonth(),
|
|
4025
|
+
now.getDate(),
|
|
4026
|
+
23,
|
|
4027
|
+
59,
|
|
4028
|
+
59,
|
|
4029
|
+
999
|
|
4030
|
+
);
|
|
4031
|
+
switch (value) {
|
|
4032
|
+
case "now":
|
|
4033
|
+
return now.getTime();
|
|
4034
|
+
case "today":
|
|
4035
|
+
return bound === "start" ? startOfToday.getTime() : endOfToday.getTime();
|
|
4036
|
+
case "yesterday":
|
|
4037
|
+
return bound === "start" ? startOfToday.getTime() - 864e5 : startOfToday.getTime() - 1;
|
|
4038
|
+
default: {
|
|
4039
|
+
const daysMatch = value.match(/^(\d+)d$/);
|
|
4040
|
+
if (daysMatch) {
|
|
4041
|
+
return now.getTime() - Number(daysMatch[1]) * 864e5;
|
|
4042
|
+
}
|
|
4043
|
+
const parsed = new Date(value).getTime();
|
|
4044
|
+
if (Number.isNaN(parsed)) {
|
|
4045
|
+
throw new Error(`Invalid time value: ${value}`);
|
|
4046
|
+
}
|
|
4047
|
+
return parsed;
|
|
4048
|
+
}
|
|
4049
|
+
}
|
|
4050
|
+
}
|
|
4051
|
+
const result = await runQuery(
|
|
4052
|
+
client,
|
|
4053
|
+
api.activities.queries.listOrgActivity,
|
|
4054
|
+
{
|
|
4055
|
+
orgSlug,
|
|
4056
|
+
entityType: options.entityType ?? void 0,
|
|
4057
|
+
eventType: options.eventType ?? void 0,
|
|
4058
|
+
since: parseTimeArg(options.since, "start"),
|
|
4059
|
+
until: parseTimeArg(options.until, "end"),
|
|
4060
|
+
limit: optionalNumber(options.limit, "limit") ?? void 0,
|
|
4061
|
+
cursor: options.cursor ?? void 0
|
|
4062
|
+
}
|
|
4063
|
+
);
|
|
4064
|
+
printOutput(result, runtime.json);
|
|
4065
|
+
});
|
|
1050
4066
|
activityCommand.command("project <projectKey>").option("--limit <n>").option("--cursor <cursor>").action(async (projectKey, options, command) => {
|
|
1051
4067
|
const { client, runtime } = await getClient(command);
|
|
1052
4068
|
const orgSlug = requireOrg(runtime);
|
|
@@ -1503,13 +4519,14 @@ adminCommand.command("sync-disposable-domains").action(async (_options, command)
|
|
|
1503
4519
|
printOutput(result, runtime.json);
|
|
1504
4520
|
});
|
|
1505
4521
|
var teamCommand = program.command("team").description("Teams");
|
|
1506
|
-
teamCommand.command("list [slug]").option("--limit <n>").action(async (slug, options, command) => {
|
|
4522
|
+
teamCommand.command("list [slug]").option("--limit <n>").option("--created-after <date>", "Filter: created on or after date (ISO)").option("--created-before <date>", "Filter: created on or before date (ISO)").option("--sort <field>", "Sort by field (e.g. createdAt, name, key)").option("--order <direction>", "Sort order: asc or desc (default: asc)").action(async (slug, options, command) => {
|
|
1507
4523
|
const { client, runtime } = await getClient(command);
|
|
1508
4524
|
const orgSlug = requireOrg(runtime, slug);
|
|
1509
|
-
const
|
|
1510
|
-
orgSlug
|
|
1511
|
-
limit: options.limit ? Number(options.limit) : void 0
|
|
4525
|
+
const raw = await runAction(client, cliApi.listTeams, {
|
|
4526
|
+
orgSlug
|
|
1512
4527
|
});
|
|
4528
|
+
const filtered = applyListFilters(raw, options);
|
|
4529
|
+
const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "teams");
|
|
1513
4530
|
printOutput(result, runtime.json);
|
|
1514
4531
|
});
|
|
1515
4532
|
teamCommand.command("get <teamKey>").action(async (teamKey, _options, command) => {
|
|
@@ -1603,14 +4620,15 @@ teamCommand.command("set-lead <teamKey> <member>").action(async (teamKey, member
|
|
|
1603
4620
|
printOutput(result, runtime.json);
|
|
1604
4621
|
});
|
|
1605
4622
|
var projectCommand = program.command("project").description("Projects");
|
|
1606
|
-
projectCommand.command("list [slug]").option("--team <teamKey>").option("--limit <n>").action(async (slug, options, command) => {
|
|
4623
|
+
projectCommand.command("list [slug]").option("--team <teamKey>").option("--limit <n>").option("--created-after <date>", "Filter: created on or after date (ISO)").option("--created-before <date>", "Filter: created on or before date (ISO)").option("--sort <field>", "Sort by field (e.g. createdAt, name, key)").option("--order <direction>", "Sort order: asc or desc (default: asc)").action(async (slug, options, command) => {
|
|
1607
4624
|
const { client, runtime } = await getClient(command);
|
|
1608
4625
|
const orgSlug = requireOrg(runtime, slug);
|
|
1609
|
-
const
|
|
4626
|
+
const raw = await runAction(client, cliApi.listProjects, {
|
|
1610
4627
|
orgSlug,
|
|
1611
|
-
teamKey: options.team
|
|
1612
|
-
limit: options.limit ? Number(options.limit) : void 0
|
|
4628
|
+
teamKey: options.team
|
|
1613
4629
|
});
|
|
4630
|
+
const filtered = applyListFilters(raw, options);
|
|
4631
|
+
const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "projects");
|
|
1614
4632
|
printOutput(result, runtime.json);
|
|
1615
4633
|
});
|
|
1616
4634
|
projectCommand.command("get <projectKey>").action(async (projectKey, _options, command) => {
|
|
@@ -1710,15 +4728,17 @@ projectCommand.command("set-lead <projectKey> <member>").action(async (projectKe
|
|
|
1710
4728
|
printOutput(result, runtime.json);
|
|
1711
4729
|
});
|
|
1712
4730
|
var issueCommand = program.command("issue").description("Issues");
|
|
1713
|
-
issueCommand.command("list [slug]").option("--project <projectKey>").option("--team <teamKey>").option("--limit <n>").action(async (slug, options, command) => {
|
|
4731
|
+
issueCommand.command("list [slug]").option("--project <projectKey>").option("--team <teamKey>").option("--assignee <name>", "Filter by assignee name or email").option("--limit <n>").option("--created-after <date>", "Filter: created on or after date (ISO)").option("--created-before <date>", "Filter: created on or before date (ISO)").option("--sort <field>", "Sort by field (e.g. createdAt, title, key)").option("--order <direction>", "Sort order: asc or desc (default: asc)").action(async (slug, options, command) => {
|
|
1714
4732
|
const { client, runtime } = await getClient(command);
|
|
1715
4733
|
const orgSlug = requireOrg(runtime, slug);
|
|
1716
|
-
const
|
|
4734
|
+
const raw = await runAction(client, cliApi.listIssues, {
|
|
1717
4735
|
orgSlug,
|
|
1718
4736
|
projectKey: options.project,
|
|
1719
4737
|
teamKey: options.team,
|
|
1720
|
-
|
|
4738
|
+
assigneeName: options.assignee
|
|
1721
4739
|
});
|
|
4740
|
+
const filtered = applyListFilters(raw, options);
|
|
4741
|
+
const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "issues");
|
|
1722
4742
|
printOutput(result, runtime.json);
|
|
1723
4743
|
});
|
|
1724
4744
|
issueCommand.command("get <issueKey>").action(async (issueKey, _options, command) => {
|
|
@@ -1915,15 +4935,40 @@ issueCommand.command("comment <issueKey>").requiredOption("--body <body>").actio
|
|
|
1915
4935
|
});
|
|
1916
4936
|
printOutput(result, runtime.json);
|
|
1917
4937
|
});
|
|
4938
|
+
issueCommand.command("link-github <issueKey> <url>").description("Link a GitHub pull request, issue, or commit URL to an issue").action(async (issueKey, url, _options, command) => {
|
|
4939
|
+
const { client, runtime } = await getClient(command);
|
|
4940
|
+
const orgSlug = requireOrg(runtime);
|
|
4941
|
+
await runAction(client, api.github.actions.linkArtifactByUrl, {
|
|
4942
|
+
orgSlug,
|
|
4943
|
+
issueKey,
|
|
4944
|
+
url
|
|
4945
|
+
});
|
|
4946
|
+
printOutput({ success: true, issueKey, url }, runtime.json);
|
|
4947
|
+
});
|
|
1918
4948
|
var documentCommand = program.command("document").description("Documents");
|
|
1919
|
-
documentCommand.command("list [slug]").option("--folder-id <id>").option("--limit <n>").
|
|
4949
|
+
documentCommand.command("list [slug]").option("--folder-id <id>").option("--limit <n>").option("--created-after <date>", "Filter: created on or after date (ISO)").option("--created-before <date>", "Filter: created on or before date (ISO)").option(
|
|
4950
|
+
"--updated-after <date>",
|
|
4951
|
+
"Filter: last edited on or after date (ISO)"
|
|
4952
|
+
).option(
|
|
4953
|
+
"--updated-before <date>",
|
|
4954
|
+
"Filter: last edited on or before date (ISO)"
|
|
4955
|
+
).option(
|
|
4956
|
+
"--sort <field>",
|
|
4957
|
+
"Sort by field (e.g. createdAt, title, lastEditedAt)"
|
|
4958
|
+
).option("--order <direction>", "Sort order: asc or desc (default: asc)").action(async (slug, options, command) => {
|
|
1920
4959
|
const { client, runtime } = await getClient(command);
|
|
1921
4960
|
const orgSlug = requireOrg(runtime, slug);
|
|
1922
|
-
const
|
|
4961
|
+
const raw = await runAction(client, cliApi.listDocuments, {
|
|
1923
4962
|
orgSlug,
|
|
1924
|
-
folderId: options.folderId
|
|
1925
|
-
limit: options.limit ? Number(options.limit) : void 0
|
|
4963
|
+
folderId: options.folderId
|
|
1926
4964
|
});
|
|
4965
|
+
const filtered = applyListFilters(raw, options);
|
|
4966
|
+
const result = addEntityUrls(
|
|
4967
|
+
filtered,
|
|
4968
|
+
runtime.appUrl,
|
|
4969
|
+
orgSlug,
|
|
4970
|
+
"documents"
|
|
4971
|
+
);
|
|
1927
4972
|
printOutput(result, runtime.json);
|
|
1928
4973
|
});
|
|
1929
4974
|
documentCommand.command("get <documentId>").action(async (documentId, _options, command) => {
|
|
@@ -1989,10 +5034,12 @@ documentCommand.command("delete <documentId>").action(async (documentId, _option
|
|
|
1989
5034
|
printOutput(result, runtime.json);
|
|
1990
5035
|
});
|
|
1991
5036
|
var folderCommand = program.command("folder").description("Document folders");
|
|
1992
|
-
folderCommand.command("list [slug]").action(async (slug,
|
|
5037
|
+
folderCommand.command("list [slug]").option("--limit <n>").option("--created-after <date>", "Filter: created on or after date (ISO)").option("--created-before <date>", "Filter: created on or before date (ISO)").option("--sort <field>", "Sort by field (e.g. createdAt, name)").option("--order <direction>", "Sort order: asc or desc (default: asc)").action(async (slug, options, command) => {
|
|
1993
5038
|
const { client, runtime } = await getClient(command);
|
|
1994
5039
|
const orgSlug = requireOrg(runtime, slug);
|
|
1995
|
-
const
|
|
5040
|
+
const raw = await runAction(client, cliApi.listFolders, { orgSlug });
|
|
5041
|
+
const filtered = applyListFilters(raw, options);
|
|
5042
|
+
const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "folders");
|
|
1996
5043
|
printOutput(result, runtime.json);
|
|
1997
5044
|
});
|
|
1998
5045
|
folderCommand.command("create").requiredOption("--name <name>").option("--description <description>").option("--icon <icon>").option("--color <color>").action(async (options, command) => {
|
|
@@ -2032,6 +5079,246 @@ folderCommand.command("delete <folderId>").action(async (folderId, _options, com
|
|
|
2032
5079
|
});
|
|
2033
5080
|
printOutput(result, runtime.json);
|
|
2034
5081
|
});
|
|
5082
|
+
var VECTOR_HOME = process.env.VECTOR_HOME?.trim() || `${process.env.HOME ?? "~"}/.vector`;
|
|
5083
|
+
var serviceCommand = program.command("service").description("Manage the local bridge service");
|
|
5084
|
+
serviceCommand.command("start").description("Start the bridge service via LaunchAgent (macOS) or foreground").action(async (_options, command) => {
|
|
5085
|
+
const existing = getBridgeStatus();
|
|
5086
|
+
if (existing.running) {
|
|
5087
|
+
console.log(`Bridge is already running (PID ${existing.pid}).`);
|
|
5088
|
+
return;
|
|
5089
|
+
}
|
|
5090
|
+
const { spinner } = await import("@clack/prompts");
|
|
5091
|
+
const s = spinner();
|
|
5092
|
+
s.start("Ensuring device registration...");
|
|
5093
|
+
const config = await ensureBridgeConfig(command);
|
|
5094
|
+
s.stop(`Device ready: ${config.displayName}`);
|
|
5095
|
+
if (osPlatform() === "darwin") {
|
|
5096
|
+
s.start("Starting bridge service...");
|
|
5097
|
+
const vcliPath = process.argv[1] ?? "vcli";
|
|
5098
|
+
installLaunchAgent(vcliPath);
|
|
5099
|
+
loadLaunchAgent();
|
|
5100
|
+
s.stop("Bridge service started.");
|
|
5101
|
+
} else {
|
|
5102
|
+
console.log(
|
|
5103
|
+
"Starting bridge in foreground (use systemd for background)..."
|
|
5104
|
+
);
|
|
5105
|
+
const bridge = new BridgeService(config);
|
|
5106
|
+
await bridge.run();
|
|
5107
|
+
}
|
|
5108
|
+
});
|
|
5109
|
+
serviceCommand.command("run").description("Run the bridge service in the foreground (used by LaunchAgent)").action(async (_options, command) => {
|
|
5110
|
+
const config = await ensureBridgeConfig(command);
|
|
5111
|
+
if (osPlatform() === "darwin") {
|
|
5112
|
+
await launchMenuBar();
|
|
5113
|
+
}
|
|
5114
|
+
const bridge = new BridgeService(config);
|
|
5115
|
+
await bridge.run();
|
|
5116
|
+
});
|
|
5117
|
+
serviceCommand.command("stop").description("Stop the bridge service").action(() => {
|
|
5118
|
+
let unloaded = false;
|
|
5119
|
+
if (osPlatform() === "darwin") {
|
|
5120
|
+
unloaded = unloadLaunchAgent();
|
|
5121
|
+
}
|
|
5122
|
+
if (stopBridge() || unloaded) {
|
|
5123
|
+
console.log("Bridge stopped.");
|
|
5124
|
+
} else if (osPlatform() !== "darwin") {
|
|
5125
|
+
console.log("Bridge is not running.");
|
|
5126
|
+
} else {
|
|
5127
|
+
console.log("Bridge is not running.");
|
|
5128
|
+
}
|
|
5129
|
+
});
|
|
5130
|
+
serviceCommand.command("status").description("Show bridge service status").action((_options, command) => {
|
|
5131
|
+
const status = getBridgeStatus();
|
|
5132
|
+
if (!status.configured) {
|
|
5133
|
+
console.log("Bridge not configured. Run: vcli service start");
|
|
5134
|
+
return;
|
|
5135
|
+
}
|
|
5136
|
+
console.log("Vector Bridge");
|
|
5137
|
+
console.log(
|
|
5138
|
+
` Device: ${status.config.displayName} (${status.config.deviceId})`
|
|
5139
|
+
);
|
|
5140
|
+
console.log(` User: ${status.config.userId}`);
|
|
5141
|
+
const statusLabel = status.running ? `Running (PID ${status.pid})` : status.starting ? "Starting..." : "Not running";
|
|
5142
|
+
console.log(` Status: ${statusLabel}`);
|
|
5143
|
+
console.log(` Config: ${VECTOR_HOME}/bridge.json`);
|
|
5144
|
+
});
|
|
5145
|
+
serviceCommand.command("menu-state").description("Return JSON state for the macOS tray").action(async (_options, command) => {
|
|
5146
|
+
const status = getBridgeStatus();
|
|
5147
|
+
const globalOptions = command.optsWithGlobals();
|
|
5148
|
+
const profile = globalOptions.profile ?? "default";
|
|
5149
|
+
const session = await readSession(profile);
|
|
5150
|
+
let workSessions = [];
|
|
5151
|
+
let detectedSessions = [];
|
|
5152
|
+
try {
|
|
5153
|
+
const runtime = await getRuntime(command);
|
|
5154
|
+
if (runtime.session && status.config?.deviceId) {
|
|
5155
|
+
const client = await createConvexClient(
|
|
5156
|
+
runtime.session,
|
|
5157
|
+
runtime.appUrl,
|
|
5158
|
+
runtime.convexUrl
|
|
5159
|
+
);
|
|
5160
|
+
workSessions = await runQuery(
|
|
5161
|
+
client,
|
|
5162
|
+
api.agentBridge.queries.listDeviceWorkSessions,
|
|
5163
|
+
{
|
|
5164
|
+
deviceId: status.config.deviceId
|
|
5165
|
+
}
|
|
5166
|
+
);
|
|
5167
|
+
const devices = await runQuery(
|
|
5168
|
+
client,
|
|
5169
|
+
api.agentBridge.queries.listProcessesForAttach,
|
|
5170
|
+
{}
|
|
5171
|
+
);
|
|
5172
|
+
const currentDevice = devices.find(
|
|
5173
|
+
(entry) => entry.device._id === status.config?.deviceId
|
|
5174
|
+
);
|
|
5175
|
+
detectedSessions = currentDevice?.processes ?? [];
|
|
5176
|
+
}
|
|
5177
|
+
} catch {
|
|
5178
|
+
workSessions = [];
|
|
5179
|
+
detectedSessions = [];
|
|
5180
|
+
}
|
|
5181
|
+
printOutput(
|
|
5182
|
+
{
|
|
5183
|
+
configured: status.configured,
|
|
5184
|
+
running: status.running,
|
|
5185
|
+
starting: status.starting,
|
|
5186
|
+
pid: status.pid,
|
|
5187
|
+
config: status.config,
|
|
5188
|
+
sessionInfo: buildMenuSessionInfo(session),
|
|
5189
|
+
workSessions,
|
|
5190
|
+
detectedSessions
|
|
5191
|
+
},
|
|
5192
|
+
Boolean(globalOptions.json)
|
|
5193
|
+
);
|
|
5194
|
+
});
|
|
5195
|
+
serviceCommand.command("search-issues <query>").description("Search issues for tray attach actions").option("--limit <n>").action(async (query, options, command) => {
|
|
5196
|
+
const { client, runtime } = await getClient(command);
|
|
5197
|
+
const orgSlug = requireOrg(runtime);
|
|
5198
|
+
const result = await runQuery(client, api.search.queries.searchEntities, {
|
|
5199
|
+
orgSlug,
|
|
5200
|
+
query,
|
|
5201
|
+
limit: optionalNumber(options.limit, "limit") ?? 8
|
|
5202
|
+
});
|
|
5203
|
+
printOutput(result.issues ?? [], runtime.json);
|
|
5204
|
+
});
|
|
5205
|
+
serviceCommand.command("attach-process").description("Attach a detected local process to an issue").requiredOption("--issue-id <id>").requiredOption("--device-id <id>").requiredOption("--process-id <id>").requiredOption("--provider <provider>").option("--title <title>").action(async (options, command) => {
|
|
5206
|
+
const { client, runtime } = await getClient(command);
|
|
5207
|
+
const liveActivityId = await runMutation(
|
|
5208
|
+
client,
|
|
5209
|
+
api.agentBridge.mutations.attachLiveActivity,
|
|
5210
|
+
{
|
|
5211
|
+
issueId: options.issueId,
|
|
5212
|
+
deviceId: options.deviceId,
|
|
5213
|
+
processId: options.processId,
|
|
5214
|
+
provider: parseAgentProvider(options.provider),
|
|
5215
|
+
title: options.title?.trim() || void 0
|
|
5216
|
+
}
|
|
5217
|
+
);
|
|
5218
|
+
printOutput({ ok: true, liveActivityId }, runtime.json);
|
|
5219
|
+
});
|
|
5220
|
+
serviceCommand.command("install").description("Install the bridge as a system service (macOS LaunchAgent)").action(async (_options, command) => {
|
|
5221
|
+
if (osPlatform() !== "darwin") {
|
|
5222
|
+
console.error("Service install is currently macOS only (LaunchAgent).");
|
|
5223
|
+
console.error("On Linux, use systemd --user manually for now.");
|
|
5224
|
+
return;
|
|
5225
|
+
}
|
|
5226
|
+
const { spinner } = await import("@clack/prompts");
|
|
5227
|
+
const s = spinner();
|
|
5228
|
+
s.start("Ensuring device registration...");
|
|
5229
|
+
const config = await ensureBridgeConfig(command);
|
|
5230
|
+
s.stop(`Device ready: ${config.displayName}`);
|
|
5231
|
+
s.start("Installing LaunchAgent...");
|
|
5232
|
+
const vcliPath = process.argv[1] ?? "vcli";
|
|
5233
|
+
installLaunchAgent(vcliPath);
|
|
5234
|
+
s.stop("LaunchAgent installed");
|
|
5235
|
+
s.start("Starting bridge service...");
|
|
5236
|
+
loadLaunchAgent();
|
|
5237
|
+
s.stop("Bridge service started");
|
|
5238
|
+
console.log("");
|
|
5239
|
+
console.log(
|
|
5240
|
+
"Bridge installed and running. Will start automatically on login."
|
|
5241
|
+
);
|
|
5242
|
+
});
|
|
5243
|
+
serviceCommand.command("uninstall").description("Stop the bridge and uninstall the system service").action(() => {
|
|
5244
|
+
stopBridge({ includeMenuBar: true });
|
|
5245
|
+
uninstallLaunchAgent();
|
|
5246
|
+
stopMenuBar();
|
|
5247
|
+
console.log("Bridge stopped and service uninstalled.");
|
|
5248
|
+
});
|
|
5249
|
+
serviceCommand.command("logs").description("Show bridge service logs").action(async () => {
|
|
5250
|
+
const fs7 = await import("fs");
|
|
5251
|
+
const p = await import("path");
|
|
5252
|
+
const logPath = p.join(VECTOR_HOME, "bridge.log");
|
|
5253
|
+
if (fs7.existsSync(logPath)) {
|
|
5254
|
+
const content = fs7.readFileSync(logPath, "utf-8");
|
|
5255
|
+
const lines = content.split("\n");
|
|
5256
|
+
console.log(lines.slice(-50).join("\n"));
|
|
5257
|
+
} else {
|
|
5258
|
+
console.log(`No log file found at ${logPath}`);
|
|
5259
|
+
}
|
|
5260
|
+
});
|
|
5261
|
+
serviceCommand.command("enable").description("Enable bridge to start at login (macOS LaunchAgent)").action(async () => {
|
|
5262
|
+
if (osPlatform() !== "darwin") {
|
|
5263
|
+
console.error("Login item is macOS only.");
|
|
5264
|
+
return;
|
|
5265
|
+
}
|
|
5266
|
+
const vcliPath = process.argv[1] ?? "vcli";
|
|
5267
|
+
installLaunchAgent(vcliPath);
|
|
5268
|
+
loadLaunchAgent();
|
|
5269
|
+
console.log("Bridge will start automatically on login.");
|
|
5270
|
+
});
|
|
5271
|
+
serviceCommand.command("disable").description("Disable bridge from starting at login").action(() => {
|
|
5272
|
+
uninstallLaunchAgent();
|
|
5273
|
+
stopMenuBar();
|
|
5274
|
+
console.log("Bridge will no longer start at login.");
|
|
5275
|
+
});
|
|
5276
|
+
var bridgeCommand = program.command("bridge").description("Start/stop the local agent bridge");
|
|
5277
|
+
bridgeCommand.command("start").description("Register device, install service, and start the bridge").action(async (_options, command) => {
|
|
5278
|
+
const existingConfig = loadBridgeConfig();
|
|
5279
|
+
const config = await ensureBridgeConfig(command);
|
|
5280
|
+
if (!existingConfig || existingConfig.deviceId !== config.deviceId || existingConfig.userId !== config.userId) {
|
|
5281
|
+
console.log(
|
|
5282
|
+
`Device registered: ${config.displayName} (${config.deviceId})`
|
|
5283
|
+
);
|
|
5284
|
+
}
|
|
5285
|
+
if (osPlatform() === "darwin") {
|
|
5286
|
+
const vcliPath = process.argv[1] ?? "vcli";
|
|
5287
|
+
installLaunchAgent(vcliPath);
|
|
5288
|
+
loadLaunchAgent();
|
|
5289
|
+
console.log("\nBridge installed and started as LaunchAgent.");
|
|
5290
|
+
console.log("It will restart automatically on login.");
|
|
5291
|
+
console.log("Run `vcli service status` to check.");
|
|
5292
|
+
} else {
|
|
5293
|
+
console.log("Starting bridge in foreground...");
|
|
5294
|
+
const bridge = new BridgeService(config);
|
|
5295
|
+
await bridge.run();
|
|
5296
|
+
}
|
|
5297
|
+
});
|
|
5298
|
+
bridgeCommand.command("stop").description("Stop the bridge service").action(() => {
|
|
5299
|
+
let unloaded = false;
|
|
5300
|
+
if (osPlatform() === "darwin") {
|
|
5301
|
+
uninstallLaunchAgent();
|
|
5302
|
+
unloaded = true;
|
|
5303
|
+
}
|
|
5304
|
+
if (stopBridge() || unloaded) {
|
|
5305
|
+
console.log("Bridge stopped.");
|
|
5306
|
+
} else {
|
|
5307
|
+
console.log("Bridge is not running.");
|
|
5308
|
+
}
|
|
5309
|
+
});
|
|
5310
|
+
bridgeCommand.command("status").description("Show bridge status").action(() => {
|
|
5311
|
+
const s = getBridgeStatus();
|
|
5312
|
+
if (!s.configured) {
|
|
5313
|
+
console.log("Bridge not configured. Run: vcli bridge start");
|
|
5314
|
+
return;
|
|
5315
|
+
}
|
|
5316
|
+
console.log("Vector Bridge");
|
|
5317
|
+
console.log(` Device: ${s.config.displayName} (${s.config.deviceId})`);
|
|
5318
|
+
console.log(
|
|
5319
|
+
` Status: ${s.running ? `Running (PID ${s.pid})` : "Not running"}`
|
|
5320
|
+
);
|
|
5321
|
+
});
|
|
2035
5322
|
async function main() {
|
|
2036
5323
|
await program.parseAsync(process.argv);
|
|
2037
5324
|
}
|