@rehpic/vcli 0.1.0-beta.9.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 execFileSync3 } 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
- // ../../src/cli/index.ts
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
- // ../../src/cli/auth.ts
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.user ?? null
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
- // ../../src/cli/convex.ts
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);
@@ -208,7 +1008,7 @@ async function runAction(client, ref, ...args) {
208
1008
  return await client.action(ref, ...args);
209
1009
  }
210
1010
 
211
- // ../../src/cli/output.ts
1011
+ // src/output.ts
212
1012
  function simplify(value) {
213
1013
  if (value === null || value === void 0) {
214
1014
  return value;
@@ -255,13 +1055,68 @@ function printOutput(data, json = false) {
255
1055
  console.log(String(data));
256
1056
  }
257
1057
 
258
- // ../../src/cli/session.ts
259
- import { mkdir, readFile, rm, writeFile } from "fs/promises";
1058
+ // src/session.ts
1059
+ import { mkdir, readFile, readdir, rm, writeFile } from "fs/promises";
260
1060
  import { homedir } from "os";
261
1061
  import path from "path";
262
- var SESSION_ROOT = path.join(homedir(), ".vector");
1062
+ function getSessionRoot() {
1063
+ return process.env.VECTOR_HOME?.trim() || path.join(homedir(), ".vector");
1064
+ }
1065
+ function getProfileConfigPath() {
1066
+ return path.join(getSessionRoot(), "cli-config.json");
1067
+ }
263
1068
  function getSessionPath(profile = "default") {
264
- return path.join(SESSION_ROOT, `cli-${profile}.json`);
1069
+ return path.join(getSessionRoot(), `cli-${profile}.json`);
1070
+ }
1071
+ async function readDefaultProfile() {
1072
+ try {
1073
+ const raw = await readFile(getProfileConfigPath(), "utf8");
1074
+ const parsed = JSON.parse(raw);
1075
+ const profile = parsed.defaultProfile?.trim();
1076
+ return profile || "default";
1077
+ } catch {
1078
+ return "default";
1079
+ }
1080
+ }
1081
+ async function writeDefaultProfile(profile) {
1082
+ const normalized = profile.trim() || "default";
1083
+ await mkdir(getSessionRoot(), { recursive: true });
1084
+ const config = {
1085
+ version: 1,
1086
+ defaultProfile: normalized
1087
+ };
1088
+ await writeFile(
1089
+ getProfileConfigPath(),
1090
+ `${JSON.stringify(config, null, 2)}
1091
+ `,
1092
+ "utf8"
1093
+ );
1094
+ }
1095
+ async function listProfiles() {
1096
+ const root = getSessionRoot();
1097
+ const defaultProfile = await readDefaultProfile();
1098
+ try {
1099
+ const entries = await readdir(root, { withFileTypes: true });
1100
+ const names = entries.filter((entry) => entry.isFile()).map((entry) => entry.name).filter((name) => /^cli-.+\.json$/.test(name)).map((name) => name.replace(/^cli-/, "").replace(/\.json$/, ""));
1101
+ const uniqueNames = Array.from(/* @__PURE__ */ new Set([...names, defaultProfile])).sort(
1102
+ (left, right) => left.localeCompare(right)
1103
+ );
1104
+ return Promise.all(
1105
+ uniqueNames.map(async (name) => ({
1106
+ name,
1107
+ isDefault: name === defaultProfile,
1108
+ hasSession: await readSession(name) !== null
1109
+ }))
1110
+ );
1111
+ } catch {
1112
+ return [
1113
+ {
1114
+ name: defaultProfile,
1115
+ isDefault: true,
1116
+ hasSession: await readSession(defaultProfile) !== null
1117
+ }
1118
+ ];
1119
+ }
265
1120
  }
266
1121
  async function readSession(profile = "default") {
267
1122
  try {
@@ -273,29 +1128,2312 @@ async function readSession(profile = "default") {
273
1128
  ...parsed
274
1129
  };
275
1130
  } catch {
276
- return null;
1131
+ return null;
1132
+ }
1133
+ }
1134
+ async function writeSession(session, profile = "default") {
1135
+ await mkdir(getSessionRoot(), { recursive: true });
1136
+ await writeFile(
1137
+ getSessionPath(profile),
1138
+ `${JSON.stringify(session, null, 2)}
1139
+ `,
1140
+ "utf8"
1141
+ );
1142
+ }
1143
+ async function clearSession(profile = "default") {
1144
+ await rm(getSessionPath(profile), { force: true });
1145
+ }
1146
+ function createEmptySession() {
1147
+ return {
1148
+ version: 1,
1149
+ cookies: {}
1150
+ };
1151
+ }
1152
+
1153
+ // src/bridge-service.ts
1154
+ import { ConvexHttpClient as ConvexHttpClient2 } from "convex/browser";
1155
+ import { execFileSync as execFileSync2, execSync as execSync2 } from "child_process";
1156
+
1157
+ // src/terminal-peer.ts
1158
+ import { createServer } from "http";
1159
+ import { WebSocketServer, WebSocket } from "ws";
1160
+ import { ConvexClient } from "convex/browser";
1161
+ import * as pty from "node-pty";
1162
+ import { existsSync } from "fs";
1163
+ import { randomUUID } from "crypto";
1164
+ import { execFileSync } from "child_process";
1165
+ import localtunnel from "localtunnel";
1166
+ function findTmuxPath() {
1167
+ for (const p of [
1168
+ "/opt/homebrew/bin/tmux",
1169
+ "/usr/local/bin/tmux",
1170
+ "/usr/bin/tmux"
1171
+ ]) {
1172
+ if (existsSync(p)) return p;
1173
+ }
1174
+ return "tmux";
1175
+ }
1176
+ var TMUX = findTmuxPath();
1177
+ function ts() {
1178
+ return (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
1179
+ }
1180
+ function findPort() {
1181
+ return new Promise((resolve, reject) => {
1182
+ const srv = createServer();
1183
+ srv.listen(0, "127.0.0.1", () => {
1184
+ const addr = srv.address();
1185
+ const port = typeof addr === "object" && addr ? addr.port : 9100;
1186
+ srv.close(() => resolve(port));
1187
+ });
1188
+ srv.on("error", reject);
1189
+ });
1190
+ }
1191
+ function createViewerSession(targetSession, paneId) {
1192
+ const viewerName = `viewer-${randomUUID().slice(0, 8)}`;
1193
+ try {
1194
+ execFileSync(TMUX, [
1195
+ "new-session",
1196
+ "-d",
1197
+ "-s",
1198
+ viewerName,
1199
+ "-t",
1200
+ targetSession
1201
+ ]);
1202
+ execFileSync(TMUX, ["set-option", "-t", viewerName, "status", "off"]);
1203
+ if (paneId) {
1204
+ try {
1205
+ execFileSync(TMUX, ["select-pane", "-t", paneId]);
1206
+ } catch {
1207
+ }
1208
+ }
1209
+ return viewerName;
1210
+ } catch (err) {
1211
+ console.error(`[${ts()}] Failed to create viewer session:`, err);
1212
+ return targetSession;
1213
+ }
1214
+ }
1215
+ function killViewerSession(sessionName) {
1216
+ try {
1217
+ execFileSync(TMUX, ["kill-session", "-t", sessionName]);
1218
+ } catch {
1219
+ }
1220
+ }
1221
+ var TerminalPeerManager = class {
1222
+ constructor(config) {
1223
+ this.terminals = /* @__PURE__ */ new Map();
1224
+ this.failedSessions = /* @__PURE__ */ new Set();
1225
+ this.pendingStops = /* @__PURE__ */ new Map();
1226
+ this.unsubscribers = /* @__PURE__ */ new Map();
1227
+ this.config = config;
1228
+ this.client = new ConvexClient(config.convexUrl);
1229
+ }
1230
+ watchSession(workSessionId, tmuxSessionName, tmuxPaneId) {
1231
+ if (this.unsubscribers.has(workSessionId)) return;
1232
+ const unsub = this.client.onUpdate(
1233
+ api.agentBridge.bridgePublic.getWorkSessionTerminalState,
1234
+ {
1235
+ deviceId: this.config.deviceId,
1236
+ deviceSecret: this.config.deviceSecret,
1237
+ workSessionId
1238
+ },
1239
+ (state) => {
1240
+ if (!state) return;
1241
+ const terminal = this.terminals.get(workSessionId);
1242
+ if (state.terminalViewerActive && !terminal && !this.failedSessions.has(workSessionId)) {
1243
+ const pendingStop = this.pendingStops.get(workSessionId);
1244
+ if (pendingStop) {
1245
+ clearTimeout(pendingStop);
1246
+ this.pendingStops.delete(workSessionId);
1247
+ }
1248
+ console.log(`[${ts()}] Viewer active for ${tmuxSessionName}`);
1249
+ void this.startTerminal(
1250
+ workSessionId,
1251
+ tmuxSessionName,
1252
+ tmuxPaneId,
1253
+ state.terminalCols,
1254
+ state.terminalRows
1255
+ );
1256
+ } else if (!state.terminalViewerActive && terminal) {
1257
+ if (!this.pendingStops.has(workSessionId)) {
1258
+ this.pendingStops.set(
1259
+ workSessionId,
1260
+ setTimeout(() => {
1261
+ this.pendingStops.delete(workSessionId);
1262
+ console.log(`[${ts()}] Viewer inactive for ${tmuxSessionName}`);
1263
+ this.stopTerminal(workSessionId);
1264
+ this.failedSessions.delete(workSessionId);
1265
+ }, 2e3)
1266
+ );
1267
+ }
1268
+ }
1269
+ }
1270
+ );
1271
+ this.unsubscribers.set(workSessionId, unsub);
1272
+ }
1273
+ unwatchSession(workSessionId) {
1274
+ const unsub = this.unsubscribers.get(workSessionId);
1275
+ if (unsub) {
1276
+ unsub();
1277
+ this.unsubscribers.delete(workSessionId);
1278
+ }
1279
+ this.stopTerminal(workSessionId);
1280
+ }
1281
+ async startTerminal(workSessionId, tmuxSessionName, tmuxPaneId, cols, rows) {
1282
+ if (this.terminals.has(workSessionId)) return;
1283
+ try {
1284
+ const port = await findPort();
1285
+ const viewerSession = createViewerSession(tmuxSessionName, tmuxPaneId);
1286
+ const isLinked = viewerSession !== tmuxSessionName;
1287
+ console.log(
1288
+ `[${ts()}] Viewer session: ${viewerSession}${isLinked ? " (linked)" : ""}`
1289
+ );
1290
+ console.log(
1291
+ `[${ts()}] Spawning PTY: ${TMUX} attach-session -t ${viewerSession}`
1292
+ );
1293
+ const ptyProcess = pty.spawn(
1294
+ TMUX,
1295
+ ["attach-session", "-t", viewerSession],
1296
+ {
1297
+ name: "xterm-256color",
1298
+ cols: Math.max(cols, 10),
1299
+ rows: Math.max(rows, 4),
1300
+ cwd: process.env.HOME ?? "/",
1301
+ env: { ...process.env, TERM: "xterm-256color" }
1302
+ }
1303
+ );
1304
+ console.log(`[${ts()}] PTY started`);
1305
+ const token = randomUUID();
1306
+ const httpServer = createServer();
1307
+ const wss = new WebSocketServer({ server: httpServer });
1308
+ wss.on("connection", (ws, req) => {
1309
+ const url = new URL(req.url ?? "/", `http://localhost`);
1310
+ const clientToken = url.searchParams.get("token");
1311
+ if (clientToken !== token) {
1312
+ console.log(`[${ts()}] Rejected unauthorized connection`);
1313
+ ws.close(4401, "Unauthorized");
1314
+ return;
1315
+ }
1316
+ console.log(`[${ts()}] Client connected (${tmuxSessionName})`);
1317
+ try {
1318
+ execFileSync(TMUX, ["refresh-client", "-t", viewerSession]);
1319
+ } catch {
1320
+ }
1321
+ const dataHandler = ptyProcess.onData((data) => {
1322
+ if (ws.readyState === WebSocket.OPEN) {
1323
+ ws.send(data);
1324
+ }
1325
+ });
1326
+ ws.on("message", (msg) => {
1327
+ const str = msg.toString();
1328
+ if (str.startsWith("\0{")) {
1329
+ try {
1330
+ const parsed = JSON.parse(str.slice(1));
1331
+ if (parsed.type === "resize" && parsed.cols && parsed.rows) {
1332
+ ptyProcess.resize(
1333
+ Math.max(parsed.cols, 10),
1334
+ Math.max(parsed.rows, 4)
1335
+ );
1336
+ try {
1337
+ execFileSync(TMUX, ["refresh-client", "-t", viewerSession]);
1338
+ } catch {
1339
+ }
1340
+ return;
1341
+ }
1342
+ } catch {
1343
+ }
1344
+ }
1345
+ ptyProcess.write(str);
1346
+ });
1347
+ ws.on("close", () => {
1348
+ console.log(`[${ts()}] Client disconnected (${tmuxSessionName})`);
1349
+ dataHandler.dispose();
1350
+ });
1351
+ });
1352
+ await new Promise((resolve) => {
1353
+ httpServer.listen(port, "0.0.0.0", resolve);
1354
+ });
1355
+ console.log(`[${ts()}] WS server on port ${port}`);
1356
+ const tunnelOpts = { port };
1357
+ if (this.config.tunnelHost) {
1358
+ tunnelOpts.host = this.config.tunnelHost;
1359
+ }
1360
+ console.log(
1361
+ `[${ts()}] Opening tunnel...${this.config.tunnelHost ? ` (host: ${this.config.tunnelHost})` : ""}`
1362
+ );
1363
+ const tunnel = await localtunnel(tunnelOpts);
1364
+ const tunnelUrl = tunnel.url;
1365
+ console.log(`[${ts()}] Tunnel: ${tunnelUrl}`);
1366
+ const wsUrl = tunnelUrl.replace(/^https?:\/\//, "wss://");
1367
+ const terminal = {
1368
+ ptyProcess,
1369
+ httpServer,
1370
+ wss,
1371
+ tunnel,
1372
+ viewerSessionName: isLinked ? viewerSession : null,
1373
+ token,
1374
+ workSessionId,
1375
+ tmuxSessionName,
1376
+ port
1377
+ };
1378
+ this.terminals.set(workSessionId, terminal);
1379
+ await this.client.mutation(
1380
+ api.agentBridge.bridgePublic.updateWorkSessionTerminalUrl,
1381
+ {
1382
+ deviceId: this.config.deviceId,
1383
+ deviceSecret: this.config.deviceSecret,
1384
+ workSessionId,
1385
+ terminalUrl: wsUrl,
1386
+ terminalToken: token,
1387
+ terminalLocalPort: port
1388
+ }
1389
+ );
1390
+ ptyProcess.onExit(() => {
1391
+ console.log(`[${ts()}] PTY exited for ${tmuxSessionName}`);
1392
+ this.stopTerminal(workSessionId);
1393
+ });
1394
+ } catch (err) {
1395
+ console.error(`[${ts()}] Failed to start terminal:`, err);
1396
+ this.failedSessions.add(workSessionId);
1397
+ }
1398
+ }
1399
+ stopTerminal(workSessionId) {
1400
+ const terminal = this.terminals.get(workSessionId);
1401
+ if (!terminal) return;
1402
+ try {
1403
+ terminal.ptyProcess.kill();
1404
+ } catch {
1405
+ }
1406
+ try {
1407
+ terminal.tunnel.close();
1408
+ } catch {
1409
+ }
1410
+ try {
1411
+ terminal.wss.close();
1412
+ } catch {
1413
+ }
1414
+ try {
1415
+ terminal.httpServer.close();
1416
+ } catch {
1417
+ }
1418
+ if (terminal.viewerSessionName) {
1419
+ killViewerSession(terminal.viewerSessionName);
1420
+ }
1421
+ this.terminals.delete(workSessionId);
1422
+ console.log(`[${ts()}] Terminal stopped for ${terminal.tmuxSessionName}`);
1423
+ }
1424
+ stop() {
1425
+ for (const unsub of this.unsubscribers.values()) {
1426
+ try {
1427
+ unsub();
1428
+ } catch {
1429
+ }
1430
+ }
1431
+ this.unsubscribers.clear();
1432
+ for (const id of this.terminals.keys()) {
1433
+ this.stopTerminal(id);
1434
+ }
1435
+ void this.client.close();
1436
+ }
1437
+ };
1438
+
1439
+ // src/bridge-service.ts
1440
+ import {
1441
+ existsSync as existsSync3,
1442
+ mkdirSync,
1443
+ readFileSync as readFileSync2,
1444
+ writeFileSync,
1445
+ unlinkSync
1446
+ } from "fs";
1447
+ import { homedir as homedir3, hostname, platform } from "os";
1448
+ import { join as join2 } from "path";
1449
+ import { randomUUID as randomUUID2 } from "crypto";
1450
+
1451
+ // src/agent-adapters.ts
1452
+ import { execSync, spawn as spawn2 } from "child_process";
1453
+ import { existsSync as existsSync2, readFileSync, readdirSync } from "fs";
1454
+ import { homedir as homedir2, userInfo } from "os";
1455
+ import { basename, join } from "path";
1456
+ var LSOF_PATHS = ["/usr/sbin/lsof", "/usr/bin/lsof"];
1457
+ var VECTOR_BRIDGE_CLIENT_VERSION = "0.1.0";
1458
+ function discoverAttachableSessions() {
1459
+ return dedupeSessions([
1460
+ ...discoverTmuxSessions(),
1461
+ ...discoverCodexSessions(),
1462
+ ...discoverClaudeSessions()
1463
+ ]);
1464
+ }
1465
+ async function resumeProviderSession(provider, sessionKey, cwd, prompt2) {
1466
+ if (provider === "codex") {
1467
+ return runCodexAppServerTurn({
1468
+ cwd,
1469
+ prompt: prompt2,
1470
+ sessionKey,
1471
+ launchCommand: "codex app-server (thread/resume)"
1472
+ });
1473
+ }
1474
+ return runClaudeSdkTurn({
1475
+ cwd,
1476
+ prompt: prompt2,
1477
+ sessionKey,
1478
+ launchCommand: "@anthropic-ai/claude-agent-sdk query(resume)"
1479
+ });
1480
+ }
1481
+ async function runCodexAppServerTurn(args) {
1482
+ const child = spawn2("codex", ["app-server"], {
1483
+ cwd: args.cwd,
1484
+ env: { ...process.env },
1485
+ stdio: ["pipe", "pipe", "pipe"]
1486
+ });
1487
+ let stderr = "";
1488
+ let stdoutBuffer = "";
1489
+ let sessionKey = args.sessionKey;
1490
+ let finalAssistantText = "";
1491
+ let completed = false;
1492
+ let nextRequestId = 1;
1493
+ const pending = /* @__PURE__ */ new Map();
1494
+ let completeTurn;
1495
+ let failTurn;
1496
+ const turnCompleted = new Promise((resolve, reject) => {
1497
+ completeTurn = () => {
1498
+ completed = true;
1499
+ resolve();
1500
+ };
1501
+ failTurn = (error) => {
1502
+ completed = true;
1503
+ reject(error);
1504
+ };
1505
+ });
1506
+ child.stdout.on("data", (chunk) => {
1507
+ stdoutBuffer += chunk.toString();
1508
+ while (true) {
1509
+ const newlineIndex = stdoutBuffer.indexOf("\n");
1510
+ if (newlineIndex < 0) {
1511
+ break;
1512
+ }
1513
+ const line = stdoutBuffer.slice(0, newlineIndex).trim();
1514
+ stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1);
1515
+ if (!line) {
1516
+ continue;
1517
+ }
1518
+ const payload = tryParseJson(line);
1519
+ if (!payload || typeof payload !== "object") {
1520
+ continue;
1521
+ }
1522
+ const responseId = payload.id;
1523
+ if (typeof responseId === "number" && pending.has(responseId)) {
1524
+ const entry = pending.get(responseId);
1525
+ pending.delete(responseId);
1526
+ const errorRecord = asObject(payload.error);
1527
+ if (errorRecord) {
1528
+ entry.reject(
1529
+ new Error(
1530
+ `codex app-server error: ${asString(errorRecord.message) ?? "Unknown JSON-RPC error"}`
1531
+ )
1532
+ );
1533
+ continue;
1534
+ }
1535
+ entry.resolve(payload.result);
1536
+ continue;
1537
+ }
1538
+ const method = asString(payload.method);
1539
+ const params = asObject(payload.params);
1540
+ if (!method || !params) {
1541
+ continue;
1542
+ }
1543
+ if (method === "thread/started") {
1544
+ sessionKey = asString(asObject(params.thread)?.id) ?? asString(asObject(params.thread)?.threadId) ?? sessionKey;
1545
+ continue;
1546
+ }
1547
+ if (method === "item/agentMessage/delta") {
1548
+ finalAssistantText += asString(params.delta) ?? "";
1549
+ continue;
1550
+ }
1551
+ if (method === "item/completed") {
1552
+ const item = asObject(params.item);
1553
+ if (asString(item?.type) === "agentMessage") {
1554
+ finalAssistantText = asString(item?.text) ?? finalAssistantText;
1555
+ }
1556
+ continue;
1557
+ }
1558
+ if (method === "turn/completed") {
1559
+ const turn = asObject(params.turn);
1560
+ const status = asString(turn?.status);
1561
+ if (status === "failed") {
1562
+ const turnError = asObject(turn?.error);
1563
+ failTurn?.(
1564
+ new Error(
1565
+ asString(turnError?.message) ?? "Codex turn failed without an error message"
1566
+ )
1567
+ );
1568
+ } else if (status === "interrupted") {
1569
+ failTurn?.(new Error("Codex turn was interrupted"));
1570
+ } else {
1571
+ completeTurn?.();
1572
+ }
1573
+ }
1574
+ }
1575
+ });
1576
+ child.stderr.on("data", (chunk) => {
1577
+ stderr += chunk.toString();
1578
+ });
1579
+ const request = (method, params) => new Promise((resolve, reject) => {
1580
+ const id = nextRequestId++;
1581
+ pending.set(id, { resolve, reject });
1582
+ child.stdin.write(`${JSON.stringify({ method, id, params })}
1583
+ `);
1584
+ });
1585
+ const notify = (method, params) => {
1586
+ child.stdin.write(`${JSON.stringify({ method, params })}
1587
+ `);
1588
+ };
1589
+ const waitForExit = new Promise((_, reject) => {
1590
+ child.on("error", (error) => reject(error));
1591
+ child.on("close", (code) => {
1592
+ if (!completed) {
1593
+ const detail = stderr.trim() || `codex app-server exited with code ${code}`;
1594
+ reject(new Error(detail));
1595
+ }
1596
+ });
1597
+ });
1598
+ try {
1599
+ await Promise.race([
1600
+ request("initialize", {
1601
+ clientInfo: {
1602
+ name: "vector_bridge",
1603
+ title: "Vector Bridge",
1604
+ version: VECTOR_BRIDGE_CLIENT_VERSION
1605
+ }
1606
+ }),
1607
+ waitForExit
1608
+ ]);
1609
+ notify("initialized", {});
1610
+ const threadResult = await Promise.race([
1611
+ args.sessionKey ? request("thread/resume", {
1612
+ threadId: args.sessionKey,
1613
+ cwd: args.cwd,
1614
+ approvalPolicy: "never",
1615
+ personality: "pragmatic"
1616
+ }) : request("thread/start", {
1617
+ cwd: args.cwd,
1618
+ approvalPolicy: "never",
1619
+ personality: "pragmatic",
1620
+ serviceName: "vector_bridge"
1621
+ }),
1622
+ waitForExit
1623
+ ]);
1624
+ sessionKey = asString(asObject(threadResult.thread)?.id) ?? asString(asObject(threadResult.thread)?.threadId) ?? sessionKey;
1625
+ if (!sessionKey) {
1626
+ throw new Error("Codex app-server did not return a thread id");
1627
+ }
1628
+ await Promise.race([
1629
+ request("turn/start", {
1630
+ threadId: sessionKey,
1631
+ input: [{ type: "text", text: args.prompt }],
1632
+ cwd: args.cwd,
1633
+ approvalPolicy: "never",
1634
+ personality: "pragmatic"
1635
+ }),
1636
+ waitForExit
1637
+ ]);
1638
+ await Promise.race([turnCompleted, waitForExit]);
1639
+ const gitInfo = getGitInfo(args.cwd);
1640
+ return {
1641
+ provider: "codex",
1642
+ providerLabel: "Codex",
1643
+ sessionKey,
1644
+ cwd: args.cwd,
1645
+ ...gitInfo,
1646
+ title: summarizeTitle(void 0, args.cwd),
1647
+ mode: "managed",
1648
+ status: "waiting",
1649
+ supportsInboundMessages: true,
1650
+ responseText: finalAssistantText.trim() || void 0,
1651
+ launchCommand: args.launchCommand
1652
+ };
1653
+ } finally {
1654
+ for (const entry of pending.values()) {
1655
+ entry.reject(
1656
+ new Error("codex app-server closed before request resolved")
1657
+ );
1658
+ }
1659
+ pending.clear();
1660
+ child.kill();
1661
+ }
1662
+ }
1663
+ async function runClaudeSdkTurn(args) {
1664
+ const { query } = await import("@anthropic-ai/claude-agent-sdk");
1665
+ const stream = query({
1666
+ prompt: args.prompt,
1667
+ options: {
1668
+ cwd: args.cwd,
1669
+ resume: args.sessionKey,
1670
+ persistSession: true,
1671
+ permissionMode: "bypassPermissions",
1672
+ allowDangerouslySkipPermissions: true,
1673
+ env: {
1674
+ ...process.env,
1675
+ CLAUDE_AGENT_SDK_CLIENT_APP: `vector-bridge/${VECTOR_BRIDGE_CLIENT_VERSION}`
1676
+ }
1677
+ }
1678
+ });
1679
+ let sessionKey = args.sessionKey;
1680
+ let responseText = "";
1681
+ let model;
1682
+ try {
1683
+ for await (const message of stream) {
1684
+ if (!message || typeof message !== "object") {
1685
+ continue;
1686
+ }
1687
+ sessionKey = asString(message.session_id) ?? sessionKey;
1688
+ if (message.type === "assistant") {
1689
+ const assistantText = extractClaudeMessageTexts(
1690
+ message.message
1691
+ ).join("\n\n").trim();
1692
+ if (assistantText) {
1693
+ responseText = assistantText;
1694
+ }
1695
+ continue;
1696
+ }
1697
+ if (message.type !== "result") {
1698
+ continue;
1699
+ }
1700
+ if (message.subtype === "success") {
1701
+ const resultText = asString(message.result);
1702
+ if (resultText) {
1703
+ responseText = resultText;
1704
+ }
1705
+ model = firstObjectKey(
1706
+ message.modelUsage
1707
+ );
1708
+ continue;
1709
+ }
1710
+ const errors = message.errors;
1711
+ const detail = Array.isArray(errors) && errors.length > 0 ? errors.join("\n") : "Claude execution failed";
1712
+ throw new Error(detail);
1713
+ }
1714
+ } finally {
1715
+ stream.close();
1716
+ }
1717
+ if (!sessionKey) {
1718
+ throw new Error("Claude Agent SDK did not return a session id");
1719
+ }
1720
+ const gitInfo = getGitInfo(args.cwd);
1721
+ return {
1722
+ provider: "claude_code",
1723
+ providerLabel: "Claude",
1724
+ sessionKey,
1725
+ cwd: args.cwd,
1726
+ ...gitInfo,
1727
+ title: summarizeTitle(void 0, args.cwd),
1728
+ model,
1729
+ mode: "managed",
1730
+ status: "waiting",
1731
+ supportsInboundMessages: true,
1732
+ responseText: responseText.trim() || void 0,
1733
+ launchCommand: args.launchCommand
1734
+ };
1735
+ }
1736
+ function discoverCodexSessions() {
1737
+ const historyBySession = buildCodexHistoryIndex();
1738
+ return listLiveProcessIds("codex").flatMap((pid) => {
1739
+ const transcriptPath = getCodexTranscriptPath(pid);
1740
+ if (!transcriptPath) {
1741
+ return [];
1742
+ }
1743
+ const processCwd = getProcessCwd(pid);
1744
+ const parsed = parseObservedCodexSession(
1745
+ pid,
1746
+ transcriptPath,
1747
+ processCwd,
1748
+ historyBySession
1749
+ );
1750
+ return parsed ? [parsed] : [];
1751
+ }).sort(compareObservedSessions);
1752
+ }
1753
+ function discoverClaudeSessions() {
1754
+ const historyBySession = buildClaudeHistoryIndex();
1755
+ return listLiveProcessIds("claude").flatMap((pid) => {
1756
+ const sessionMeta = readClaudePidSession(pid);
1757
+ if (!sessionMeta?.sessionId) {
1758
+ return [];
1759
+ }
1760
+ const transcriptPath = findClaudeTranscriptPath(sessionMeta.sessionId);
1761
+ const parsed = parseObservedClaudeSession(
1762
+ pid,
1763
+ sessionMeta,
1764
+ transcriptPath,
1765
+ historyBySession
1766
+ );
1767
+ return parsed ? [parsed] : [];
1768
+ }).sort(compareObservedSessions);
1769
+ }
1770
+ function discoverTmuxSessions() {
1771
+ try {
1772
+ const output = execSync(
1773
+ "tmux list-panes -a -F '#{pane_id} #{pane_pid} #{session_name} #{window_name} #{pane_current_path} #{pane_current_command} #{pane_title}'",
1774
+ {
1775
+ encoding: "utf-8",
1776
+ timeout: 3e3
1777
+ }
1778
+ );
1779
+ return output.split("\n").map((line) => line.trim()).filter(Boolean).flatMap((line) => {
1780
+ const [
1781
+ paneId,
1782
+ panePid,
1783
+ sessionName,
1784
+ windowName,
1785
+ cwd,
1786
+ currentCommand,
1787
+ paneTitle
1788
+ ] = line.split(" ");
1789
+ if (!paneId || !panePid || !sessionName || !windowName || !cwd) {
1790
+ return [];
1791
+ }
1792
+ const normalizedCommand = (currentCommand ?? "").trim().toLowerCase();
1793
+ if (normalizedCommand === "codex" || normalizedCommand === "claude") {
1794
+ return [];
1795
+ }
1796
+ const gitInfo = getGitInfo(cwd);
1797
+ const title = summarizeTitle(
1798
+ buildTmuxPaneTitle({
1799
+ paneTitle,
1800
+ sessionName,
1801
+ windowName,
1802
+ cwd,
1803
+ currentCommand
1804
+ }),
1805
+ cwd
1806
+ );
1807
+ return [
1808
+ {
1809
+ provider: "vector_cli",
1810
+ providerLabel: "Tmux",
1811
+ localProcessId: panePid,
1812
+ sessionKey: `tmux:${paneId}`,
1813
+ cwd,
1814
+ ...gitInfo,
1815
+ title,
1816
+ tmuxSessionName: sessionName,
1817
+ tmuxWindowName: windowName,
1818
+ tmuxPaneId: paneId,
1819
+ mode: "observed",
1820
+ status: "observed",
1821
+ supportsInboundMessages: true
1822
+ }
1823
+ ];
1824
+ }).sort(compareObservedSessions);
1825
+ } catch {
1826
+ return [];
1827
+ }
1828
+ }
1829
+ function getCodexHistoryFile() {
1830
+ return join(getRealHomeDir(), ".codex", "history.jsonl");
1831
+ }
1832
+ function getClaudeProjectsDir() {
1833
+ return join(getRealHomeDir(), ".claude", "projects");
1834
+ }
1835
+ function getClaudeSessionStateDir() {
1836
+ return join(getRealHomeDir(), ".claude", "sessions");
1837
+ }
1838
+ function getClaudeHistoryFile() {
1839
+ return join(getRealHomeDir(), ".claude", "history.jsonl");
1840
+ }
1841
+ function getRealHomeDir() {
1842
+ try {
1843
+ const realHome = userInfo().homedir?.trim();
1844
+ if (realHome) {
1845
+ return realHome;
1846
+ }
1847
+ } catch {
1848
+ }
1849
+ return homedir2();
1850
+ }
1851
+ function resolveExecutable(fallbackCommand, absoluteCandidates) {
1852
+ for (const candidate of absoluteCandidates) {
1853
+ if (existsSync2(candidate)) {
1854
+ return candidate;
1855
+ }
1856
+ }
1857
+ try {
1858
+ const output = execSync(`command -v ${fallbackCommand}`, {
1859
+ encoding: "utf-8",
1860
+ timeout: 1e3
1861
+ }).trim();
1862
+ return output || void 0;
1863
+ } catch {
1864
+ return void 0;
1865
+ }
1866
+ }
1867
+ function listLiveProcessIds(commandName) {
1868
+ try {
1869
+ const output = execSync("ps -axo pid=,comm=", {
1870
+ encoding: "utf-8",
1871
+ timeout: 3e3
1872
+ });
1873
+ 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);
1874
+ } catch {
1875
+ return [];
1876
+ }
1877
+ }
1878
+ function getProcessCwd(pid) {
1879
+ const lsofCommand = resolveExecutable("lsof", LSOF_PATHS);
1880
+ if (!lsofCommand) {
1881
+ return void 0;
1882
+ }
1883
+ try {
1884
+ const output = execSync(`${lsofCommand} -a -p ${pid} -Fn -d cwd`, {
1885
+ encoding: "utf-8",
1886
+ timeout: 3e3
1887
+ });
1888
+ return output.split("\n").map((line) => line.trim()).find((line) => line.startsWith("n"))?.slice(1);
1889
+ } catch {
1890
+ return void 0;
1891
+ }
1892
+ }
1893
+ function getCodexTranscriptPath(pid) {
1894
+ const lsofCommand = resolveExecutable("lsof", LSOF_PATHS);
1895
+ if (!lsofCommand) {
1896
+ return void 0;
1897
+ }
1898
+ try {
1899
+ const output = execSync(`${lsofCommand} -p ${pid} -Fn`, {
1900
+ encoding: "utf-8",
1901
+ timeout: 3e3
1902
+ });
1903
+ return output.split("\n").map((line) => line.trim()).find(
1904
+ (line) => line.startsWith("n") && line.includes("/.codex/sessions/") && line.endsWith(".jsonl")
1905
+ )?.slice(1);
1906
+ } catch {
1907
+ return void 0;
1908
+ }
1909
+ }
1910
+ function readClaudePidSession(pid) {
1911
+ const path3 = join(getClaudeSessionStateDir(), `${pid}.json`);
1912
+ if (!existsSync2(path3)) {
1913
+ return null;
1914
+ }
1915
+ try {
1916
+ const payload = JSON.parse(readFileSync(path3, "utf-8"));
1917
+ const sessionId = asString(payload.sessionId);
1918
+ if (!sessionId) {
1919
+ return null;
1920
+ }
1921
+ return {
1922
+ sessionId,
1923
+ cwd: asString(payload.cwd),
1924
+ startedAt: typeof payload.startedAt === "number" ? payload.startedAt : void 0
1925
+ };
1926
+ } catch {
1927
+ return null;
1928
+ }
1929
+ }
1930
+ function findClaudeTranscriptPath(sessionId) {
1931
+ return findJsonlFileByStem(getClaudeProjectsDir(), sessionId);
1932
+ }
1933
+ function findJsonlFileByStem(root, stem) {
1934
+ if (!existsSync2(root)) {
1935
+ return void 0;
1936
+ }
1937
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
1938
+ const path3 = join(root, entry.name);
1939
+ if (entry.isDirectory()) {
1940
+ const nested = findJsonlFileByStem(path3, stem);
1941
+ if (nested) {
1942
+ return nested;
1943
+ }
1944
+ continue;
1945
+ }
1946
+ if (entry.isFile() && entry.name === `${stem}.jsonl`) {
1947
+ return path3;
1948
+ }
1949
+ }
1950
+ return void 0;
1951
+ }
1952
+ function readJsonLines(path3) {
1953
+ try {
1954
+ return readFileSync(path3, "utf-8").split("\n").map((line) => line.trim()).filter(Boolean).map(tryParseJson).filter(Boolean);
1955
+ } catch {
1956
+ return [];
1957
+ }
1958
+ }
1959
+ function tryParseJson(value) {
1960
+ try {
1961
+ return JSON.parse(value);
1962
+ } catch {
1963
+ return null;
1964
+ }
1965
+ }
1966
+ function dedupeSessions(sessions) {
1967
+ const seen = /* @__PURE__ */ new Set();
1968
+ return sessions.filter((session) => {
1969
+ const key = `${session.provider}:${session.localProcessId ?? session.sessionKey}`;
1970
+ if (seen.has(key)) {
1971
+ return false;
1972
+ }
1973
+ seen.add(key);
1974
+ return true;
1975
+ });
1976
+ }
1977
+ function compareObservedSessions(a, b) {
1978
+ return Number(b.localProcessId ?? 0) - Number(a.localProcessId ?? 0);
1979
+ }
1980
+ function parseObservedCodexSession(pid, transcriptPath, processCwd, historyBySession) {
1981
+ const entries = readJsonLines(transcriptPath);
1982
+ let sessionKey;
1983
+ let cwd = processCwd;
1984
+ const userMessages = [];
1985
+ const assistantMessages = [];
1986
+ for (const rawEntry of entries) {
1987
+ const entry = asObject(rawEntry);
1988
+ if (!entry) {
1989
+ continue;
1990
+ }
1991
+ if (entry.type === "session_meta") {
1992
+ const payload = asObject(entry.payload);
1993
+ sessionKey = asString(payload?.id) ?? sessionKey;
1994
+ cwd = asString(payload?.cwd) ?? cwd;
1995
+ }
1996
+ if (entry.type === "event_msg") {
1997
+ const payload = asObject(entry.payload);
1998
+ if (payload?.type === "user_message") {
1999
+ pushIfPresent(userMessages, payload.message);
2000
+ }
2001
+ }
2002
+ if (entry.type === "response_item" && asObject(entry.payload)?.type === "message" && asObject(entry.payload)?.role === "user") {
2003
+ userMessages.push(
2004
+ ...extractTextSegments(asObject(entry.payload)?.content)
2005
+ );
2006
+ }
2007
+ if (entry.type === "event_msg") {
2008
+ const payload = asObject(entry.payload);
2009
+ if (payload?.type === "agent_message") {
2010
+ pushIfPresent(assistantMessages, payload.message);
2011
+ }
2012
+ }
2013
+ if (entry.type === "response_item" && asObject(entry.payload)?.type === "message" && asObject(entry.payload)?.role === "assistant") {
2014
+ assistantMessages.push(
2015
+ ...extractTextSegments(asObject(entry.payload)?.content)
2016
+ );
2017
+ }
2018
+ }
2019
+ if (!sessionKey) {
2020
+ return null;
2021
+ }
2022
+ const gitInfo = cwd ? getGitInfo(cwd) : {};
2023
+ const historyTitle = sessionKey ? selectSessionTitle(historyBySession?.get(sessionKey) ?? []) : void 0;
2024
+ return {
2025
+ provider: "codex",
2026
+ providerLabel: "Codex",
2027
+ localProcessId: pid,
2028
+ sessionKey,
2029
+ cwd,
2030
+ ...gitInfo,
2031
+ title: summarizeTitle(
2032
+ historyTitle ?? selectSessionTitle(userMessages) ?? selectSessionTitle(assistantMessages),
2033
+ cwd
2034
+ ),
2035
+ mode: "observed",
2036
+ status: "observed",
2037
+ supportsInboundMessages: true
2038
+ };
2039
+ }
2040
+ function parseObservedClaudeSession(pid, sessionMeta, transcriptPath, historyBySession) {
2041
+ const entries = transcriptPath ? readJsonLines(transcriptPath) : [];
2042
+ let cwd = sessionMeta.cwd;
2043
+ let branch;
2044
+ let model;
2045
+ const userMessages = [];
2046
+ const assistantMessages = [];
2047
+ for (const rawEntry of entries) {
2048
+ const entry = asObject(rawEntry);
2049
+ if (!entry) {
2050
+ continue;
2051
+ }
2052
+ cwd = asString(entry.cwd) ?? cwd;
2053
+ branch = asString(entry.gitBranch) ?? branch;
2054
+ if (entry.type === "user") {
2055
+ userMessages.push(...extractClaudeMessageTexts(entry.message));
2056
+ }
2057
+ if (entry.type === "assistant") {
2058
+ const message = asObject(entry.message);
2059
+ model = asString(message?.model) ?? model;
2060
+ assistantMessages.push(...extractClaudeMessageTexts(entry.message));
2061
+ }
2062
+ }
2063
+ const gitInfo = cwd ? getGitInfo(cwd) : {};
2064
+ const historyTitle = selectSessionTitle(
2065
+ historyBySession?.get(sessionMeta.sessionId) ?? []
2066
+ );
2067
+ return {
2068
+ provider: "claude_code",
2069
+ providerLabel: "Claude",
2070
+ localProcessId: pid,
2071
+ sessionKey: sessionMeta.sessionId,
2072
+ cwd,
2073
+ repoRoot: gitInfo.repoRoot,
2074
+ branch: branch ?? gitInfo.branch,
2075
+ title: summarizeTitle(
2076
+ historyTitle ?? selectSessionTitle(userMessages) ?? selectSessionTitle(assistantMessages),
2077
+ cwd
2078
+ ),
2079
+ model,
2080
+ mode: "observed",
2081
+ status: "observed",
2082
+ supportsInboundMessages: true
2083
+ };
2084
+ }
2085
+ function summarizeTitle(message, cwd) {
2086
+ if (message) {
2087
+ return truncate(message.replace(/\s+/g, " ").trim(), 96);
2088
+ }
2089
+ if (cwd) {
2090
+ return basename(cwd);
2091
+ }
2092
+ return "Local session";
2093
+ }
2094
+ function buildTmuxPaneTitle(args) {
2095
+ const paneTitle = cleanSessionTitleCandidate(args.paneTitle ?? "");
2096
+ if (paneTitle) {
2097
+ return paneTitle;
2098
+ }
2099
+ const command = asString(args.currentCommand);
2100
+ if (command && !["zsh", "bash", "fish", "sh", "nu"].includes(command)) {
2101
+ return `${command} in ${basename(args.cwd)}`;
2102
+ }
2103
+ return `${basename(args.cwd)} (${args.sessionName}:${args.windowName})`;
2104
+ }
2105
+ function truncate(value, maxLength) {
2106
+ return value.length > maxLength ? `${value.slice(0, maxLength - 3).trimEnd()}...` : value;
2107
+ }
2108
+ function firstObjectKey(value) {
2109
+ if (!value || typeof value !== "object") {
2110
+ return void 0;
2111
+ }
2112
+ const [firstKey] = Object.keys(value);
2113
+ return firstKey ? normalizeModelKey(firstKey) : void 0;
2114
+ }
2115
+ function normalizeModelKey(value) {
2116
+ const normalized = stripAnsi(value).replace(/\[\d+(?:;\d+)*m$/g, "").trim();
2117
+ return normalized || void 0;
2118
+ }
2119
+ function asObject(value) {
2120
+ return value && typeof value === "object" ? value : void 0;
2121
+ }
2122
+ function asString(value) {
2123
+ return typeof value === "string" && value.trim() ? value : void 0;
2124
+ }
2125
+ function pushIfPresent(target, value) {
2126
+ const text2 = asString(value);
2127
+ if (text2) {
2128
+ target.push(text2);
2129
+ }
2130
+ }
2131
+ function extractClaudeMessageTexts(message) {
2132
+ if (!message || typeof message !== "object") {
2133
+ return [];
2134
+ }
2135
+ return extractTextSegments(message.content);
2136
+ }
2137
+ function extractTextSegments(value) {
2138
+ if (typeof value === "string") {
2139
+ return [value];
2140
+ }
2141
+ if (!Array.isArray(value)) {
2142
+ return [];
2143
+ }
2144
+ return value.flatMap(extractTextSegmentFromBlock).filter(Boolean);
2145
+ }
2146
+ function extractTextSegmentFromBlock(block) {
2147
+ if (!block || typeof block !== "object") {
2148
+ return [];
2149
+ }
2150
+ const typedBlock = block;
2151
+ const blockType = asString(typedBlock.type);
2152
+ if (blockType && isIgnoredContentBlockType(blockType)) {
2153
+ return [];
2154
+ }
2155
+ const directText = asString(typedBlock.text);
2156
+ if (directText) {
2157
+ return [directText];
2158
+ }
2159
+ if (typeof typedBlock.content === "string") {
2160
+ return [typedBlock.content];
2161
+ }
2162
+ return [];
2163
+ }
2164
+ function isIgnoredContentBlockType(blockType) {
2165
+ return [
2166
+ "tool_result",
2167
+ "tool_use",
2168
+ "image",
2169
+ "thinking",
2170
+ "reasoning",
2171
+ "contextCompaction"
2172
+ ].includes(blockType);
2173
+ }
2174
+ function buildCodexHistoryIndex() {
2175
+ const historyBySession = /* @__PURE__ */ new Map();
2176
+ for (const rawEntry of readJsonLines(getCodexHistoryFile())) {
2177
+ const entry = asObject(rawEntry);
2178
+ if (!entry) {
2179
+ continue;
2180
+ }
2181
+ const sessionId = asString(entry.session_id);
2182
+ const text2 = asString(entry.text);
2183
+ if (!sessionId || !text2) {
2184
+ continue;
2185
+ }
2186
+ appendHistoryEntry(historyBySession, sessionId, text2);
2187
+ }
2188
+ return historyBySession;
2189
+ }
2190
+ function buildClaudeHistoryIndex() {
2191
+ const historyBySession = /* @__PURE__ */ new Map();
2192
+ for (const rawEntry of readJsonLines(getClaudeHistoryFile())) {
2193
+ const entry = asObject(rawEntry);
2194
+ if (!entry) {
2195
+ continue;
2196
+ }
2197
+ const sessionId = asString(entry.sessionId);
2198
+ if (!sessionId) {
2199
+ continue;
2200
+ }
2201
+ const texts = extractClaudeHistoryTexts(entry);
2202
+ for (const text2 of texts) {
2203
+ appendHistoryEntry(historyBySession, sessionId, text2);
2204
+ }
2205
+ }
2206
+ return historyBySession;
2207
+ }
2208
+ function appendHistoryEntry(historyBySession, sessionId, text2) {
2209
+ const existing = historyBySession.get(sessionId);
2210
+ if (existing) {
2211
+ existing.push(text2);
2212
+ return;
2213
+ }
2214
+ historyBySession.set(sessionId, [text2]);
2215
+ }
2216
+ function extractClaudeHistoryTexts(entry) {
2217
+ if (!entry || typeof entry !== "object") {
2218
+ return [];
2219
+ }
2220
+ const record = entry;
2221
+ const pastedTexts = extractClaudePastedTexts(record.pastedContents);
2222
+ if (pastedTexts.length > 0) {
2223
+ return pastedTexts;
2224
+ }
2225
+ const display = asString(record.display);
2226
+ return display ? [display] : [];
2227
+ }
2228
+ function extractClaudePastedTexts(value) {
2229
+ if (!value || typeof value !== "object") {
2230
+ return [];
2231
+ }
2232
+ return Object.values(value).flatMap((item) => {
2233
+ if (!item || typeof item !== "object") {
2234
+ return [];
2235
+ }
2236
+ const record = item;
2237
+ return record.type === "text" && typeof record.content === "string" ? [record.content] : [];
2238
+ }).filter(Boolean);
2239
+ }
2240
+ function selectSessionTitle(messages) {
2241
+ for (const message of messages) {
2242
+ const cleaned = cleanSessionTitleCandidate(message);
2243
+ if (cleaned) {
2244
+ return cleaned;
2245
+ }
2246
+ }
2247
+ return void 0;
2248
+ }
2249
+ function cleanSessionTitleCandidate(message) {
2250
+ const normalized = stripAnsi(message).replace(/\s+/g, " ").trim();
2251
+ if (!normalized) {
2252
+ return void 0;
2253
+ }
2254
+ if (normalized.length < 4) {
2255
+ return void 0;
2256
+ }
2257
+ if (normalized.startsWith("/") || looksLikeGeneratedTagEnvelope(normalized) || looksLikeGeneratedImageSummary(normalized) || looksLikeStandaloneImagePath(normalized) || looksLikeInstructionScaffold(normalized)) {
2258
+ return void 0;
2259
+ }
2260
+ return normalized;
2261
+ }
2262
+ function looksLikeGeneratedTagEnvelope(value) {
2263
+ return /^<[\w:-]+>[\s\S]*<\/[\w:-]+>$/.test(value);
2264
+ }
2265
+ function looksLikeGeneratedImageSummary(value) {
2266
+ return /^\[image:/i.test(value) || /displayed at/i.test(value) && /coordinates/i.test(value);
2267
+ }
2268
+ function looksLikeStandaloneImagePath(value) {
2269
+ return /^\/\S+\.(png|jpe?g|gif|webp|heic|bmp)$/i.test(value) || /^file:\S+\.(png|jpe?g|gif|webp|heic|bmp)$/i.test(value);
2270
+ }
2271
+ function looksLikeInstructionScaffold(value) {
2272
+ if (value.length < 700) {
2273
+ return false;
2274
+ }
2275
+ const headingCount = value.match(/^#{1,3}\s/gm)?.length ?? 0;
2276
+ const tagCount = value.match(/<\/?[\w:-]+>/g)?.length ?? 0;
2277
+ const bulletCount = value.match(/^\s*[-*]\s/gm)?.length ?? 0;
2278
+ return headingCount + tagCount + bulletCount >= 6;
2279
+ }
2280
+ function stripAnsi(value) {
2281
+ return value.replace(/\u001B\[[0-9;]*m/g, "");
2282
+ }
2283
+ function getGitInfo(cwd) {
2284
+ try {
2285
+ const repoRoot = execSync("git rev-parse --show-toplevel", {
2286
+ encoding: "utf-8",
2287
+ cwd,
2288
+ timeout: 3e3
2289
+ }).trim();
2290
+ const branch = execSync("git rev-parse --abbrev-ref HEAD", {
2291
+ encoding: "utf-8",
2292
+ cwd,
2293
+ timeout: 3e3
2294
+ }).trim();
2295
+ return {
2296
+ repoRoot: repoRoot || void 0,
2297
+ branch: branch || void 0
2298
+ };
2299
+ } catch {
2300
+ return {};
2301
+ }
2302
+ }
2303
+
2304
+ // src/bridge-service.ts
2305
+ var CONFIG_DIR = process.env.VECTOR_HOME?.trim() || join2(homedir3(), ".vector");
2306
+ var BRIDGE_CONFIG_FILE = join2(CONFIG_DIR, "bridge.json");
2307
+ var DEVICE_KEY_FILE = join2(CONFIG_DIR, "device-key");
2308
+ var PID_FILE = join2(CONFIG_DIR, "bridge.pid");
2309
+ var LIVE_ACTIVITIES_CACHE = join2(CONFIG_DIR, "live-activities.json");
2310
+ var LAUNCHAGENT_DIR = join2(homedir3(), "Library", "LaunchAgents");
2311
+ var LAUNCHAGENT_PLIST = join2(LAUNCHAGENT_DIR, "com.vector.bridge.plist");
2312
+ var LAUNCHAGENT_LABEL = "com.vector.bridge";
2313
+ var LEGACY_MENUBAR_LAUNCHAGENT_LABEL = "com.vector.menubar";
2314
+ var LEGACY_MENUBAR_LAUNCHAGENT_PLIST = join2(
2315
+ LAUNCHAGENT_DIR,
2316
+ `${LEGACY_MENUBAR_LAUNCHAGENT_LABEL}.plist`
2317
+ );
2318
+ var HEARTBEAT_INTERVAL_MS = 3e4;
2319
+ var COMMAND_POLL_INTERVAL_MS = 5e3;
2320
+ var LIVE_ACTIVITY_SYNC_INTERVAL_MS = 5e3;
2321
+ var PROCESS_DISCOVERY_INTERVAL_MS = 6e4;
2322
+ function loadBridgeConfig() {
2323
+ if (!existsSync3(BRIDGE_CONFIG_FILE)) return null;
2324
+ try {
2325
+ return JSON.parse(readFileSync2(BRIDGE_CONFIG_FILE, "utf-8"));
2326
+ } catch {
2327
+ return null;
2328
+ }
2329
+ }
2330
+ function saveBridgeConfig(config) {
2331
+ if (!existsSync3(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
2332
+ writeFileSync(BRIDGE_CONFIG_FILE, JSON.stringify(config, null, 2));
2333
+ persistDeviceKey(config.deviceKey);
2334
+ }
2335
+ function writeLiveActivitiesCache(activities) {
2336
+ if (!existsSync3(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
2337
+ writeFileSync(LIVE_ACTIVITIES_CACHE, JSON.stringify(activities, null, 2));
2338
+ }
2339
+ var BridgeService = class {
2340
+ constructor(config) {
2341
+ this.timers = [];
2342
+ this.terminalPeer = null;
2343
+ this.config = config;
2344
+ this.client = new ConvexHttpClient2(config.convexUrl);
2345
+ }
2346
+ async heartbeat() {
2347
+ await this.client.mutation(api.agentBridge.bridgePublic.heartbeat, {
2348
+ deviceId: this.config.deviceId,
2349
+ deviceSecret: this.config.deviceSecret
2350
+ });
2351
+ }
2352
+ async pollCommands() {
2353
+ const commands = await this.client.query(
2354
+ api.agentBridge.bridgePublic.getPendingCommands,
2355
+ {
2356
+ deviceId: this.config.deviceId,
2357
+ deviceSecret: this.config.deviceSecret
2358
+ }
2359
+ );
2360
+ if (commands.length > 0) {
2361
+ console.log(`[${ts2()}] ${commands.length} pending command(s)`);
2362
+ }
2363
+ for (const cmd of commands) {
2364
+ await this.handleCommand(cmd);
2365
+ }
2366
+ }
2367
+ async handleCommand(cmd) {
2368
+ const claimed = await this.client.mutation(
2369
+ api.agentBridge.bridgePublic.claimCommand,
2370
+ {
2371
+ deviceId: this.config.deviceId,
2372
+ deviceSecret: this.config.deviceSecret,
2373
+ commandId: cmd._id
2374
+ }
2375
+ );
2376
+ if (!claimed) {
2377
+ return;
2378
+ }
2379
+ console.log(` ${cmd.kind}: ${cmd._id}`);
2380
+ try {
2381
+ switch (cmd.kind) {
2382
+ case "message":
2383
+ await this.handleMessageCommand(cmd);
2384
+ await this.completeCommand(cmd._id, "delivered");
2385
+ return;
2386
+ case "launch":
2387
+ await this.handleLaunchCommand(cmd);
2388
+ await this.completeCommand(cmd._id, "delivered");
2389
+ return;
2390
+ case "resize":
2391
+ await this.handleResizeCommand(cmd);
2392
+ await this.completeCommand(cmd._id, "delivered");
2393
+ return;
2394
+ default:
2395
+ throw new Error(`Unsupported bridge command: ${cmd.kind}`);
2396
+ }
2397
+ } catch (error) {
2398
+ const message = error instanceof Error ? error.message : "Unknown bridge error";
2399
+ console.error(` ! ${message}`);
2400
+ await this.postCommandError(cmd, message);
2401
+ await this.completeCommand(cmd._id, "failed");
2402
+ }
2403
+ }
2404
+ async reportProcesses() {
2405
+ const processes = discoverAttachableSessions();
2406
+ const activeSessionKeys = processes.map((proc) => proc.sessionKey).filter((value) => Boolean(value));
2407
+ const activeLocalProcessIds = processes.map((proc) => proc.localProcessId).filter((value) => Boolean(value));
2408
+ for (const proc of processes) {
2409
+ try {
2410
+ await this.reportProcess(proc);
2411
+ } catch {
2412
+ }
2413
+ }
2414
+ try {
2415
+ await this.client.mutation(
2416
+ api.agentBridge.bridgePublic.reconcileObservedProcesses,
2417
+ {
2418
+ deviceId: this.config.deviceId,
2419
+ deviceSecret: this.config.deviceSecret,
2420
+ activeSessionKeys,
2421
+ activeLocalProcessIds
2422
+ }
2423
+ );
2424
+ } catch {
2425
+ }
2426
+ if (processes.length > 0) {
2427
+ console.log(
2428
+ `[${ts2()}] Discovered ${processes.length} attachable session(s)`
2429
+ );
2430
+ }
2431
+ }
2432
+ async refreshLiveActivities() {
2433
+ try {
2434
+ const activities = await this.client.query(
2435
+ api.agentBridge.bridgePublic.getDeviceLiveActivities,
2436
+ {
2437
+ deviceId: this.config.deviceId,
2438
+ deviceSecret: this.config.deviceSecret
2439
+ }
2440
+ );
2441
+ writeLiveActivitiesCache(activities);
2442
+ if (this.terminalPeer) {
2443
+ for (const activity of activities) {
2444
+ if (activity.workSessionId && activity.tmuxSessionName) {
2445
+ this.terminalPeer.watchSession(
2446
+ activity.workSessionId,
2447
+ activity.tmuxSessionName,
2448
+ activity.tmuxPaneId
2449
+ );
2450
+ }
2451
+ }
2452
+ }
2453
+ } catch {
2454
+ }
2455
+ }
2456
+ async syncWorkSessionTerminals(activities) {
2457
+ for (const activity of activities) {
2458
+ if (!activity.workSessionId || !activity.tmuxPaneId) {
2459
+ continue;
2460
+ }
2461
+ try {
2462
+ await this.refreshWorkSessionTerminal(activity.workSessionId, {
2463
+ tmuxPaneId: activity.tmuxPaneId,
2464
+ cwd: activity.cwd,
2465
+ repoRoot: activity.repoRoot,
2466
+ branch: activity.branch,
2467
+ agentProvider: activity.agentProvider,
2468
+ agentSessionKey: activity.agentSessionKey
2469
+ });
2470
+ await this.verifyManagedWorkSession(activity);
2471
+ } catch {
2472
+ }
2473
+ }
2474
+ }
2475
+ async verifyManagedWorkSession(activity) {
2476
+ if (!activity.workSessionId || !activity.tmuxPaneId || !activity.agentProvider || !isBridgeProvider(activity.agentProvider) || activity.agentProcessId) {
2477
+ return;
2478
+ }
2479
+ const workspacePath = activity.workspacePath ?? activity.cwd ?? activity.repoRoot;
2480
+ if (!workspacePath) {
2481
+ return;
2482
+ }
2483
+ const attachedSession = await this.attachObservedAgentSession(
2484
+ activity.agentProvider,
2485
+ workspacePath
2486
+ );
2487
+ if (!attachedSession) {
2488
+ return;
2489
+ }
2490
+ await this.refreshWorkSessionTerminal(activity.workSessionId, {
2491
+ tmuxPaneId: activity.tmuxPaneId,
2492
+ cwd: attachedSession.process.cwd ?? activity.cwd ?? workspacePath,
2493
+ repoRoot: attachedSession.process.repoRoot ?? activity.repoRoot ?? workspacePath,
2494
+ branch: attachedSession.process.branch ?? activity.branch,
2495
+ agentProvider: attachedSession.process.provider,
2496
+ agentSessionKey: attachedSession.process.sessionKey
2497
+ });
2498
+ await this.postAgentMessage(
2499
+ activity._id,
2500
+ "status",
2501
+ `Verified ${providerLabel(attachedSession.process.provider)} in ${activity.tmuxPaneId}`
2502
+ );
2503
+ await this.updateLiveActivity(activity._id, {
2504
+ status: "active",
2505
+ latestSummary: `Verified ${providerLabel(attachedSession.process.provider)} in ${activity.tmuxPaneId}`,
2506
+ processId: attachedSession.processId,
2507
+ title: activity.title
2508
+ });
2509
+ }
2510
+ async refreshWorkSessionTerminal(workSessionId, metadata) {
2511
+ if (!workSessionId || !metadata.tmuxPaneId) {
2512
+ return;
2513
+ }
2514
+ const terminalSnapshot = captureTmuxPane(metadata.tmuxPaneId);
2515
+ await this.client.mutation(
2516
+ api.agentBridge.bridgePublic.updateWorkSessionTerminal,
2517
+ {
2518
+ deviceId: this.config.deviceId,
2519
+ deviceSecret: this.config.deviceSecret,
2520
+ workSessionId,
2521
+ terminalSnapshot,
2522
+ tmuxSessionName: metadata.tmuxSessionName,
2523
+ tmuxWindowName: metadata.tmuxWindowName,
2524
+ tmuxPaneId: metadata.tmuxPaneId,
2525
+ cwd: metadata.cwd,
2526
+ repoRoot: metadata.repoRoot,
2527
+ branch: metadata.branch,
2528
+ agentProvider: metadata.agentProvider,
2529
+ agentSessionKey: metadata.agentSessionKey
2530
+ }
2531
+ );
2532
+ }
2533
+ async run() {
2534
+ console.log("Vector Bridge Service");
2535
+ console.log(
2536
+ ` Device: ${this.config.displayName} (${this.config.deviceId})`
2537
+ );
2538
+ console.log(` Convex: ${this.config.convexUrl}`);
2539
+ console.log(` PID: ${process.pid}`);
2540
+ console.log("");
2541
+ if (!existsSync3(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
2542
+ writeFileSync(PID_FILE, String(process.pid));
2543
+ try {
2544
+ this.terminalPeer = new TerminalPeerManager({
2545
+ deviceId: this.config.deviceId,
2546
+ deviceSecret: this.config.deviceSecret,
2547
+ convexUrl: this.config.convexUrl,
2548
+ tunnelHost: this.config.tunnelHost
2549
+ });
2550
+ console.log(
2551
+ ` Terminal: ready${this.config.tunnelHost ? ` (tunnel: ${this.config.tunnelHost})` : ""}`
2552
+ );
2553
+ } catch (e) {
2554
+ console.error(
2555
+ ` WebRTC: failed (${e instanceof Error ? e.message : "unknown"})`
2556
+ );
2557
+ }
2558
+ console.log("");
2559
+ await this.heartbeat();
2560
+ await this.reportProcesses();
2561
+ await this.refreshLiveActivities();
2562
+ console.log(`[${ts2()}] Service running. Ctrl+C to stop.
2563
+ `);
2564
+ this.timers.push(
2565
+ setInterval(() => {
2566
+ this.heartbeat().catch(
2567
+ (e) => console.error(`[${ts2()}] Heartbeat error:`, e.message)
2568
+ );
2569
+ }, HEARTBEAT_INTERVAL_MS)
2570
+ );
2571
+ this.timers.push(
2572
+ setInterval(() => {
2573
+ this.pollCommands().catch(
2574
+ (e) => console.error(`[${ts2()}] Command poll error:`, e.message)
2575
+ );
2576
+ }, COMMAND_POLL_INTERVAL_MS)
2577
+ );
2578
+ this.timers.push(
2579
+ setInterval(() => {
2580
+ this.refreshLiveActivities().catch(
2581
+ (e) => console.error(`[${ts2()}] Live activity sync error:`, e.message)
2582
+ );
2583
+ }, LIVE_ACTIVITY_SYNC_INTERVAL_MS)
2584
+ );
2585
+ this.timers.push(
2586
+ setInterval(() => {
2587
+ this.reportProcesses().catch(
2588
+ (e) => console.error(`[${ts2()}] Discovery error:`, e.message)
2589
+ );
2590
+ }, PROCESS_DISCOVERY_INTERVAL_MS)
2591
+ );
2592
+ const shutdown = () => {
2593
+ console.log(`
2594
+ [${ts2()}] Shutting down...`);
2595
+ for (const t of this.timers) clearInterval(t);
2596
+ this.terminalPeer?.stop();
2597
+ try {
2598
+ unlinkSync(PID_FILE);
2599
+ } catch {
2600
+ }
2601
+ try {
2602
+ writeLiveActivitiesCache([]);
2603
+ } catch {
2604
+ }
2605
+ process.exit(0);
2606
+ };
2607
+ process.on("SIGINT", shutdown);
2608
+ process.on("SIGTERM", shutdown);
2609
+ await new Promise(() => {
2610
+ });
2611
+ }
2612
+ async handleMessageCommand(cmd) {
2613
+ if (!cmd.liveActivityId) {
2614
+ throw new Error("Message command is missing liveActivityId");
2615
+ }
2616
+ const payload = cmd.payload;
2617
+ const body = payload?.body?.trim();
2618
+ if (!body) {
2619
+ throw new Error("Message command is missing a body");
2620
+ }
2621
+ const process9 = cmd.process;
2622
+ console.log(` > "${truncateForLog(body)}"`);
2623
+ if (cmd.workSession?.tmuxPaneId) {
2624
+ sendTextToTmuxPane(cmd.workSession.tmuxPaneId, body);
2625
+ const attachedSession = cmd.workSession.agentProvider && isBridgeProvider(cmd.workSession.agentProvider) ? await this.attachObservedAgentSession(
2626
+ cmd.workSession.agentProvider,
2627
+ cmd.workSession.workspacePath ?? cmd.workSession.cwd ?? process9?.cwd
2628
+ ) : null;
2629
+ await this.postAgentMessage(
2630
+ cmd.liveActivityId,
2631
+ "status",
2632
+ "Sent input to work session terminal"
2633
+ );
2634
+ await this.refreshWorkSessionTerminal(cmd.workSession._id, {
2635
+ tmuxSessionName: cmd.workSession.tmuxSessionName,
2636
+ tmuxWindowName: cmd.workSession.tmuxWindowName,
2637
+ tmuxPaneId: cmd.workSession.tmuxPaneId,
2638
+ cwd: cmd.workSession.cwd,
2639
+ repoRoot: cmd.workSession.repoRoot,
2640
+ branch: cmd.workSession.branch,
2641
+ agentProvider: attachedSession?.process.provider ?? cmd.workSession.agentProvider,
2642
+ agentSessionKey: attachedSession?.process.sessionKey ?? cmd.workSession.agentSessionKey
2643
+ });
2644
+ await this.updateLiveActivity(cmd.liveActivityId, {
2645
+ status: "waiting_for_input",
2646
+ latestSummary: `Input sent to ${cmd.workSession.tmuxPaneId}`,
2647
+ title: cmd.liveActivity?.title,
2648
+ processId: attachedSession?.processId ?? process9?._id
2649
+ });
2650
+ return;
2651
+ }
2652
+ if (!process9 || !process9.supportsInboundMessages || !process9.sessionKey || !process9.cwd || !isBridgeProvider(process9.provider)) {
2653
+ throw new Error("No resumable local session is attached to this issue");
2654
+ }
2655
+ await this.reportProcess({
2656
+ provider: process9.provider,
2657
+ providerLabel: process9.providerLabel ?? providerLabel(process9.provider),
2658
+ sessionKey: process9.sessionKey,
2659
+ cwd: process9.cwd,
2660
+ repoRoot: process9.repoRoot,
2661
+ branch: process9.branch,
2662
+ title: process9.title,
2663
+ model: process9.model,
2664
+ mode: "managed",
2665
+ status: "waiting",
2666
+ supportsInboundMessages: true
2667
+ });
2668
+ await this.updateLiveActivity(cmd.liveActivityId, {
2669
+ status: "active",
2670
+ processId: process9._id,
2671
+ title: cmd.liveActivity?.title ?? process9.title
2672
+ });
2673
+ const result = await resumeProviderSession(
2674
+ process9.provider,
2675
+ process9.sessionKey,
2676
+ process9.cwd,
2677
+ body
2678
+ );
2679
+ const processId = await this.reportProcess(result);
2680
+ if (result.responseText) {
2681
+ await this.postAgentMessage(
2682
+ cmd.liveActivityId,
2683
+ "assistant",
2684
+ result.responseText
2685
+ );
2686
+ console.log(` < "${truncateForLog(result.responseText)}"`);
2687
+ }
2688
+ await this.updateLiveActivity(cmd.liveActivityId, {
2689
+ processId,
2690
+ status: "waiting_for_input",
2691
+ latestSummary: summarizeMessage(result.responseText),
2692
+ title: cmd.liveActivity?.title ?? process9.title
2693
+ });
2694
+ }
2695
+ async handleResizeCommand(cmd) {
2696
+ const payload = cmd.payload;
2697
+ const cols = payload?.cols;
2698
+ const rows = payload?.rows;
2699
+ const paneId = cmd.workSession?.tmuxPaneId;
2700
+ if (!paneId || !cols || !rows) {
2701
+ throw new Error("Resize command missing paneId, cols, or rows");
2702
+ }
2703
+ console.log(` Resize ${paneId} \u2192 ${cols}x${rows}`);
2704
+ resizeTmuxPane(paneId, cols, rows);
2705
+ if (cmd.workSession) {
2706
+ await this.refreshWorkSessionTerminal(cmd.workSession._id, {
2707
+ tmuxSessionName: cmd.workSession.tmuxSessionName,
2708
+ tmuxWindowName: cmd.workSession.tmuxWindowName,
2709
+ tmuxPaneId: paneId,
2710
+ cwd: cmd.workSession.cwd,
2711
+ repoRoot: cmd.workSession.repoRoot,
2712
+ branch: cmd.workSession.branch,
2713
+ agentProvider: cmd.workSession.agentProvider,
2714
+ agentSessionKey: cmd.workSession.agentSessionKey
2715
+ });
2716
+ }
2717
+ }
2718
+ async handleLaunchCommand(cmd) {
2719
+ if (!cmd.liveActivityId) {
2720
+ throw new Error("Launch command is missing liveActivityId");
2721
+ }
2722
+ const payload = cmd.payload;
2723
+ const workspacePath = payload?.workspacePath?.trim();
2724
+ if (!workspacePath) {
2725
+ throw new Error("Launch command is missing workspacePath");
2726
+ }
2727
+ const requestedProvider = payload?.provider;
2728
+ const provider = requestedProvider && isBridgeProvider(requestedProvider) ? requestedProvider : void 0;
2729
+ const issueKey = payload?.issueKey ?? cmd.liveActivity?.issueKey ?? "ISSUE";
2730
+ const issueTitle = payload?.issueTitle ?? cmd.liveActivity?.issueTitle ?? "Untitled issue";
2731
+ const issueDescription = payload?.issueDescription;
2732
+ const prompt2 = buildLaunchPrompt(
2733
+ issueKey,
2734
+ issueTitle,
2735
+ workspacePath,
2736
+ issueDescription
2737
+ );
2738
+ const launchLabel = provider ? providerLabel(provider) : "shell session";
2739
+ const workSessionTitle = `${issueKey}: ${issueTitle}`;
2740
+ await this.updateLiveActivity(cmd.liveActivityId, {
2741
+ status: "active",
2742
+ latestSummary: `Launching ${launchLabel} in ${workspacePath}`,
2743
+ delegatedRunId: payload?.delegatedRunId,
2744
+ launchStatus: "launching",
2745
+ title: workSessionTitle
2746
+ });
2747
+ const tmuxSession = createTmuxWorkSession({
2748
+ workspacePath,
2749
+ issueKey,
2750
+ issueTitle,
2751
+ provider,
2752
+ prompt: prompt2
2753
+ });
2754
+ await this.refreshWorkSessionTerminal(cmd.workSession?._id, {
2755
+ tmuxSessionName: tmuxSession.sessionName,
2756
+ tmuxWindowName: tmuxSession.windowName,
2757
+ tmuxPaneId: tmuxSession.paneId,
2758
+ cwd: workspacePath,
2759
+ repoRoot: workspacePath,
2760
+ branch: currentGitBranch(workspacePath),
2761
+ agentProvider: provider
2762
+ });
2763
+ await this.updateLiveActivity(cmd.liveActivityId, {
2764
+ status: "active",
2765
+ latestSummary: `Running ${launchLabel} in ${tmuxSession.sessionName}`,
2766
+ delegatedRunId: payload?.delegatedRunId,
2767
+ launchStatus: "running",
2768
+ title: workSessionTitle
2769
+ });
2770
+ }
2771
+ async attachObservedAgentSession(provider, workspacePath, sessionsBeforeLaunch = [], paneProcessId) {
2772
+ if (!workspacePath) {
2773
+ return null;
2774
+ }
2775
+ const existingKeys = new Set(
2776
+ sessionsBeforeLaunch.map(sessionIdentityKey).filter(Boolean)
2777
+ );
2778
+ for (let attempt = 0; attempt < 10; attempt += 1) {
2779
+ const observedSessions = listObservedSessionsForWorkspace(
2780
+ provider,
2781
+ workspacePath
2782
+ );
2783
+ const candidate = (paneProcessId ? findObservedSessionInProcessTree(observedSessions, paneProcessId) : void 0) ?? observedSessions.find(
2784
+ (session) => !existingKeys.has(sessionIdentityKey(session))
2785
+ ) ?? (attempt === 9 ? observedSessions[0] : void 0);
2786
+ if (candidate) {
2787
+ const processId = await this.reportProcess(candidate);
2788
+ return {
2789
+ process: candidate,
2790
+ processId
2791
+ };
2792
+ }
2793
+ await sleep(750);
2794
+ }
2795
+ return null;
2796
+ }
2797
+ async reportProcess(process9) {
2798
+ const {
2799
+ provider,
2800
+ providerLabel: providerLabel2,
2801
+ localProcessId,
2802
+ sessionKey,
2803
+ cwd,
2804
+ repoRoot,
2805
+ branch,
2806
+ title,
2807
+ model,
2808
+ tmuxSessionName,
2809
+ tmuxWindowName,
2810
+ tmuxPaneId,
2811
+ mode,
2812
+ status,
2813
+ supportsInboundMessages
2814
+ } = process9;
2815
+ return await this.client.mutation(
2816
+ api.agentBridge.bridgePublic.reportProcess,
2817
+ {
2818
+ deviceId: this.config.deviceId,
2819
+ deviceSecret: this.config.deviceSecret,
2820
+ provider,
2821
+ providerLabel: providerLabel2,
2822
+ localProcessId,
2823
+ sessionKey,
2824
+ cwd,
2825
+ repoRoot,
2826
+ branch,
2827
+ title,
2828
+ model,
2829
+ tmuxSessionName,
2830
+ tmuxWindowName,
2831
+ tmuxPaneId,
2832
+ mode,
2833
+ status,
2834
+ supportsInboundMessages
2835
+ }
2836
+ );
2837
+ }
2838
+ async updateLiveActivity(liveActivityId, args) {
2839
+ await this.client.mutation(
2840
+ api.agentBridge.bridgePublic.updateLiveActivityState,
2841
+ {
2842
+ deviceId: this.config.deviceId,
2843
+ deviceSecret: this.config.deviceSecret,
2844
+ liveActivityId,
2845
+ ...args
2846
+ }
2847
+ );
2848
+ }
2849
+ async postAgentMessage(liveActivityId, role, body) {
2850
+ await this.client.mutation(api.agentBridge.bridgePublic.postAgentMessage, {
2851
+ deviceId: this.config.deviceId,
2852
+ deviceSecret: this.config.deviceSecret,
2853
+ liveActivityId,
2854
+ role,
2855
+ body
2856
+ });
2857
+ }
2858
+ async completeCommand(commandId, status) {
2859
+ await this.client.mutation(api.agentBridge.bridgePublic.completeCommand, {
2860
+ deviceId: this.config.deviceId,
2861
+ deviceSecret: this.config.deviceSecret,
2862
+ commandId,
2863
+ status
2864
+ });
2865
+ }
2866
+ async postCommandError(cmd, errorMessage) {
2867
+ if (cmd.kind === "launch" && cmd.liveActivityId) {
2868
+ const payload = cmd.payload;
2869
+ await this.updateLiveActivity(cmd.liveActivityId, {
2870
+ status: "failed",
2871
+ latestSummary: errorMessage,
2872
+ delegatedRunId: payload?.delegatedRunId,
2873
+ launchStatus: "failed"
2874
+ });
2875
+ await this.postAgentMessage(cmd.liveActivityId, "status", errorMessage);
2876
+ return;
2877
+ }
2878
+ if (cmd.kind === "message" && cmd.liveActivityId) {
2879
+ await this.postAgentMessage(cmd.liveActivityId, "status", errorMessage);
2880
+ await this.updateLiveActivity(cmd.liveActivityId, {
2881
+ status: "waiting_for_input",
2882
+ latestSummary: errorMessage
2883
+ });
2884
+ }
2885
+ }
2886
+ };
2887
+ function createTmuxWorkSession(args) {
2888
+ const slug = sanitizeTmuxName(args.issueKey.toLowerCase());
2889
+ const sessionName = `vector-${slug}-${randomUUID2().slice(0, 8)}`;
2890
+ const windowName = sanitizeTmuxName(
2891
+ args.provider === "codex" ? "codex" : args.provider === "claude_code" ? "claude" : "shell"
2892
+ );
2893
+ execFileSync2("tmux", [
2894
+ "new-session",
2895
+ "-d",
2896
+ "-s",
2897
+ sessionName,
2898
+ "-n",
2899
+ windowName,
2900
+ "-c",
2901
+ args.workspacePath
2902
+ ]);
2903
+ const paneId = execFileSync2(
2904
+ "tmux",
2905
+ [
2906
+ "display-message",
2907
+ "-p",
2908
+ "-t",
2909
+ `${sessionName}:${windowName}.0`,
2910
+ "#{pane_id}"
2911
+ ],
2912
+ { encoding: "utf-8" }
2913
+ ).trim();
2914
+ const paneProcessId = execFileSync2(
2915
+ "tmux",
2916
+ ["display-message", "-p", "-t", paneId, "#{pane_pid}"],
2917
+ { encoding: "utf-8" }
2918
+ ).trim();
2919
+ if (args.provider) {
2920
+ execFileSync2("tmux", [
2921
+ "send-keys",
2922
+ "-t",
2923
+ paneId,
2924
+ buildManagedLaunchCommand(args.provider, args.prompt),
2925
+ "Enter"
2926
+ ]);
2927
+ } else {
2928
+ execFileSync2("tmux", [
2929
+ "send-keys",
2930
+ "-t",
2931
+ paneId,
2932
+ `printf '%s\\n\\n' ${shellQuote(args.prompt)}`,
2933
+ "Enter"
2934
+ ]);
2935
+ }
2936
+ return {
2937
+ sessionName,
2938
+ windowName,
2939
+ paneId,
2940
+ paneProcessId
2941
+ };
2942
+ }
2943
+ function sendTextToTmuxPane(paneId, text2) {
2944
+ execFileSync2("tmux", ["set-buffer", "--", text2]);
2945
+ execFileSync2("tmux", ["paste-buffer", "-t", paneId]);
2946
+ execFileSync2("tmux", ["send-keys", "-t", paneId, "Enter"]);
2947
+ execFileSync2("tmux", ["delete-buffer"]);
2948
+ }
2949
+ function captureTmuxPane(paneId) {
2950
+ return execFileSync2(
2951
+ "tmux",
2952
+ ["capture-pane", "-p", "-e", "-t", paneId, "-S", "-120"],
2953
+ { encoding: "utf-8" }
2954
+ ).trimEnd();
2955
+ }
2956
+ function resizeTmuxPane(paneId, cols, rows) {
2957
+ try {
2958
+ execFileSync2("tmux", [
2959
+ "resize-pane",
2960
+ "-t",
2961
+ paneId,
2962
+ "-x",
2963
+ String(cols),
2964
+ "-y",
2965
+ String(rows)
2966
+ ]);
2967
+ } catch (e) {
2968
+ console.error(`Failed to resize pane ${paneId}:`, e);
2969
+ }
2970
+ }
2971
+ function currentGitBranch(cwd) {
2972
+ try {
2973
+ return execSync2("git rev-parse --abbrev-ref HEAD", {
2974
+ encoding: "utf-8",
2975
+ cwd,
2976
+ timeout: 3e3
2977
+ }).trim();
2978
+ } catch {
2979
+ return void 0;
2980
+ }
2981
+ }
2982
+ function buildManagedLaunchCommand(provider, prompt2) {
2983
+ if (provider === "codex") {
2984
+ return `codex --no-alt-screen -a never ${shellQuote(prompt2)}`;
2985
+ }
2986
+ return `claude --permission-mode bypassPermissions --dangerously-skip-permissions ${shellQuote(prompt2)}`;
2987
+ }
2988
+ function sanitizeTmuxName(value) {
2989
+ return value.replace(/[^a-z0-9_-]+/gi, "-").replace(/^-+|-+$/g, "") || "work";
2990
+ }
2991
+ function shellQuote(value) {
2992
+ return `'${value.replace(/'/g, `'"'"'`)}'`;
2993
+ }
2994
+ async function setupBridgeDevice(client, convexUrl) {
2995
+ const deviceKey = getStableDeviceKey();
2996
+ const displayName = `${process.env.USER ?? "user"}'s ${platform() === "darwin" ? "Mac" : "machine"}`;
2997
+ const result = await client.mutation(
2998
+ api.agentBridge.mutations.registerBridgeDevice,
2999
+ {
3000
+ deviceKey,
3001
+ displayName,
3002
+ hostname: hostname(),
3003
+ platform: platform(),
3004
+ serviceType: "foreground",
3005
+ cliVersion: "0.1.0",
3006
+ capabilities: ["codex", "claude_code"]
3007
+ }
3008
+ );
3009
+ const config = {
3010
+ deviceId: result.deviceId,
3011
+ deviceKey,
3012
+ deviceSecret: result.deviceSecret,
3013
+ userId: result.userId,
3014
+ displayName,
3015
+ convexUrl,
3016
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
3017
+ };
3018
+ saveBridgeConfig(config);
3019
+ return config;
3020
+ }
3021
+ function getStableDeviceKey() {
3022
+ const existingConfig = loadBridgeConfig();
3023
+ const existingKey = existingConfig?.deviceKey?.trim();
3024
+ if (existingKey) {
3025
+ persistDeviceKey(existingKey);
3026
+ return existingKey;
3027
+ }
3028
+ if (existsSync3(DEVICE_KEY_FILE)) {
3029
+ const savedKey = readFileSync2(DEVICE_KEY_FILE, "utf-8").trim();
3030
+ if (savedKey) {
3031
+ return savedKey;
3032
+ }
3033
+ }
3034
+ const generatedKey = `${hostname()}-${randomUUID2().slice(0, 8)}`;
3035
+ persistDeviceKey(generatedKey);
3036
+ return generatedKey;
3037
+ }
3038
+ function persistDeviceKey(deviceKey) {
3039
+ if (!existsSync3(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
3040
+ writeFileSync(DEVICE_KEY_FILE, `${deviceKey}
3041
+ `);
3042
+ }
3043
+ function buildLaunchPrompt(issueKey, issueTitle, workspacePath, issueDescription) {
3044
+ const lines = [`You are working on issue ${issueKey}: ${issueTitle}`];
3045
+ if (issueDescription?.trim()) {
3046
+ lines.push("", "Issue description:", issueDescription.trim());
3047
+ }
3048
+ lines.push(
3049
+ "",
3050
+ `The repository is at ${workspacePath}.`,
3051
+ "Do exactly and only what the issue describes \u2014 nothing more, nothing less.",
3052
+ "If anything is unclear or ambiguous, ask clarifying questions before making changes.",
3053
+ 'Do not refactor, clean up, or "improve" code that is not part of the issue scope.'
3054
+ );
3055
+ return lines.join("\n");
3056
+ }
3057
+ function summarizeMessage(message) {
3058
+ if (!message) {
3059
+ return void 0;
3060
+ }
3061
+ return message.length > 120 ? `${message.slice(0, 117).trimEnd()}...` : message;
3062
+ }
3063
+ function truncateForLog(message) {
3064
+ return message.length > 80 ? `${message.slice(0, 77).trimEnd()}...` : message;
3065
+ }
3066
+ function listObservedSessionsForWorkspace(provider, workspacePath) {
3067
+ return discoverAttachableSessions().filter(
3068
+ (session) => session.provider === provider && matchesWorkspacePath(session, workspacePath)
3069
+ ).sort(compareLocalSessionRecency);
3070
+ }
3071
+ function findObservedSessionInProcessTree(sessions, paneProcessId) {
3072
+ const descendantIds = listDescendantProcessIds(paneProcessId);
3073
+ if (descendantIds.size === 0) {
3074
+ return void 0;
3075
+ }
3076
+ return sessions.find(
3077
+ (session) => session.localProcessId ? descendantIds.has(session.localProcessId) : false
3078
+ );
3079
+ }
3080
+ function listDescendantProcessIds(rootPid) {
3081
+ const descendants = /* @__PURE__ */ new Set([rootPid]);
3082
+ try {
3083
+ const output = execSync2("ps -axo pid=,ppid=", {
3084
+ encoding: "utf-8",
3085
+ timeout: 3e3
3086
+ });
3087
+ const parentToChildren = /* @__PURE__ */ new Map();
3088
+ for (const line of output.split("\n").map((value) => value.trim()).filter(Boolean)) {
3089
+ const [pid, ppid] = line.split(/\s+/, 2);
3090
+ if (!pid || !ppid) {
3091
+ continue;
3092
+ }
3093
+ const children = parentToChildren.get(ppid) ?? [];
3094
+ children.push(pid);
3095
+ parentToChildren.set(ppid, children);
3096
+ }
3097
+ const queue = [rootPid];
3098
+ while (queue.length > 0) {
3099
+ const currentPid = queue.shift();
3100
+ if (!currentPid) {
3101
+ continue;
3102
+ }
3103
+ for (const childPid of parentToChildren.get(currentPid) ?? []) {
3104
+ if (descendants.has(childPid)) {
3105
+ continue;
3106
+ }
3107
+ descendants.add(childPid);
3108
+ queue.push(childPid);
3109
+ }
3110
+ }
3111
+ } catch {
3112
+ return descendants;
3113
+ }
3114
+ return descendants;
3115
+ }
3116
+ function matchesWorkspacePath(session, workspacePath) {
3117
+ const normalizedWorkspace = normalizePath(workspacePath);
3118
+ const candidatePaths = [session.cwd, session.repoRoot].filter((value) => Boolean(value)).map(normalizePath);
3119
+ return candidatePaths.some((path3) => path3 === normalizedWorkspace);
3120
+ }
3121
+ function normalizePath(value) {
3122
+ return value.replace(/\/+$/, "");
3123
+ }
3124
+ function sessionIdentityKey(session) {
3125
+ return [
3126
+ session.provider,
3127
+ session.sessionKey,
3128
+ session.localProcessId,
3129
+ session.cwd
3130
+ ].filter(Boolean).join("::");
3131
+ }
3132
+ function compareLocalSessionRecency(a, b) {
3133
+ return Number(b.localProcessId ?? 0) - Number(a.localProcessId ?? 0);
3134
+ }
3135
+ function sleep(ms) {
3136
+ return new Promise((resolve) => setTimeout(resolve, ms));
3137
+ }
3138
+ function isBridgeProvider(provider) {
3139
+ return provider === "codex" || provider === "claude_code";
3140
+ }
3141
+ function providerLabel(provider) {
3142
+ if (provider === "codex") {
3143
+ return "Codex";
3144
+ }
3145
+ if (provider === "claude_code") {
3146
+ return "Claude";
3147
+ }
3148
+ return "Vector CLI";
3149
+ }
3150
+ function installLaunchAgent(vcliPath) {
3151
+ if (platform() !== "darwin") {
3152
+ console.error("LaunchAgent is macOS only. Use systemd on Linux.");
3153
+ return;
3154
+ }
3155
+ const programArguments = getLaunchAgentProgramArguments(vcliPath);
3156
+ const environmentVariables = [
3157
+ " <key>PATH</key>",
3158
+ " <string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>",
3159
+ ...process.env.VECTOR_HOME?.trim() ? [
3160
+ " <key>VECTOR_HOME</key>",
3161
+ ` <string>${process.env.VECTOR_HOME.trim()}</string>`
3162
+ ] : []
3163
+ ].join("\n");
3164
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
3165
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3166
+ <plist version="1.0">
3167
+ <dict>
3168
+ <key>Label</key>
3169
+ <string>${LAUNCHAGENT_LABEL}</string>
3170
+ <key>ProgramArguments</key>
3171
+ ${programArguments}
3172
+ <key>RunAtLoad</key>
3173
+ <true/>
3174
+ <key>KeepAlive</key>
3175
+ <true/>
3176
+ <key>StandardOutPath</key>
3177
+ <string>${CONFIG_DIR}/bridge.log</string>
3178
+ <key>StandardErrorPath</key>
3179
+ <string>${CONFIG_DIR}/bridge.err.log</string>
3180
+ <key>EnvironmentVariables</key>
3181
+ <dict>
3182
+ ${environmentVariables}
3183
+ </dict>
3184
+ </dict>
3185
+ </plist>`;
3186
+ if (!existsSync3(LAUNCHAGENT_DIR)) {
3187
+ mkdirSync(LAUNCHAGENT_DIR, { recursive: true });
3188
+ }
3189
+ removeLegacyMenuBarLaunchAgent();
3190
+ writeFileSync(LAUNCHAGENT_PLIST, plist);
3191
+ console.log(`Installed LaunchAgent: ${LAUNCHAGENT_PLIST}`);
3192
+ }
3193
+ function getLaunchAgentProgramArguments(vcliPath) {
3194
+ const args = resolveCliInvocation(vcliPath);
3195
+ return [
3196
+ "<array>",
3197
+ ...args.map((arg) => ` <string>${arg}</string>`),
3198
+ " <string>service</string>",
3199
+ " <string>run</string>",
3200
+ " </array>"
3201
+ ].join("\n");
3202
+ }
3203
+ function resolveCliInvocation(vcliPath) {
3204
+ if (vcliPath.endsWith(".js")) {
3205
+ return [process.execPath, vcliPath];
3206
+ }
3207
+ if (vcliPath.endsWith(".ts")) {
3208
+ const tsxPath = join2(
3209
+ import.meta.dirname ?? process.cwd(),
3210
+ "..",
3211
+ "..",
3212
+ "..",
3213
+ "node_modules",
3214
+ ".bin",
3215
+ "tsx"
3216
+ );
3217
+ if (existsSync3(tsxPath)) {
3218
+ return [tsxPath, vcliPath];
3219
+ }
3220
+ }
3221
+ return [vcliPath];
3222
+ }
3223
+ function loadLaunchAgent() {
3224
+ if (runLaunchctl(["bootstrap", launchctlGuiDomain(), LAUNCHAGENT_PLIST])) {
3225
+ runLaunchctl([
3226
+ "kickstart",
3227
+ "-k",
3228
+ `${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`
3229
+ ]);
3230
+ console.log(
3231
+ "LaunchAgent loaded. Bridge will start automatically on login."
3232
+ );
3233
+ return;
3234
+ }
3235
+ if (runLaunchctl([
3236
+ "kickstart",
3237
+ "-k",
3238
+ `${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`
3239
+ ]) || runLaunchctl(["load", LAUNCHAGENT_PLIST])) {
3240
+ console.log(
3241
+ "LaunchAgent loaded. Bridge will start automatically on login."
3242
+ );
3243
+ return;
3244
+ }
3245
+ console.error("Failed to load LaunchAgent");
3246
+ }
3247
+ function unloadLaunchAgent() {
3248
+ if (runLaunchctl(["bootout", `${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`]) || runLaunchctl(["bootout", launchctlGuiDomain(), LAUNCHAGENT_PLIST]) || runLaunchctl(["unload", LAUNCHAGENT_PLIST])) {
3249
+ console.log("LaunchAgent unloaded.");
3250
+ return true;
3251
+ }
3252
+ console.error("Failed to unload LaunchAgent (may not be loaded)");
3253
+ return false;
3254
+ }
3255
+ function uninstallLaunchAgent() {
3256
+ unloadLaunchAgent();
3257
+ removeLegacyMenuBarLaunchAgent();
3258
+ try {
3259
+ unlinkSync(LAUNCHAGENT_PLIST);
3260
+ console.log("LaunchAgent removed.");
3261
+ } catch {
3262
+ }
3263
+ }
3264
+ var MENUBAR_PID_FILE = join2(CONFIG_DIR, "menubar.pid");
3265
+ function removeLegacyMenuBarLaunchAgent() {
3266
+ if (platform() !== "darwin" || !existsSync3(LEGACY_MENUBAR_LAUNCHAGENT_PLIST)) {
3267
+ return;
3268
+ }
3269
+ try {
3270
+ execSync2(`launchctl unload ${LEGACY_MENUBAR_LAUNCHAGENT_PLIST}`, {
3271
+ stdio: "pipe"
3272
+ });
3273
+ } catch {
3274
+ }
3275
+ try {
3276
+ unlinkSync(LEGACY_MENUBAR_LAUNCHAGENT_PLIST);
3277
+ } catch {
3278
+ }
3279
+ }
3280
+ function launchctlGuiDomain() {
3281
+ const uid = typeof process.getuid === "function" ? process.getuid() : typeof process.geteuid === "function" ? process.geteuid() : 0;
3282
+ return `gui/${uid}`;
3283
+ }
3284
+ function runLaunchctl(args) {
3285
+ try {
3286
+ execFileSync2("launchctl", args, {
3287
+ stdio: "ignore"
3288
+ });
3289
+ return true;
3290
+ } catch {
3291
+ return false;
3292
+ }
3293
+ }
3294
+ function findCliEntrypoint() {
3295
+ const candidates = [
3296
+ join2(import.meta.dirname ?? "", "index.js"),
3297
+ join2(import.meta.dirname ?? "", "index.ts"),
3298
+ join2(import.meta.dirname ?? "", "..", "dist", "index.js")
3299
+ ];
3300
+ for (const p of candidates) {
3301
+ if (existsSync3(p)) return p;
3302
+ }
3303
+ return null;
3304
+ }
3305
+ function getCurrentCliInvocation() {
3306
+ const entrypoint = findCliEntrypoint();
3307
+ if (!entrypoint) {
3308
+ return null;
3309
+ }
3310
+ return resolveCliInvocation(entrypoint);
3311
+ }
3312
+ function findMenuBarExecutable() {
3313
+ const candidates = [
3314
+ join2(
3315
+ import.meta.dirname ?? "",
3316
+ "..",
3317
+ "native",
3318
+ "VectorMenuBar.app",
3319
+ "Contents",
3320
+ "MacOS",
3321
+ "VectorMenuBar"
3322
+ ),
3323
+ join2(
3324
+ import.meta.dirname ?? "",
3325
+ "native",
3326
+ "VectorMenuBar.app",
3327
+ "Contents",
3328
+ "MacOS",
3329
+ "VectorMenuBar"
3330
+ )
3331
+ ];
3332
+ for (const p of candidates) {
3333
+ if (existsSync3(p)) {
3334
+ return p;
3335
+ }
3336
+ }
3337
+ return null;
3338
+ }
3339
+ function isKnownMenuBarProcess(pid) {
3340
+ try {
3341
+ const command = execSync2(`ps -p ${pid} -o args=`, {
3342
+ encoding: "utf-8",
3343
+ timeout: 3e3
3344
+ });
3345
+ return command.includes("menubar.js") || command.includes("menubar.ts") || command.includes("VectorMenuBar");
3346
+ } catch {
3347
+ return false;
3348
+ }
3349
+ }
3350
+ function killExistingMenuBar() {
3351
+ if (existsSync3(MENUBAR_PID_FILE)) {
3352
+ try {
3353
+ const pid = Number(readFileSync2(MENUBAR_PID_FILE, "utf-8").trim());
3354
+ if (Number.isFinite(pid) && pid > 0 && isKnownMenuBarProcess(pid)) {
3355
+ process.kill(pid, "SIGTERM");
3356
+ }
3357
+ } catch {
3358
+ }
3359
+ try {
3360
+ unlinkSync(MENUBAR_PID_FILE);
3361
+ } catch {
3362
+ }
3363
+ }
3364
+ }
3365
+ async function launchMenuBar() {
3366
+ if (platform() !== "darwin") return;
3367
+ removeLegacyMenuBarLaunchAgent();
3368
+ const executable = findMenuBarExecutable();
3369
+ const cliInvocation = getCurrentCliInvocation();
3370
+ if (!executable || !cliInvocation) return;
3371
+ killExistingMenuBar();
3372
+ try {
3373
+ const { spawn: spawnChild } = await import("child_process");
3374
+ const child = spawnChild(executable, [], {
3375
+ detached: true,
3376
+ stdio: "ignore",
3377
+ env: {
3378
+ ...process.env,
3379
+ VECTOR_CLI_COMMAND: cliInvocation[0],
3380
+ VECTOR_CLI_ARGS_JSON: JSON.stringify(cliInvocation.slice(1))
3381
+ }
3382
+ });
3383
+ child.unref();
3384
+ if (child.pid) {
3385
+ writeFileSync(MENUBAR_PID_FILE, String(child.pid));
3386
+ }
3387
+ } catch {
277
3388
  }
278
3389
  }
279
- async function writeSession(session, profile = "default") {
280
- await mkdir(SESSION_ROOT, { recursive: true });
281
- await writeFile(
282
- getSessionPath(profile),
283
- `${JSON.stringify(session, null, 2)}
284
- `,
285
- "utf8"
286
- );
3390
+ function stopMenuBar() {
3391
+ killExistingMenuBar();
287
3392
  }
288
- async function clearSession(profile = "default") {
289
- await rm(getSessionPath(profile), { force: true });
3393
+ function getBridgeStatus() {
3394
+ const config = loadBridgeConfig();
3395
+ if (!config) return { configured: false, running: false, starting: false };
3396
+ let running = false;
3397
+ let starting = false;
3398
+ let pid;
3399
+ if (existsSync3(PID_FILE)) {
3400
+ const pidStr = readFileSync2(PID_FILE, "utf-8").trim();
3401
+ pid = Number(pidStr);
3402
+ try {
3403
+ process.kill(pid, 0);
3404
+ running = true;
3405
+ } catch {
3406
+ running = false;
3407
+ }
3408
+ }
3409
+ if (!running && platform() === "darwin") {
3410
+ starting = runLaunchctl(["print", `${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`]) || runLaunchctl(["list", LAUNCHAGENT_LABEL]);
3411
+ }
3412
+ return { configured: true, running, starting, pid, config };
290
3413
  }
291
- function createEmptySession() {
292
- return {
293
- version: 1,
294
- cookies: {}
295
- };
3414
+ function stopBridge(options) {
3415
+ if (options?.includeMenuBar) {
3416
+ killExistingMenuBar();
3417
+ }
3418
+ try {
3419
+ writeLiveActivitiesCache([]);
3420
+ } catch {
3421
+ }
3422
+ if (!existsSync3(PID_FILE)) return false;
3423
+ const pid = Number(readFileSync2(PID_FILE, "utf-8").trim());
3424
+ try {
3425
+ process.kill(pid, "SIGTERM");
3426
+ return true;
3427
+ } catch {
3428
+ return false;
3429
+ }
3430
+ }
3431
+ function ts2() {
3432
+ return (/* @__PURE__ */ new Date()).toLocaleTimeString();
296
3433
  }
297
3434
 
298
- // ../../src/cli/index.ts
3435
+ // src/index.ts
3436
+ import { platform as osPlatform } from "os";
299
3437
  loadEnv({ path: ".env.local", override: false });
300
3438
  loadEnv({ path: ".env", override: false });
301
3439
  var cliApi = {
@@ -404,7 +3542,103 @@ function buildPaginationOptions(limit, cursor) {
404
3542
  function normalizeMatch(value) {
405
3543
  return value?.trim().toLowerCase();
406
3544
  }
407
- async function fetchConvexUrl(appUrl) {
3545
+ function parseDate(value) {
3546
+ const ms = Date.parse(value);
3547
+ if (!Number.isFinite(ms)) {
3548
+ throw new Error(`Invalid date: ${value}`);
3549
+ }
3550
+ return ms;
3551
+ }
3552
+ function applyListFilters(items, options) {
3553
+ let result = [...items];
3554
+ if (options.createdAfter) {
3555
+ const threshold = parseDate(options.createdAfter);
3556
+ result = result.filter(
3557
+ (item) => typeof item.createdAt === "number" && item.createdAt >= threshold
3558
+ );
3559
+ }
3560
+ if (options.createdBefore) {
3561
+ const threshold = parseDate(options.createdBefore);
3562
+ result = result.filter(
3563
+ (item) => typeof item.createdAt === "number" && item.createdAt <= threshold
3564
+ );
3565
+ }
3566
+ if (options.updatedAfter) {
3567
+ const threshold = parseDate(options.updatedAfter);
3568
+ result = result.filter(
3569
+ (item) => typeof item.lastEditedAt === "number" && item.lastEditedAt >= threshold
3570
+ );
3571
+ }
3572
+ if (options.updatedBefore) {
3573
+ const threshold = parseDate(options.updatedBefore);
3574
+ result = result.filter(
3575
+ (item) => typeof item.lastEditedAt === "number" && item.lastEditedAt <= threshold
3576
+ );
3577
+ }
3578
+ if (options.sort) {
3579
+ const field = options.sort;
3580
+ const desc = options.order?.toLowerCase() === "desc";
3581
+ result.sort((a, b) => {
3582
+ const aVal = a[field];
3583
+ const bVal = b[field];
3584
+ if (aVal == null && bVal == null) return 0;
3585
+ if (aVal == null) return 1;
3586
+ if (bVal == null) return -1;
3587
+ if (typeof aVal === "number" && typeof bVal === "number")
3588
+ return desc ? bVal - aVal : aVal - bVal;
3589
+ return desc ? String(bVal).localeCompare(String(aVal)) : String(aVal).localeCompare(String(bVal));
3590
+ });
3591
+ }
3592
+ if (options.limit) {
3593
+ const limit = Number(options.limit);
3594
+ if (Number.isFinite(limit) && limit > 0) {
3595
+ result = result.slice(0, limit);
3596
+ }
3597
+ }
3598
+ return result;
3599
+ }
3600
+ function addEntityUrls(items, appUrl, orgSlug, entityType) {
3601
+ return items.map((item) => {
3602
+ let path3;
3603
+ switch (entityType) {
3604
+ case "issues":
3605
+ path3 = `/${orgSlug}/issues/${item.key}`;
3606
+ break;
3607
+ case "projects":
3608
+ path3 = `/${orgSlug}/projects/${item.key}`;
3609
+ break;
3610
+ case "teams":
3611
+ path3 = `/${orgSlug}/teams/${item.key}`;
3612
+ break;
3613
+ case "documents":
3614
+ path3 = `/${orgSlug}/documents/${item.id}`;
3615
+ break;
3616
+ case "folders":
3617
+ path3 = `/${orgSlug}/documents/folders/${item.id}`;
3618
+ break;
3619
+ }
3620
+ return { ...item, url: `${appUrl}${path3}` };
3621
+ });
3622
+ }
3623
+ function normalizeAppUrl(raw) {
3624
+ let url = raw.trim();
3625
+ if (!/^https?:\/\//i.test(url)) {
3626
+ const isLocal = /^localhost(:\d+)?/i.test(url) || /^127\.0\.0\.1(:\d+)?/.test(url);
3627
+ url = isLocal ? `http://${url}` : `https://${url}`;
3628
+ }
3629
+ return url.replace(/\/+$/, "");
3630
+ }
3631
+ async function resolveAppUrl(raw) {
3632
+ const url = normalizeAppUrl(raw);
3633
+ try {
3634
+ const response = await fetch(url, { method: "HEAD", redirect: "follow" });
3635
+ const resolved = new URL(response.url).origin;
3636
+ return resolved;
3637
+ } catch {
3638
+ return url;
3639
+ }
3640
+ }
3641
+ async function fetchAppConfig(appUrl) {
408
3642
  try {
409
3643
  const url = new URL("/api/config", appUrl).toString();
410
3644
  const response = await fetch(url);
@@ -413,21 +3647,29 @@ async function fetchConvexUrl(appUrl) {
413
3647
  }
414
3648
  const data = await response.json();
415
3649
  if (data.convexUrl) {
416
- return data.convexUrl;
3650
+ return {
3651
+ convexUrl: data.convexUrl,
3652
+ tunnelHost: data.tunnelHost || void 0
3653
+ };
417
3654
  }
418
3655
  } catch {
419
3656
  }
420
- return "http://127.0.0.1:3210";
3657
+ return { convexUrl: "http://127.0.0.1:3210" };
3658
+ }
3659
+ async function fetchConvexUrl(appUrl) {
3660
+ const config = await fetchAppConfig(appUrl);
3661
+ return config.convexUrl;
421
3662
  }
422
3663
  async function getRuntime(command) {
423
3664
  const options = command.optsWithGlobals();
424
- const profile = options.profile ?? "default";
3665
+ const profile = options.profile ?? await readDefaultProfile();
425
3666
  const session = await readSession(profile);
426
3667
  const appUrlSource = options.appUrl ?? session?.appUrl ?? process.env.NEXT_PUBLIC_APP_URL;
427
- const appUrl = requiredString(appUrlSource, "app URL");
428
- let convexUrl = options.convexUrl ?? session?.convexUrl ?? process.env.NEXT_PUBLIC_CONVEX_URL ?? process.env.CONVEX_URL;
3668
+ const appUrl = await resolveAppUrl(requiredString(appUrlSource, "app URL"));
3669
+ let convexUrl = options.convexUrl ?? session?.convexUrl;
429
3670
  if (!convexUrl) {
430
- convexUrl = await fetchConvexUrl(appUrl);
3671
+ const fetchedUrl = await fetchConvexUrl(appUrl);
3672
+ convexUrl = fetchedUrl !== "http://127.0.0.1:3210" ? fetchedUrl : process.env.NEXT_PUBLIC_CONVEX_URL ?? process.env.CONVEX_URL ?? fetchedUrl;
431
3673
  }
432
3674
  return {
433
3675
  appUrl,
@@ -439,7 +3681,7 @@ async function getRuntime(command) {
439
3681
  };
440
3682
  }
441
3683
  function requireSession(runtime) {
442
- if (!runtime.session || Object.keys(runtime.session.cookies).length === 0) {
3684
+ if (!runtime.session || Object.keys(runtime.session.cookies).length === 0 && !runtime.session.bearerToken) {
443
3685
  throw new Error("Not logged in. Run `vcli auth login` first.");
444
3686
  }
445
3687
  return runtime.session;
@@ -453,6 +3695,80 @@ function requireOrg(runtime, explicit) {
453
3695
  }
454
3696
  return orgSlug;
455
3697
  }
3698
+ function hostForAppUrl(appUrl) {
3699
+ if (!appUrl) {
3700
+ return void 0;
3701
+ }
3702
+ try {
3703
+ const url = new URL(appUrl);
3704
+ return url.port ? `${url.hostname}:${url.port}` : url.hostname;
3705
+ } catch {
3706
+ return void 0;
3707
+ }
3708
+ }
3709
+ function decodeSessionClaims(session) {
3710
+ const jwt = session?.cookies?.["__Secure-better-auth.convex_jwt"];
3711
+ if (!jwt) {
3712
+ return {};
3713
+ }
3714
+ const parts = jwt.split(".");
3715
+ if (parts.length < 2) {
3716
+ return {};
3717
+ }
3718
+ let payload = parts[1].replace(/-/g, "+").replace(/_/g, "/");
3719
+ while (payload.length % 4 !== 0) {
3720
+ payload += "=";
3721
+ }
3722
+ try {
3723
+ const decoded = JSON.parse(
3724
+ Buffer.from(payload, "base64").toString("utf8")
3725
+ );
3726
+ return {
3727
+ email: decoded.email,
3728
+ userId: decoded.sub ?? decoded.userId
3729
+ };
3730
+ } catch {
3731
+ return {};
3732
+ }
3733
+ }
3734
+ function buildMenuSessionInfo(session) {
3735
+ const claims = decodeSessionClaims(session);
3736
+ return {
3737
+ orgSlug: session?.activeOrgSlug ?? "oss-lab",
3738
+ appUrl: session?.appUrl,
3739
+ appDomain: hostForAppUrl(session?.appUrl),
3740
+ email: claims.email,
3741
+ userId: claims.userId
3742
+ };
3743
+ }
3744
+ function parseAgentProvider(value) {
3745
+ if (value === "codex" || value === "claude_code" || value === "vector_cli") {
3746
+ return value;
3747
+ }
3748
+ throw new Error("provider must be one of: codex, claude_code, vector_cli");
3749
+ }
3750
+ function isBridgeDeviceAuthError(error) {
3751
+ if (!error || typeof error !== "object") {
3752
+ return false;
3753
+ }
3754
+ const maybeData = error.data;
3755
+ return maybeData === "INVALID_DEVICE_SECRET" || maybeData === "DEVICE_NOT_FOUND";
3756
+ }
3757
+ async function validateStoredBridgeConfig(config) {
3758
+ const client = new ConvexHttpClient3(config.convexUrl);
3759
+ try {
3760
+ await client.mutation(api.agentBridge.bridgePublic.heartbeat, {
3761
+ deviceId: config.deviceId,
3762
+ deviceSecret: config.deviceSecret
3763
+ });
3764
+ return true;
3765
+ } catch (error) {
3766
+ if (isBridgeDeviceAuthError(error)) {
3767
+ return false;
3768
+ }
3769
+ throw error;
3770
+ }
3771
+ }
456
3772
  async function getClient(command) {
457
3773
  const runtime = await getRuntime(command);
458
3774
  const session = requireSession(runtime);
@@ -463,6 +3779,43 @@ async function getClient(command) {
463
3779
  );
464
3780
  return { client, runtime, session };
465
3781
  }
3782
+ async function ensureBridgeConfig(command) {
3783
+ let config = loadBridgeConfig();
3784
+ try {
3785
+ const runtime = await getRuntime(command);
3786
+ const session = requireSession(runtime);
3787
+ const client = await createConvexClient(
3788
+ session,
3789
+ runtime.appUrl,
3790
+ runtime.convexUrl
3791
+ );
3792
+ const user = await runQuery(client, api.users.currentUser);
3793
+ if (!user) {
3794
+ throw new Error("Not logged in. Run `vcli auth login` first.");
3795
+ }
3796
+ const backendDevice = config ? await runQuery(client, api.agentBridge.queries.getDevice, {
3797
+ deviceId: config.deviceId
3798
+ }) : null;
3799
+ const needsRegistration = !config || config.userId !== user._id || config.convexUrl !== runtime.convexUrl || !backendDevice || !await validateStoredBridgeConfig(config);
3800
+ if (needsRegistration) {
3801
+ config = await setupBridgeDevice(client, runtime.convexUrl);
3802
+ }
3803
+ if (!config) {
3804
+ throw new Error("Bridge device is not configured.");
3805
+ }
3806
+ const appConfig = await fetchAppConfig(runtime.appUrl);
3807
+ if (appConfig.tunnelHost) {
3808
+ config.tunnelHost = appConfig.tunnelHost;
3809
+ }
3810
+ saveBridgeConfig(config);
3811
+ return config;
3812
+ } catch (error) {
3813
+ if (config) {
3814
+ return config;
3815
+ }
3816
+ throw error;
3817
+ }
3818
+ }
466
3819
  async function resolveMemberId(client, orgSlug, ref) {
467
3820
  const members = await runQuery(
468
3821
  client,
@@ -638,10 +3991,19 @@ async function parseEstimatedTimes(client, orgSlug, value) {
638
3991
  return estimatedTimes;
639
3992
  }
640
3993
  var program = new Command();
641
- program.name("vcli").description("Vector CLI").showHelpAfterError().option(
3994
+ function readPackageVersionSync() {
3995
+ try {
3996
+ const dir = import.meta.dirname ?? dirname(fileURLToPath2(import.meta.url));
3997
+ const raw = readFileSync3(join3(dir, "..", "package.json"), "utf8");
3998
+ return JSON.parse(raw).version ?? "unknown";
3999
+ } catch {
4000
+ return "unknown";
4001
+ }
4002
+ }
4003
+ program.name("vcli").description("Vector CLI").version(readPackageVersionSync(), "-v, --version").showHelpAfterError().option(
642
4004
  "--app-url <url>",
643
4005
  "Vector app URL. Required unless saved in the profile or NEXT_PUBLIC_APP_URL is set."
644
- ).option("--convex-url <url>", "Convex deployment URL").option("--org <slug>", "Organization slug override").option("--profile <name>", "CLI profile name", "default").option("--json", "Output JSON");
4006
+ ).option("--convex-url <url>", "Convex deployment URL").option("--org <slug>", "Organization slug override").option("--profile <name>", "CLI profile name").option("--json", "Output JSON");
645
4007
  var authCommand = program.command("auth").description("Authentication");
646
4008
  authCommand.command("signup").option("--email <email>", "Email address").option("--username <username>", "Username").option("--password <password>", "Password").action(async (options, command) => {
647
4009
  const runtime = await getRuntime(command);
@@ -682,19 +4044,48 @@ authCommand.command("signup").option("--email <email>", "Email address").option(
682
4044
  runtime.json
683
4045
  );
684
4046
  });
685
- authCommand.command("login [identifier]").option("--password <password>", "Password").action(async (identifier, options, command) => {
4047
+ authCommand.command("login [identifier]").option("--password <password>", "Password (uses device flow if omitted)").action(async (identifier, options, command) => {
686
4048
  const runtime = await getRuntime(command);
687
- const loginId = identifier?.trim() || await prompt("Email or username: ");
688
- const password = options.password?.trim() || await promptSecret("Password: ");
689
4049
  let session = createEmptySession();
690
4050
  session.appUrl = runtime.appUrl;
691
4051
  session.convexUrl = runtime.convexUrl;
692
- session = await loginWithPassword(
693
- session,
694
- runtime.appUrl,
695
- loginId,
696
- password
697
- );
4052
+ const usePassword = Boolean(identifier || options.password);
4053
+ if (usePassword) {
4054
+ const loginId = identifier?.trim() || await prompt("Email or username: ");
4055
+ const password = options.password?.trim() || await promptSecret("Password: ");
4056
+ session = await loginWithPassword(
4057
+ session,
4058
+ runtime.appUrl,
4059
+ loginId,
4060
+ password
4061
+ );
4062
+ } else {
4063
+ const deviceResp = await requestDeviceCode(runtime.appUrl, "vcli");
4064
+ const verifyUrl = `${runtime.appUrl}/device?user_code=${deviceResp.user_code}`;
4065
+ console.log();
4066
+ console.log(` Open this URL in your browser to log in:`);
4067
+ console.log();
4068
+ console.log(` ${verifyUrl}`);
4069
+ console.log();
4070
+ console.log(` Or go to ${runtime.appUrl}/device and enter code:`);
4071
+ console.log();
4072
+ console.log(` ${deviceResp.user_code}`);
4073
+ console.log();
4074
+ const open2 = await Promise.resolve().then(() => (init_open(), open_exports)).then((m) => m.default).catch(() => null);
4075
+ if (open2) {
4076
+ await open2(verifyUrl).catch(() => {
4077
+ });
4078
+ }
4079
+ console.log(" Waiting for authorization...");
4080
+ session = await pollDeviceToken(
4081
+ session,
4082
+ runtime.appUrl,
4083
+ deviceResp.device_code,
4084
+ "vcli",
4085
+ deviceResp.interval,
4086
+ deviceResp.expires_in
4087
+ );
4088
+ }
698
4089
  const authState = await fetchAuthSession(session, runtime.appUrl);
699
4090
  session = authState.session;
700
4091
  const client = await createConvexClient(
@@ -735,6 +4126,38 @@ authCommand.command("whoami").action(async (_options, command) => {
735
4126
  runtime.json
736
4127
  );
737
4128
  });
4129
+ authCommand.command("profiles").action(async (_options, command) => {
4130
+ const options = command.optsWithGlobals();
4131
+ const explicitProfile = options.profile?.trim();
4132
+ const defaultProfile = await readDefaultProfile();
4133
+ const profiles = await listProfiles();
4134
+ const activeProfile = explicitProfile || defaultProfile;
4135
+ printOutput(
4136
+ {
4137
+ activeProfile,
4138
+ defaultProfile,
4139
+ profiles
4140
+ },
4141
+ Boolean(options.json)
4142
+ );
4143
+ });
4144
+ authCommand.command("use-profile <name>").action(async (name, _options, command) => {
4145
+ const options = command.optsWithGlobals();
4146
+ const profile = name.trim();
4147
+ if (!profile) {
4148
+ throw new Error("Profile name is required.");
4149
+ }
4150
+ await writeDefaultProfile(profile);
4151
+ const session = await readSession(profile);
4152
+ printOutput(
4153
+ {
4154
+ ok: true,
4155
+ defaultProfile: profile,
4156
+ hasSession: session !== null
4157
+ },
4158
+ Boolean(options.json)
4159
+ );
4160
+ });
738
4161
  var orgCommand = program.command("org").description("Organizations");
739
4162
  orgCommand.command("list").action(async (_options, command) => {
740
4163
  const { client, runtime } = await getClient(command);
@@ -1065,6 +4488,75 @@ permissionCommand.command("check-many <permissions>").option("--team <teamKey>")
1065
4488
  printOutput(result, runtime.json);
1066
4489
  });
1067
4490
  var activityCommand = program.command("activity").description("Activity feed");
4491
+ activityCommand.command("list").description(
4492
+ "List org-wide activity with optional filters by entity type, event type, and time range"
4493
+ ).option(
4494
+ "--entity-type <type>",
4495
+ "Filter by entity type: issue, project, team, document"
4496
+ ).option(
4497
+ "--event-type <type>",
4498
+ "Filter by event type (e.g. issue_created, issue_priority_changed)"
4499
+ ).option(
4500
+ "--since <datetime>",
4501
+ "Start of time range (ISO date or shorthand: today, yesterday, 7d, 30d)"
4502
+ ).option(
4503
+ "--until <datetime>",
4504
+ "End of time range (ISO date or shorthand: today, now)"
4505
+ ).option("--limit <n>").option("--cursor <cursor>").action(async (options, command) => {
4506
+ const { client, runtime } = await getClient(command);
4507
+ const orgSlug = requireOrg(runtime);
4508
+ function parseTimeArg(value, bound) {
4509
+ if (!value) return void 0;
4510
+ const now = /* @__PURE__ */ new Date();
4511
+ const startOfToday = new Date(
4512
+ now.getFullYear(),
4513
+ now.getMonth(),
4514
+ now.getDate()
4515
+ );
4516
+ const endOfToday = new Date(
4517
+ now.getFullYear(),
4518
+ now.getMonth(),
4519
+ now.getDate(),
4520
+ 23,
4521
+ 59,
4522
+ 59,
4523
+ 999
4524
+ );
4525
+ switch (value) {
4526
+ case "now":
4527
+ return now.getTime();
4528
+ case "today":
4529
+ return bound === "start" ? startOfToday.getTime() : endOfToday.getTime();
4530
+ case "yesterday":
4531
+ return bound === "start" ? startOfToday.getTime() - 864e5 : startOfToday.getTime() - 1;
4532
+ default: {
4533
+ const daysMatch = value.match(/^(\d+)d$/);
4534
+ if (daysMatch) {
4535
+ return now.getTime() - Number(daysMatch[1]) * 864e5;
4536
+ }
4537
+ const parsed = new Date(value).getTime();
4538
+ if (Number.isNaN(parsed)) {
4539
+ throw new Error(`Invalid time value: ${value}`);
4540
+ }
4541
+ return parsed;
4542
+ }
4543
+ }
4544
+ }
4545
+ const result = await runQuery(
4546
+ client,
4547
+ api.activities.queries.listOrgActivity,
4548
+ {
4549
+ orgSlug,
4550
+ entityType: options.entityType ?? void 0,
4551
+ eventType: options.eventType ?? void 0,
4552
+ since: parseTimeArg(options.since, "start"),
4553
+ until: parseTimeArg(options.until, "end"),
4554
+ limit: optionalNumber(options.limit, "limit") ?? void 0,
4555
+ cursor: options.cursor ?? void 0
4556
+ }
4557
+ );
4558
+ printOutput(result, runtime.json);
4559
+ });
1068
4560
  activityCommand.command("project <projectKey>").option("--limit <n>").option("--cursor <cursor>").action(async (projectKey, options, command) => {
1069
4561
  const { client, runtime } = await getClient(command);
1070
4562
  const orgSlug = requireOrg(runtime);
@@ -1521,13 +5013,14 @@ adminCommand.command("sync-disposable-domains").action(async (_options, command)
1521
5013
  printOutput(result, runtime.json);
1522
5014
  });
1523
5015
  var teamCommand = program.command("team").description("Teams");
1524
- teamCommand.command("list [slug]").option("--limit <n>").action(async (slug, options, command) => {
5016
+ 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) => {
1525
5017
  const { client, runtime } = await getClient(command);
1526
5018
  const orgSlug = requireOrg(runtime, slug);
1527
- const result = await runAction(client, cliApi.listTeams, {
1528
- orgSlug,
1529
- limit: options.limit ? Number(options.limit) : void 0
5019
+ const raw = await runAction(client, cliApi.listTeams, {
5020
+ orgSlug
1530
5021
  });
5022
+ const filtered = applyListFilters(raw, options);
5023
+ const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "teams");
1531
5024
  printOutput(result, runtime.json);
1532
5025
  });
1533
5026
  teamCommand.command("get <teamKey>").action(async (teamKey, _options, command) => {
@@ -1621,14 +5114,15 @@ teamCommand.command("set-lead <teamKey> <member>").action(async (teamKey, member
1621
5114
  printOutput(result, runtime.json);
1622
5115
  });
1623
5116
  var projectCommand = program.command("project").description("Projects");
1624
- projectCommand.command("list [slug]").option("--team <teamKey>").option("--limit <n>").action(async (slug, options, command) => {
5117
+ 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) => {
1625
5118
  const { client, runtime } = await getClient(command);
1626
5119
  const orgSlug = requireOrg(runtime, slug);
1627
- const result = await runAction(client, cliApi.listProjects, {
5120
+ const raw = await runAction(client, cliApi.listProjects, {
1628
5121
  orgSlug,
1629
- teamKey: options.team,
1630
- limit: options.limit ? Number(options.limit) : void 0
5122
+ teamKey: options.team
1631
5123
  });
5124
+ const filtered = applyListFilters(raw, options);
5125
+ const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "projects");
1632
5126
  printOutput(result, runtime.json);
1633
5127
  });
1634
5128
  projectCommand.command("get <projectKey>").action(async (projectKey, _options, command) => {
@@ -1728,15 +5222,17 @@ projectCommand.command("set-lead <projectKey> <member>").action(async (projectKe
1728
5222
  printOutput(result, runtime.json);
1729
5223
  });
1730
5224
  var issueCommand = program.command("issue").description("Issues");
1731
- issueCommand.command("list [slug]").option("--project <projectKey>").option("--team <teamKey>").option("--limit <n>").action(async (slug, options, command) => {
5225
+ 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) => {
1732
5226
  const { client, runtime } = await getClient(command);
1733
5227
  const orgSlug = requireOrg(runtime, slug);
1734
- const result = await runAction(client, cliApi.listIssues, {
5228
+ const raw = await runAction(client, cliApi.listIssues, {
1735
5229
  orgSlug,
1736
5230
  projectKey: options.project,
1737
5231
  teamKey: options.team,
1738
- limit: options.limit ? Number(options.limit) : void 0
5232
+ assigneeName: options.assignee
1739
5233
  });
5234
+ const filtered = applyListFilters(raw, options);
5235
+ const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "issues");
1740
5236
  printOutput(result, runtime.json);
1741
5237
  });
1742
5238
  issueCommand.command("get <issueKey>").action(async (issueKey, _options, command) => {
@@ -1933,15 +5429,40 @@ issueCommand.command("comment <issueKey>").requiredOption("--body <body>").actio
1933
5429
  });
1934
5430
  printOutput(result, runtime.json);
1935
5431
  });
5432
+ 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) => {
5433
+ const { client, runtime } = await getClient(command);
5434
+ const orgSlug = requireOrg(runtime);
5435
+ await runAction(client, api.github.actions.linkArtifactByUrl, {
5436
+ orgSlug,
5437
+ issueKey,
5438
+ url
5439
+ });
5440
+ printOutput({ success: true, issueKey, url }, runtime.json);
5441
+ });
1936
5442
  var documentCommand = program.command("document").description("Documents");
1937
- documentCommand.command("list [slug]").option("--folder-id <id>").option("--limit <n>").action(async (slug, options, command) => {
5443
+ 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(
5444
+ "--updated-after <date>",
5445
+ "Filter: last edited on or after date (ISO)"
5446
+ ).option(
5447
+ "--updated-before <date>",
5448
+ "Filter: last edited on or before date (ISO)"
5449
+ ).option(
5450
+ "--sort <field>",
5451
+ "Sort by field (e.g. createdAt, title, lastEditedAt)"
5452
+ ).option("--order <direction>", "Sort order: asc or desc (default: asc)").action(async (slug, options, command) => {
1938
5453
  const { client, runtime } = await getClient(command);
1939
5454
  const orgSlug = requireOrg(runtime, slug);
1940
- const result = await runAction(client, cliApi.listDocuments, {
5455
+ const raw = await runAction(client, cliApi.listDocuments, {
1941
5456
  orgSlug,
1942
- folderId: options.folderId,
1943
- limit: options.limit ? Number(options.limit) : void 0
5457
+ folderId: options.folderId
1944
5458
  });
5459
+ const filtered = applyListFilters(raw, options);
5460
+ const result = addEntityUrls(
5461
+ filtered,
5462
+ runtime.appUrl,
5463
+ orgSlug,
5464
+ "documents"
5465
+ );
1945
5466
  printOutput(result, runtime.json);
1946
5467
  });
1947
5468
  documentCommand.command("get <documentId>").action(async (documentId, _options, command) => {
@@ -2007,10 +5528,12 @@ documentCommand.command("delete <documentId>").action(async (documentId, _option
2007
5528
  printOutput(result, runtime.json);
2008
5529
  });
2009
5530
  var folderCommand = program.command("folder").description("Document folders");
2010
- folderCommand.command("list [slug]").action(async (slug, _options, command) => {
5531
+ 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) => {
2011
5532
  const { client, runtime } = await getClient(command);
2012
5533
  const orgSlug = requireOrg(runtime, slug);
2013
- const result = await runAction(client, cliApi.listFolders, { orgSlug });
5534
+ const raw = await runAction(client, cliApi.listFolders, { orgSlug });
5535
+ const filtered = applyListFilters(raw, options);
5536
+ const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "folders");
2014
5537
  printOutput(result, runtime.json);
2015
5538
  });
2016
5539
  folderCommand.command("create").requiredOption("--name <name>").option("--description <description>").option("--icon <icon>").option("--color <color>").action(async (options, command) => {
@@ -2050,6 +5573,371 @@ folderCommand.command("delete <folderId>").action(async (folderId, _options, com
2050
5573
  });
2051
5574
  printOutput(result, runtime.json);
2052
5575
  });
5576
+ var VECTOR_HOME = process.env.VECTOR_HOME?.trim() || `${process.env.HOME ?? "~"}/.vector`;
5577
+ var serviceCommand = program.command("service").description("Manage the local bridge service");
5578
+ serviceCommand.command("start").description("Start the bridge service via LaunchAgent (macOS) or foreground").action(async (_options, command) => {
5579
+ const existing = getBridgeStatus();
5580
+ if (existing.running) {
5581
+ console.log(`Bridge is already running (PID ${existing.pid}).`);
5582
+ return;
5583
+ }
5584
+ const { spinner } = await import("@clack/prompts");
5585
+ const s = spinner();
5586
+ s.start("Ensuring device registration...");
5587
+ const config = await ensureBridgeConfig(command);
5588
+ s.stop(`Device ready: ${config.displayName}`);
5589
+ if (osPlatform() === "darwin") {
5590
+ s.start("Starting bridge service...");
5591
+ const vcliPath = process.argv[1] ?? "vcli";
5592
+ installLaunchAgent(vcliPath);
5593
+ loadLaunchAgent();
5594
+ s.stop("Bridge service started.");
5595
+ } else {
5596
+ console.log(
5597
+ "Starting bridge in foreground (use systemd for background)..."
5598
+ );
5599
+ const bridge = new BridgeService(config);
5600
+ await bridge.run();
5601
+ }
5602
+ });
5603
+ serviceCommand.command("run").description("Run the bridge service in the foreground (used by LaunchAgent)").action(async (_options, command) => {
5604
+ const config = await ensureBridgeConfig(command);
5605
+ if (osPlatform() === "darwin") {
5606
+ await launchMenuBar();
5607
+ }
5608
+ const bridge = new BridgeService(config);
5609
+ await bridge.run();
5610
+ });
5611
+ serviceCommand.command("stop").description("Stop the bridge service").action(() => {
5612
+ let unloaded = false;
5613
+ if (osPlatform() === "darwin") {
5614
+ unloaded = unloadLaunchAgent();
5615
+ }
5616
+ if (stopBridge() || unloaded) {
5617
+ console.log("Bridge stopped.");
5618
+ } else if (osPlatform() !== "darwin") {
5619
+ console.log("Bridge is not running.");
5620
+ } else {
5621
+ console.log("Bridge is not running.");
5622
+ }
5623
+ });
5624
+ serviceCommand.command("status").description("Show bridge service status").action((_options, command) => {
5625
+ const status = getBridgeStatus();
5626
+ if (!status.configured) {
5627
+ console.log("Bridge not configured. Run: vcli service start");
5628
+ return;
5629
+ }
5630
+ console.log("Vector Bridge");
5631
+ console.log(
5632
+ ` Device: ${status.config.displayName} (${status.config.deviceId})`
5633
+ );
5634
+ console.log(` User: ${status.config.userId}`);
5635
+ const statusLabel = status.running ? `Running (PID ${status.pid})` : status.starting ? "Starting..." : "Not running";
5636
+ console.log(` Status: ${statusLabel}`);
5637
+ console.log(` Config: ${VECTOR_HOME}/bridge.json`);
5638
+ });
5639
+ serviceCommand.command("menu-state").description("Return JSON state for the macOS tray").action(async (_options, command) => {
5640
+ const status = getBridgeStatus();
5641
+ const globalOptions = command.optsWithGlobals();
5642
+ const profile = globalOptions.profile ?? await readDefaultProfile();
5643
+ const session = await readSession(profile);
5644
+ const profiles = await listProfiles();
5645
+ const defaultProfile = await readDefaultProfile();
5646
+ let workspaces = [];
5647
+ let workSessions = [];
5648
+ let detectedSessions = [];
5649
+ try {
5650
+ const runtime = await getRuntime(command);
5651
+ if (runtime.session && status.config?.deviceId) {
5652
+ const client = await createConvexClient(
5653
+ runtime.session,
5654
+ runtime.appUrl,
5655
+ runtime.convexUrl
5656
+ );
5657
+ workspaces = await runQuery(
5658
+ client,
5659
+ api.agentBridge.queries.listDeviceWorkspaces,
5660
+ {
5661
+ deviceId: status.config.deviceId
5662
+ }
5663
+ );
5664
+ workSessions = await runQuery(
5665
+ client,
5666
+ api.agentBridge.queries.listDeviceWorkSessions,
5667
+ {
5668
+ deviceId: status.config.deviceId
5669
+ }
5670
+ );
5671
+ const devices = await runQuery(
5672
+ client,
5673
+ api.agentBridge.queries.listProcessesForAttach,
5674
+ {}
5675
+ );
5676
+ const currentDevice = devices.find(
5677
+ (entry) => entry.device._id === status.config?.deviceId
5678
+ );
5679
+ detectedSessions = currentDevice?.processes ?? [];
5680
+ }
5681
+ } catch {
5682
+ workspaces = [];
5683
+ workSessions = [];
5684
+ detectedSessions = [];
5685
+ }
5686
+ printOutput(
5687
+ {
5688
+ configured: status.configured,
5689
+ running: status.running,
5690
+ starting: status.starting,
5691
+ pid: status.pid,
5692
+ config: status.config,
5693
+ sessionInfo: buildMenuSessionInfo(session),
5694
+ activeProfile: profile,
5695
+ defaultProfile,
5696
+ profiles,
5697
+ workspaces,
5698
+ workSessions,
5699
+ detectedSessions
5700
+ },
5701
+ Boolean(globalOptions.json)
5702
+ );
5703
+ });
5704
+ serviceCommand.command("set-default-workspace").description("Set the default workspace for this device").requiredOption("--workspace-id <id>").action(async (options, command) => {
5705
+ const { client, runtime } = await getClient(command);
5706
+ const workspaceId = await runMutation(
5707
+ client,
5708
+ api.agentBridge.mutations.setDefaultWorkspace,
5709
+ {
5710
+ workspaceId: options.workspaceId
5711
+ }
5712
+ );
5713
+ printOutput({ ok: true, workspaceId }, runtime.json);
5714
+ });
5715
+ serviceCommand.command("search-issues <query>").description("Search issues for tray attach actions").option("--limit <n>").action(async (query, options, command) => {
5716
+ const { client, runtime } = await getClient(command);
5717
+ const orgSlug = requireOrg(runtime);
5718
+ const result = await runQuery(client, api.search.queries.searchEntities, {
5719
+ orgSlug,
5720
+ query,
5721
+ limit: optionalNumber(options.limit, "limit") ?? 8
5722
+ });
5723
+ printOutput(result.issues ?? [], runtime.json);
5724
+ });
5725
+ 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) => {
5726
+ const { client, runtime } = await getClient(command);
5727
+ const liveActivityId = await runMutation(
5728
+ client,
5729
+ api.agentBridge.mutations.attachLiveActivity,
5730
+ {
5731
+ issueId: options.issueId,
5732
+ deviceId: options.deviceId,
5733
+ processId: options.processId,
5734
+ provider: parseAgentProvider(options.provider),
5735
+ title: options.title?.trim() || void 0
5736
+ }
5737
+ );
5738
+ printOutput({ ok: true, liveActivityId }, runtime.json);
5739
+ });
5740
+ serviceCommand.command("install").description("Install the bridge as a system service (macOS LaunchAgent)").action(async (_options, command) => {
5741
+ if (osPlatform() !== "darwin") {
5742
+ console.error("Service install is currently macOS only (LaunchAgent).");
5743
+ console.error("On Linux, use systemd --user manually for now.");
5744
+ return;
5745
+ }
5746
+ const { spinner } = await import("@clack/prompts");
5747
+ const s = spinner();
5748
+ s.start("Ensuring device registration...");
5749
+ const config = await ensureBridgeConfig(command);
5750
+ s.stop(`Device ready: ${config.displayName}`);
5751
+ s.start("Installing LaunchAgent...");
5752
+ const vcliPath = process.argv[1] ?? "vcli";
5753
+ installLaunchAgent(vcliPath);
5754
+ s.stop("LaunchAgent installed");
5755
+ s.start("Starting bridge service...");
5756
+ loadLaunchAgent();
5757
+ s.stop("Bridge service started");
5758
+ console.log("");
5759
+ console.log(
5760
+ "Bridge installed and running. Will start automatically on login."
5761
+ );
5762
+ });
5763
+ serviceCommand.command("uninstall").description("Stop the bridge and uninstall the system service").action(() => {
5764
+ stopBridge({ includeMenuBar: true });
5765
+ uninstallLaunchAgent();
5766
+ stopMenuBar();
5767
+ console.log("Bridge stopped and service uninstalled.");
5768
+ });
5769
+ serviceCommand.command("logs").description("Show bridge service logs").action(async () => {
5770
+ const fs7 = await import("fs");
5771
+ const p = await import("path");
5772
+ const logPath = p.join(VECTOR_HOME, "bridge.log");
5773
+ if (fs7.existsSync(logPath)) {
5774
+ const content = fs7.readFileSync(logPath, "utf-8");
5775
+ const lines = content.split("\n");
5776
+ console.log(lines.slice(-50).join("\n"));
5777
+ } else {
5778
+ console.log(`No log file found at ${logPath}`);
5779
+ }
5780
+ });
5781
+ serviceCommand.command("enable").description("Enable bridge to start at login (macOS LaunchAgent)").action(async () => {
5782
+ if (osPlatform() !== "darwin") {
5783
+ console.error("Login item is macOS only.");
5784
+ return;
5785
+ }
5786
+ const vcliPath = process.argv[1] ?? "vcli";
5787
+ installLaunchAgent(vcliPath);
5788
+ loadLaunchAgent();
5789
+ console.log("Bridge will start automatically on login.");
5790
+ });
5791
+ serviceCommand.command("disable").description("Disable bridge from starting at login").action(() => {
5792
+ uninstallLaunchAgent();
5793
+ stopMenuBar();
5794
+ console.log("Bridge will no longer start at login.");
5795
+ });
5796
+ var bridgeCommand = program.command("bridge").description("Start/stop the local agent bridge");
5797
+ bridgeCommand.command("start").description("Register device, install service, and start the bridge").action(async (_options, command) => {
5798
+ const existingConfig = loadBridgeConfig();
5799
+ const config = await ensureBridgeConfig(command);
5800
+ if (!existingConfig || existingConfig.deviceId !== config.deviceId || existingConfig.userId !== config.userId) {
5801
+ console.log(
5802
+ `Device registered: ${config.displayName} (${config.deviceId})`
5803
+ );
5804
+ }
5805
+ if (osPlatform() === "darwin") {
5806
+ const vcliPath = process.argv[1] ?? "vcli";
5807
+ installLaunchAgent(vcliPath);
5808
+ loadLaunchAgent();
5809
+ console.log("\nBridge installed and started as LaunchAgent.");
5810
+ console.log("It will restart automatically on login.");
5811
+ console.log("Run `vcli service status` to check.");
5812
+ } else {
5813
+ console.log("Starting bridge in foreground...");
5814
+ const bridge = new BridgeService(config);
5815
+ await bridge.run();
5816
+ }
5817
+ });
5818
+ bridgeCommand.command("stop").description("Stop the bridge service").action(() => {
5819
+ let unloaded = false;
5820
+ if (osPlatform() === "darwin") {
5821
+ uninstallLaunchAgent();
5822
+ unloaded = true;
5823
+ }
5824
+ if (stopBridge() || unloaded) {
5825
+ console.log("Bridge stopped.");
5826
+ } else {
5827
+ console.log("Bridge is not running.");
5828
+ }
5829
+ });
5830
+ bridgeCommand.command("status").description("Show bridge status").action(() => {
5831
+ const s = getBridgeStatus();
5832
+ if (!s.configured) {
5833
+ console.log("Bridge not configured. Run: vcli bridge start");
5834
+ return;
5835
+ }
5836
+ console.log("Vector Bridge");
5837
+ console.log(` Device: ${s.config.displayName} (${s.config.deviceId})`);
5838
+ console.log(
5839
+ ` Status: ${s.running ? `Running (PID ${s.pid})` : "Not running"}`
5840
+ );
5841
+ });
5842
+ function detectInstallMethod(version) {
5843
+ const execPath = process.argv[1] ?? "";
5844
+ const pkg = `@rehpic/vcli@${version}`;
5845
+ if (execPath.includes(".volta")) {
5846
+ return {
5847
+ method: "volta",
5848
+ command: ["volta", "install", pkg]
5849
+ };
5850
+ }
5851
+ if (execPath.includes("pnpm")) {
5852
+ return {
5853
+ method: "pnpm",
5854
+ command: ["pnpm", "add", "-g", pkg]
5855
+ };
5856
+ }
5857
+ if (execPath.includes("yarn")) {
5858
+ return {
5859
+ method: "yarn",
5860
+ command: ["yarn", "global", "add", pkg]
5861
+ };
5862
+ }
5863
+ return {
5864
+ method: "npm",
5865
+ command: ["npm", "install", "-g", pkg]
5866
+ };
5867
+ }
5868
+ async function checkForUpdate() {
5869
+ try {
5870
+ const { execSync: exec } = await import("child_process");
5871
+ const tagsRaw = exec("npm view @rehpic/vcli dist-tags --json", {
5872
+ encoding: "utf-8",
5873
+ timeout: 1e4
5874
+ }).trim();
5875
+ const tags = JSON.parse(tagsRaw);
5876
+ const latest = tags.latest?.includes("beta") ? tags.beta ?? tags.latest : tags.latest ?? tags.beta ?? "";
5877
+ const current = readPackageVersionSync();
5878
+ return {
5879
+ current,
5880
+ latest,
5881
+ hasUpdate: Boolean(latest) && latest !== current
5882
+ };
5883
+ } catch {
5884
+ return null;
5885
+ }
5886
+ }
5887
+ program.command("update").description("Update the CLI to the latest version").action(async () => {
5888
+ const { spinner, log } = await import("@clack/prompts");
5889
+ const s = spinner();
5890
+ s.start("Checking for updates...");
5891
+ const updateInfo = await checkForUpdate();
5892
+ if (!updateInfo) {
5893
+ s.stop("Could not check for updates.");
5894
+ return;
5895
+ }
5896
+ if (!updateInfo.hasUpdate) {
5897
+ s.stop(`Already on the latest version (${updateInfo.current}).`);
5898
+ return;
5899
+ }
5900
+ s.stop(`Update available: ${updateInfo.current} \u2192 ${updateInfo.latest}`);
5901
+ const install = detectInstallMethod(updateInfo.latest);
5902
+ log.info(`Install method: ${install.method}`);
5903
+ s.start("Stopping bridge service...");
5904
+ const wasRunning = getBridgeStatus().running;
5905
+ if (wasRunning) {
5906
+ stopBridge({ includeMenuBar: true });
5907
+ if (osPlatform() === "darwin") {
5908
+ unloadLaunchAgent();
5909
+ }
5910
+ stopMenuBar();
5911
+ }
5912
+ s.stop(wasRunning ? "Bridge stopped." : "Bridge was not running.");
5913
+ s.start(`Updating via ${install.method}...`);
5914
+ try {
5915
+ const { execFileSync: exec } = await import("child_process");
5916
+ exec(install.command[0], install.command.slice(1), {
5917
+ stdio: "inherit",
5918
+ timeout: 12e4
5919
+ });
5920
+ s.stop("CLI updated successfully.");
5921
+ } catch (err) {
5922
+ s.stop("Update failed.");
5923
+ log.error(`Run manually: ${install.command.join(" ")}`);
5924
+ return;
5925
+ }
5926
+ if (wasRunning) {
5927
+ s.start("Restarting bridge service...");
5928
+ try {
5929
+ const { execFileSync: exec } = await import("child_process");
5930
+ exec("vcli", ["service", "start"], {
5931
+ stdio: "inherit",
5932
+ timeout: 3e4
5933
+ });
5934
+ s.stop("Bridge restarted.");
5935
+ } catch {
5936
+ s.stop("Could not auto-restart. Run: vcli service start");
5937
+ }
5938
+ }
5939
+ log.success(`Updated to v${updateInfo.latest}`);
5940
+ });
2053
5941
  async function main() {
2054
5942
  await program.parseAsync(process.argv);
2055
5943
  }