@rehpic/vcli 0.1.0-beta.8.1 → 0.1.0-beta.80.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,818 @@
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
+ });
737
+
738
+ // package.json
739
+ var package_exports = {};
740
+ __export(package_exports, {
741
+ default: () => package_default
742
+ });
743
+ var package_default;
744
+ var init_package = __esm({
745
+ "package.json"() {
746
+ package_default = {
747
+ name: "@rehpic/vcli",
748
+ version: "0.1.0",
749
+ description: "Command line interface for Vector workspaces.",
750
+ license: "Apache-2.0",
751
+ type: "module",
752
+ repository: {
753
+ type: "git",
754
+ url: "git+https://github.com/xrehpicx/vector.git",
755
+ directory: "packages/vector-cli"
756
+ },
757
+ homepage: "https://github.com/xrehpicx/vector/tree/main/packages/vector-cli#readme",
758
+ bugs: {
759
+ url: "https://github.com/xrehpicx/vector/issues"
760
+ },
761
+ keywords: [
762
+ "vector",
763
+ "cli",
764
+ "project-management",
765
+ "convex",
766
+ "issues"
767
+ ],
768
+ engines: {
769
+ node: ">=20.19.0"
770
+ },
771
+ bin: {
772
+ vcli: "dist/index.js"
773
+ },
774
+ files: [
775
+ "dist",
776
+ "native",
777
+ "scripts",
778
+ "README.md"
779
+ ],
780
+ scripts: {
781
+ build: "node scripts/build-menubar-app.js && tsup --config tsup.config.ts"
782
+ },
783
+ dependencies: {
784
+ "@anthropic-ai/claude-agent-sdk": "^0.2.79",
785
+ "@clack/prompts": "^1.1.0",
786
+ commander: "^14.0.3",
787
+ convex: "^1.33.1",
788
+ dotenv: "^16.4.5",
789
+ localtunnel: "^2.0.2",
790
+ "node-datachannel": "^0.32.1",
791
+ "node-pty": "1.2.0-beta.12",
792
+ tunnelmole: "^2.4.0",
793
+ werift: "^0.22.9",
794
+ ws: "^8.19.0"
795
+ },
796
+ publishConfig: {
797
+ access: "public",
798
+ provenance: true
799
+ },
800
+ devDependencies: {
801
+ "@types/localtunnel": "^2.0.4",
802
+ "@types/ws": "^8.18.1"
803
+ }
804
+ };
805
+ }
806
+ });
2
807
 
3
- // ../../src/cli/index.ts
808
+ // src/index.ts
809
+ import { readFileSync as readFileSync3 } from "fs";
4
810
  import { readFile as readFile2 } from "fs/promises";
5
- import { extname } from "path";
811
+ import { dirname, extname, join as join3 } from "path";
812
+ import { fileURLToPath as fileURLToPath2 } from "url";
6
813
  import { config as loadEnv } from "dotenv";
7
814
  import { Command } from "commander";
815
+ import { ConvexHttpClient as ConvexHttpClient3 } from "convex/browser";
8
816
  import { makeFunctionReference } from "convex/server";
9
817
 
10
818
  // ../../convex/_generated/api.js
@@ -12,7 +820,7 @@ import { anyApi, componentsGeneric } from "convex/server";
12
820
  var api = anyApi;
13
821
  var components = componentsGeneric();
14
822
 
15
- // ../../src/cli/auth.ts
823
+ // src/auth.ts
16
824
  import { isCancel, password as passwordPrompt, text } from "@clack/prompts";
17
825
  function buildUrl(appUrl, pathname) {
18
826
  return new URL(pathname, appUrl).toString();
@@ -52,6 +860,9 @@ function applySetCookieHeaders(session, response) {
52
860
  async function authRequest(session, appUrl, pathname, init = {}) {
53
861
  const headers = new Headers(init.headers);
54
862
  const origin = new URL(appUrl).origin;
863
+ if (session.bearerToken && !headers.has("authorization")) {
864
+ headers.set("authorization", `Bearer ${session.bearerToken}`);
865
+ }
55
866
  if (Object.keys(session.cookies).length > 0) {
56
867
  headers.set("cookie", cookieHeader(session.cookies));
57
868
  }
@@ -146,7 +957,7 @@ async function fetchAuthSession(session, appUrl) {
146
957
  const data = await response.json();
147
958
  return {
148
959
  session: nextSession,
149
- user: data.user ?? null
960
+ user: data?.user ?? null
150
961
  };
151
962
  }
152
963
  async function fetchConvexToken(session, appUrl) {
@@ -170,6 +981,65 @@ async function fetchConvexToken(session, appUrl) {
170
981
  token: data.token
171
982
  };
172
983
  }
984
+ async function requestDeviceCode(appUrl, clientId) {
985
+ const response = await fetch(buildUrl(appUrl, "/api/auth/device/code"), {
986
+ method: "POST",
987
+ headers: { "content-type": "application/json" },
988
+ body: JSON.stringify({ client_id: clientId })
989
+ });
990
+ if (!response.ok) {
991
+ throw new Error(`Failed to request device code: HTTP ${response.status}`);
992
+ }
993
+ return await response.json();
994
+ }
995
+ async function pollDeviceToken(session, appUrl, deviceCode, clientId, interval, expiresIn) {
996
+ const deadline = Date.now() + expiresIn * 1e3;
997
+ let pollInterval = interval * 1e3;
998
+ while (Date.now() < deadline) {
999
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
1000
+ const { response, session: nextSession } = await authRequest(
1001
+ session,
1002
+ appUrl,
1003
+ "/api/auth/device/token",
1004
+ {
1005
+ method: "POST",
1006
+ body: JSON.stringify({
1007
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
1008
+ device_code: deviceCode,
1009
+ client_id: clientId
1010
+ })
1011
+ }
1012
+ );
1013
+ session = nextSession;
1014
+ if (response.ok) {
1015
+ const data = await response.json();
1016
+ if (data.access_token) {
1017
+ session.bearerToken = data.access_token;
1018
+ return session;
1019
+ }
1020
+ }
1021
+ let errorData;
1022
+ try {
1023
+ errorData = await response.json();
1024
+ } catch {
1025
+ errorData = { error: `HTTP ${response.status}` };
1026
+ }
1027
+ switch (errorData.error) {
1028
+ case "authorization_pending":
1029
+ break;
1030
+ case "slow_down":
1031
+ pollInterval += 5e3;
1032
+ break;
1033
+ case "access_denied":
1034
+ throw new Error("Authorization denied by user.");
1035
+ case "expired_token":
1036
+ throw new Error("Device code expired. Please try again.");
1037
+ default:
1038
+ throw new Error(`Device auth error: ${errorData.error}`);
1039
+ }
1040
+ }
1041
+ throw new Error("Device code expired. Please try again.");
1042
+ }
173
1043
  async function prompt(question) {
174
1044
  const value = await text({
175
1045
  message: question.replace(/:\s*$/, "")
@@ -190,7 +1060,7 @@ async function promptSecret(question) {
190
1060
  return String(value);
191
1061
  }
192
1062
 
193
- // ../../src/cli/convex.ts
1063
+ // src/convex.ts
194
1064
  import { ConvexHttpClient } from "convex/browser";
195
1065
  async function createConvexClient(session, appUrl, convexUrl) {
196
1066
  const { token } = await fetchConvexToken(session, appUrl);
@@ -208,7 +1078,7 @@ async function runAction(client, ref, ...args) {
208
1078
  return await client.action(ref, ...args);
209
1079
  }
210
1080
 
211
- // ../../src/cli/output.ts
1081
+ // src/output.ts
212
1082
  function simplify(value) {
213
1083
  if (value === null || value === void 0) {
214
1084
  return value;
@@ -255,13 +1125,68 @@ function printOutput(data, json = false) {
255
1125
  console.log(String(data));
256
1126
  }
257
1127
 
258
- // ../../src/cli/session.ts
259
- import { mkdir, readFile, rm, writeFile } from "fs/promises";
1128
+ // src/session.ts
1129
+ import { mkdir, readFile, readdir, rm, writeFile } from "fs/promises";
260
1130
  import { homedir } from "os";
261
1131
  import path from "path";
262
- var SESSION_ROOT = path.join(homedir(), ".vector");
1132
+ function getSessionRoot() {
1133
+ return process.env.VECTOR_HOME?.trim() || path.join(homedir(), ".vector");
1134
+ }
1135
+ function getProfileConfigPath() {
1136
+ return path.join(getSessionRoot(), "cli-config.json");
1137
+ }
263
1138
  function getSessionPath(profile = "default") {
264
- return path.join(SESSION_ROOT, `cli-${profile}.json`);
1139
+ return path.join(getSessionRoot(), `cli-${profile}.json`);
1140
+ }
1141
+ async function readDefaultProfile() {
1142
+ try {
1143
+ const raw = await readFile(getProfileConfigPath(), "utf8");
1144
+ const parsed = JSON.parse(raw);
1145
+ const profile = parsed.defaultProfile?.trim();
1146
+ return profile || "default";
1147
+ } catch {
1148
+ return "default";
1149
+ }
1150
+ }
1151
+ async function writeDefaultProfile(profile) {
1152
+ const normalized = profile.trim() || "default";
1153
+ await mkdir(getSessionRoot(), { recursive: true });
1154
+ const config = {
1155
+ version: 1,
1156
+ defaultProfile: normalized
1157
+ };
1158
+ await writeFile(
1159
+ getProfileConfigPath(),
1160
+ `${JSON.stringify(config, null, 2)}
1161
+ `,
1162
+ "utf8"
1163
+ );
1164
+ }
1165
+ async function listProfiles() {
1166
+ const root = getSessionRoot();
1167
+ const defaultProfile = await readDefaultProfile();
1168
+ try {
1169
+ const entries = await readdir(root, { withFileTypes: true });
1170
+ const names = entries.filter((entry) => entry.isFile()).map((entry) => entry.name).filter((name) => /^cli-.+\.json$/.test(name)).map((name) => name.replace(/^cli-/, "").replace(/\.json$/, ""));
1171
+ const uniqueNames = Array.from(/* @__PURE__ */ new Set([...names, defaultProfile])).sort(
1172
+ (left, right) => left.localeCompare(right)
1173
+ );
1174
+ return Promise.all(
1175
+ uniqueNames.map(async (name) => ({
1176
+ name,
1177
+ isDefault: name === defaultProfile,
1178
+ hasSession: await readSession(name) !== null
1179
+ }))
1180
+ );
1181
+ } catch {
1182
+ return [
1183
+ {
1184
+ name: defaultProfile,
1185
+ isDefault: true,
1186
+ hasSession: await readSession(defaultProfile) !== null
1187
+ }
1188
+ ];
1189
+ }
265
1190
  }
266
1191
  async function readSession(profile = "default") {
267
1192
  try {
@@ -273,29 +1198,2312 @@ async function readSession(profile = "default") {
273
1198
  ...parsed
274
1199
  };
275
1200
  } catch {
276
- return null;
1201
+ return null;
1202
+ }
1203
+ }
1204
+ async function writeSession(session, profile = "default") {
1205
+ await mkdir(getSessionRoot(), { recursive: true });
1206
+ await writeFile(
1207
+ getSessionPath(profile),
1208
+ `${JSON.stringify(session, null, 2)}
1209
+ `,
1210
+ "utf8"
1211
+ );
1212
+ }
1213
+ async function clearSession(profile = "default") {
1214
+ await rm(getSessionPath(profile), { force: true });
1215
+ }
1216
+ function createEmptySession() {
1217
+ return {
1218
+ version: 1,
1219
+ cookies: {}
1220
+ };
1221
+ }
1222
+
1223
+ // src/bridge-service.ts
1224
+ import { ConvexHttpClient as ConvexHttpClient2 } from "convex/browser";
1225
+ import { execFileSync as execFileSync2, execSync as execSync2 } from "child_process";
1226
+
1227
+ // src/terminal-peer.ts
1228
+ import { createServer } from "http";
1229
+ import { WebSocketServer, WebSocket } from "ws";
1230
+ import { ConvexClient } from "convex/browser";
1231
+ import * as pty from "node-pty";
1232
+ import { existsSync } from "fs";
1233
+ import { randomUUID } from "crypto";
1234
+ import { execFileSync } from "child_process";
1235
+ import localtunnel from "localtunnel";
1236
+ function findTmuxPath() {
1237
+ for (const p of [
1238
+ "/opt/homebrew/bin/tmux",
1239
+ "/usr/local/bin/tmux",
1240
+ "/usr/bin/tmux"
1241
+ ]) {
1242
+ if (existsSync(p)) return p;
1243
+ }
1244
+ return "tmux";
1245
+ }
1246
+ var TMUX = findTmuxPath();
1247
+ function ts() {
1248
+ return (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
1249
+ }
1250
+ function findPort() {
1251
+ return new Promise((resolve, reject) => {
1252
+ const srv = createServer();
1253
+ srv.listen(0, "127.0.0.1", () => {
1254
+ const addr = srv.address();
1255
+ const port = typeof addr === "object" && addr ? addr.port : 9100;
1256
+ srv.close(() => resolve(port));
1257
+ });
1258
+ srv.on("error", reject);
1259
+ });
1260
+ }
1261
+ function createViewerSession(targetSession, paneId) {
1262
+ const viewerName = `viewer-${randomUUID().slice(0, 8)}`;
1263
+ try {
1264
+ execFileSync(TMUX, [
1265
+ "new-session",
1266
+ "-d",
1267
+ "-s",
1268
+ viewerName,
1269
+ "-t",
1270
+ targetSession
1271
+ ]);
1272
+ execFileSync(TMUX, ["set-option", "-t", viewerName, "status", "off"]);
1273
+ if (paneId) {
1274
+ try {
1275
+ execFileSync(TMUX, ["select-pane", "-t", paneId]);
1276
+ } catch {
1277
+ }
1278
+ }
1279
+ return viewerName;
1280
+ } catch (err) {
1281
+ console.error(`[${ts()}] Failed to create viewer session:`, err);
1282
+ return targetSession;
1283
+ }
1284
+ }
1285
+ function killViewerSession(sessionName) {
1286
+ try {
1287
+ execFileSync(TMUX, ["kill-session", "-t", sessionName]);
1288
+ } catch {
1289
+ }
1290
+ }
1291
+ var TerminalPeerManager = class {
1292
+ constructor(config) {
1293
+ this.terminals = /* @__PURE__ */ new Map();
1294
+ this.failedSessions = /* @__PURE__ */ new Set();
1295
+ this.pendingStops = /* @__PURE__ */ new Map();
1296
+ this.unsubscribers = /* @__PURE__ */ new Map();
1297
+ this.config = config;
1298
+ this.client = new ConvexClient(config.convexUrl);
1299
+ }
1300
+ watchSession(workSessionId, tmuxSessionName, tmuxPaneId) {
1301
+ if (this.unsubscribers.has(workSessionId)) return;
1302
+ const unsub = this.client.onUpdate(
1303
+ api.agentBridge.bridgePublic.getWorkSessionTerminalState,
1304
+ {
1305
+ deviceId: this.config.deviceId,
1306
+ deviceSecret: this.config.deviceSecret,
1307
+ workSessionId
1308
+ },
1309
+ (state) => {
1310
+ if (!state) return;
1311
+ const terminal = this.terminals.get(workSessionId);
1312
+ if (state.terminalViewerActive && !terminal && !this.failedSessions.has(workSessionId)) {
1313
+ const pendingStop = this.pendingStops.get(workSessionId);
1314
+ if (pendingStop) {
1315
+ clearTimeout(pendingStop);
1316
+ this.pendingStops.delete(workSessionId);
1317
+ }
1318
+ console.log(`[${ts()}] Viewer active for ${tmuxSessionName}`);
1319
+ void this.startTerminal(
1320
+ workSessionId,
1321
+ tmuxSessionName,
1322
+ tmuxPaneId,
1323
+ state.terminalCols,
1324
+ state.terminalRows
1325
+ );
1326
+ } else if (!state.terminalViewerActive && terminal) {
1327
+ if (!this.pendingStops.has(workSessionId)) {
1328
+ this.pendingStops.set(
1329
+ workSessionId,
1330
+ setTimeout(() => {
1331
+ this.pendingStops.delete(workSessionId);
1332
+ console.log(`[${ts()}] Viewer inactive for ${tmuxSessionName}`);
1333
+ this.stopTerminal(workSessionId);
1334
+ this.failedSessions.delete(workSessionId);
1335
+ }, 2e3)
1336
+ );
1337
+ }
1338
+ }
1339
+ }
1340
+ );
1341
+ this.unsubscribers.set(workSessionId, unsub);
1342
+ }
1343
+ unwatchSession(workSessionId) {
1344
+ const unsub = this.unsubscribers.get(workSessionId);
1345
+ if (unsub) {
1346
+ unsub();
1347
+ this.unsubscribers.delete(workSessionId);
1348
+ }
1349
+ this.stopTerminal(workSessionId);
1350
+ }
1351
+ async startTerminal(workSessionId, tmuxSessionName, tmuxPaneId, cols, rows) {
1352
+ if (this.terminals.has(workSessionId)) return;
1353
+ try {
1354
+ const port = await findPort();
1355
+ const viewerSession = createViewerSession(tmuxSessionName, tmuxPaneId);
1356
+ const isLinked = viewerSession !== tmuxSessionName;
1357
+ console.log(
1358
+ `[${ts()}] Viewer session: ${viewerSession}${isLinked ? " (linked)" : ""}`
1359
+ );
1360
+ console.log(
1361
+ `[${ts()}] Spawning PTY: ${TMUX} attach-session -t ${viewerSession}`
1362
+ );
1363
+ const ptyProcess = pty.spawn(
1364
+ TMUX,
1365
+ ["attach-session", "-t", viewerSession],
1366
+ {
1367
+ name: "xterm-256color",
1368
+ cols: Math.max(cols, 10),
1369
+ rows: Math.max(rows, 4),
1370
+ cwd: process.env.HOME ?? "/",
1371
+ env: { ...process.env, TERM: "xterm-256color" }
1372
+ }
1373
+ );
1374
+ console.log(`[${ts()}] PTY started`);
1375
+ const token = randomUUID();
1376
+ const httpServer = createServer();
1377
+ const wss = new WebSocketServer({ server: httpServer });
1378
+ wss.on("connection", (ws, req) => {
1379
+ const url = new URL(req.url ?? "/", `http://localhost`);
1380
+ const clientToken = url.searchParams.get("token");
1381
+ if (clientToken !== token) {
1382
+ console.log(`[${ts()}] Rejected unauthorized connection`);
1383
+ ws.close(4401, "Unauthorized");
1384
+ return;
1385
+ }
1386
+ console.log(`[${ts()}] Client connected (${tmuxSessionName})`);
1387
+ try {
1388
+ execFileSync(TMUX, ["refresh-client", "-t", viewerSession]);
1389
+ } catch {
1390
+ }
1391
+ const dataHandler = ptyProcess.onData((data) => {
1392
+ if (ws.readyState === WebSocket.OPEN) {
1393
+ ws.send(data);
1394
+ }
1395
+ });
1396
+ ws.on("message", (msg) => {
1397
+ const str = msg.toString();
1398
+ if (str.startsWith("\0{")) {
1399
+ try {
1400
+ const parsed = JSON.parse(str.slice(1));
1401
+ if (parsed.type === "resize" && parsed.cols && parsed.rows) {
1402
+ ptyProcess.resize(
1403
+ Math.max(parsed.cols, 10),
1404
+ Math.max(parsed.rows, 4)
1405
+ );
1406
+ try {
1407
+ execFileSync(TMUX, ["refresh-client", "-t", viewerSession]);
1408
+ } catch {
1409
+ }
1410
+ return;
1411
+ }
1412
+ } catch {
1413
+ }
1414
+ }
1415
+ ptyProcess.write(str);
1416
+ });
1417
+ ws.on("close", () => {
1418
+ console.log(`[${ts()}] Client disconnected (${tmuxSessionName})`);
1419
+ dataHandler.dispose();
1420
+ });
1421
+ });
1422
+ await new Promise((resolve) => {
1423
+ httpServer.listen(port, "0.0.0.0", resolve);
1424
+ });
1425
+ console.log(`[${ts()}] WS server on port ${port}`);
1426
+ const tunnelOpts = { port };
1427
+ if (this.config.tunnelHost) {
1428
+ tunnelOpts.host = this.config.tunnelHost;
1429
+ }
1430
+ console.log(
1431
+ `[${ts()}] Opening tunnel...${this.config.tunnelHost ? ` (host: ${this.config.tunnelHost})` : ""}`
1432
+ );
1433
+ const tunnel = await localtunnel(tunnelOpts);
1434
+ const tunnelUrl = tunnel.url;
1435
+ console.log(`[${ts()}] Tunnel: ${tunnelUrl}`);
1436
+ const wsUrl = tunnelUrl.replace(/^https?:\/\//, "wss://");
1437
+ const terminal = {
1438
+ ptyProcess,
1439
+ httpServer,
1440
+ wss,
1441
+ tunnel,
1442
+ viewerSessionName: isLinked ? viewerSession : null,
1443
+ token,
1444
+ workSessionId,
1445
+ tmuxSessionName,
1446
+ port
1447
+ };
1448
+ this.terminals.set(workSessionId, terminal);
1449
+ await this.client.mutation(
1450
+ api.agentBridge.bridgePublic.updateWorkSessionTerminalUrl,
1451
+ {
1452
+ deviceId: this.config.deviceId,
1453
+ deviceSecret: this.config.deviceSecret,
1454
+ workSessionId,
1455
+ terminalUrl: wsUrl,
1456
+ terminalToken: token,
1457
+ terminalLocalPort: port
1458
+ }
1459
+ );
1460
+ ptyProcess.onExit(() => {
1461
+ console.log(`[${ts()}] PTY exited for ${tmuxSessionName}`);
1462
+ this.stopTerminal(workSessionId);
1463
+ });
1464
+ } catch (err) {
1465
+ console.error(`[${ts()}] Failed to start terminal:`, err);
1466
+ this.failedSessions.add(workSessionId);
1467
+ }
1468
+ }
1469
+ stopTerminal(workSessionId) {
1470
+ const terminal = this.terminals.get(workSessionId);
1471
+ if (!terminal) return;
1472
+ try {
1473
+ terminal.ptyProcess.kill();
1474
+ } catch {
1475
+ }
1476
+ try {
1477
+ terminal.tunnel.close();
1478
+ } catch {
1479
+ }
1480
+ try {
1481
+ terminal.wss.close();
1482
+ } catch {
1483
+ }
1484
+ try {
1485
+ terminal.httpServer.close();
1486
+ } catch {
1487
+ }
1488
+ if (terminal.viewerSessionName) {
1489
+ killViewerSession(terminal.viewerSessionName);
1490
+ }
1491
+ this.terminals.delete(workSessionId);
1492
+ console.log(`[${ts()}] Terminal stopped for ${terminal.tmuxSessionName}`);
1493
+ }
1494
+ stop() {
1495
+ for (const unsub of this.unsubscribers.values()) {
1496
+ try {
1497
+ unsub();
1498
+ } catch {
1499
+ }
1500
+ }
1501
+ this.unsubscribers.clear();
1502
+ for (const id of this.terminals.keys()) {
1503
+ this.stopTerminal(id);
1504
+ }
1505
+ void this.client.close();
1506
+ }
1507
+ };
1508
+
1509
+ // src/bridge-service.ts
1510
+ import {
1511
+ existsSync as existsSync3,
1512
+ mkdirSync,
1513
+ readFileSync as readFileSync2,
1514
+ writeFileSync,
1515
+ unlinkSync
1516
+ } from "fs";
1517
+ import { homedir as homedir3, hostname, platform } from "os";
1518
+ import { join as join2 } from "path";
1519
+ import { randomUUID as randomUUID2 } from "crypto";
1520
+
1521
+ // src/agent-adapters.ts
1522
+ import { execSync, spawn as spawn2 } from "child_process";
1523
+ import { existsSync as existsSync2, readFileSync, readdirSync } from "fs";
1524
+ import { homedir as homedir2, userInfo } from "os";
1525
+ import { basename, join } from "path";
1526
+ var LSOF_PATHS = ["/usr/sbin/lsof", "/usr/bin/lsof"];
1527
+ var VECTOR_BRIDGE_CLIENT_VERSION = "0.1.0";
1528
+ function discoverAttachableSessions() {
1529
+ return dedupeSessions([
1530
+ ...discoverTmuxSessions(),
1531
+ ...discoverCodexSessions(),
1532
+ ...discoverClaudeSessions()
1533
+ ]);
1534
+ }
1535
+ async function resumeProviderSession(provider, sessionKey, cwd, prompt2) {
1536
+ if (provider === "codex") {
1537
+ return runCodexAppServerTurn({
1538
+ cwd,
1539
+ prompt: prompt2,
1540
+ sessionKey,
1541
+ launchCommand: "codex app-server (thread/resume)"
1542
+ });
1543
+ }
1544
+ return runClaudeSdkTurn({
1545
+ cwd,
1546
+ prompt: prompt2,
1547
+ sessionKey,
1548
+ launchCommand: "@anthropic-ai/claude-agent-sdk query(resume)"
1549
+ });
1550
+ }
1551
+ async function runCodexAppServerTurn(args) {
1552
+ const child = spawn2("codex", ["app-server"], {
1553
+ cwd: args.cwd,
1554
+ env: { ...process.env },
1555
+ stdio: ["pipe", "pipe", "pipe"]
1556
+ });
1557
+ let stderr = "";
1558
+ let stdoutBuffer = "";
1559
+ let sessionKey = args.sessionKey;
1560
+ let finalAssistantText = "";
1561
+ let completed = false;
1562
+ let nextRequestId = 1;
1563
+ const pending = /* @__PURE__ */ new Map();
1564
+ let completeTurn;
1565
+ let failTurn;
1566
+ const turnCompleted = new Promise((resolve, reject) => {
1567
+ completeTurn = () => {
1568
+ completed = true;
1569
+ resolve();
1570
+ };
1571
+ failTurn = (error) => {
1572
+ completed = true;
1573
+ reject(error);
1574
+ };
1575
+ });
1576
+ child.stdout.on("data", (chunk) => {
1577
+ stdoutBuffer += chunk.toString();
1578
+ while (true) {
1579
+ const newlineIndex = stdoutBuffer.indexOf("\n");
1580
+ if (newlineIndex < 0) {
1581
+ break;
1582
+ }
1583
+ const line = stdoutBuffer.slice(0, newlineIndex).trim();
1584
+ stdoutBuffer = stdoutBuffer.slice(newlineIndex + 1);
1585
+ if (!line) {
1586
+ continue;
1587
+ }
1588
+ const payload = tryParseJson(line);
1589
+ if (!payload || typeof payload !== "object") {
1590
+ continue;
1591
+ }
1592
+ const responseId = payload.id;
1593
+ if (typeof responseId === "number" && pending.has(responseId)) {
1594
+ const entry = pending.get(responseId);
1595
+ pending.delete(responseId);
1596
+ const errorRecord = asObject(payload.error);
1597
+ if (errorRecord) {
1598
+ entry.reject(
1599
+ new Error(
1600
+ `codex app-server error: ${asString(errorRecord.message) ?? "Unknown JSON-RPC error"}`
1601
+ )
1602
+ );
1603
+ continue;
1604
+ }
1605
+ entry.resolve(payload.result);
1606
+ continue;
1607
+ }
1608
+ const method = asString(payload.method);
1609
+ const params = asObject(payload.params);
1610
+ if (!method || !params) {
1611
+ continue;
1612
+ }
1613
+ if (method === "thread/started") {
1614
+ sessionKey = asString(asObject(params.thread)?.id) ?? asString(asObject(params.thread)?.threadId) ?? sessionKey;
1615
+ continue;
1616
+ }
1617
+ if (method === "item/agentMessage/delta") {
1618
+ finalAssistantText += asString(params.delta) ?? "";
1619
+ continue;
1620
+ }
1621
+ if (method === "item/completed") {
1622
+ const item = asObject(params.item);
1623
+ if (asString(item?.type) === "agentMessage") {
1624
+ finalAssistantText = asString(item?.text) ?? finalAssistantText;
1625
+ }
1626
+ continue;
1627
+ }
1628
+ if (method === "turn/completed") {
1629
+ const turn = asObject(params.turn);
1630
+ const status = asString(turn?.status);
1631
+ if (status === "failed") {
1632
+ const turnError = asObject(turn?.error);
1633
+ failTurn?.(
1634
+ new Error(
1635
+ asString(turnError?.message) ?? "Codex turn failed without an error message"
1636
+ )
1637
+ );
1638
+ } else if (status === "interrupted") {
1639
+ failTurn?.(new Error("Codex turn was interrupted"));
1640
+ } else {
1641
+ completeTurn?.();
1642
+ }
1643
+ }
1644
+ }
1645
+ });
1646
+ child.stderr.on("data", (chunk) => {
1647
+ stderr += chunk.toString();
1648
+ });
1649
+ const request = (method, params) => new Promise((resolve, reject) => {
1650
+ const id = nextRequestId++;
1651
+ pending.set(id, { resolve, reject });
1652
+ child.stdin.write(`${JSON.stringify({ method, id, params })}
1653
+ `);
1654
+ });
1655
+ const notify = (method, params) => {
1656
+ child.stdin.write(`${JSON.stringify({ method, params })}
1657
+ `);
1658
+ };
1659
+ const waitForExit = new Promise((_, reject) => {
1660
+ child.on("error", (error) => reject(error));
1661
+ child.on("close", (code) => {
1662
+ if (!completed) {
1663
+ const detail = stderr.trim() || `codex app-server exited with code ${code}`;
1664
+ reject(new Error(detail));
1665
+ }
1666
+ });
1667
+ });
1668
+ try {
1669
+ await Promise.race([
1670
+ request("initialize", {
1671
+ clientInfo: {
1672
+ name: "vector_bridge",
1673
+ title: "Vector Bridge",
1674
+ version: VECTOR_BRIDGE_CLIENT_VERSION
1675
+ }
1676
+ }),
1677
+ waitForExit
1678
+ ]);
1679
+ notify("initialized", {});
1680
+ const threadResult = await Promise.race([
1681
+ args.sessionKey ? request("thread/resume", {
1682
+ threadId: args.sessionKey,
1683
+ cwd: args.cwd,
1684
+ approvalPolicy: "never",
1685
+ personality: "pragmatic"
1686
+ }) : request("thread/start", {
1687
+ cwd: args.cwd,
1688
+ approvalPolicy: "never",
1689
+ personality: "pragmatic",
1690
+ serviceName: "vector_bridge"
1691
+ }),
1692
+ waitForExit
1693
+ ]);
1694
+ sessionKey = asString(asObject(threadResult.thread)?.id) ?? asString(asObject(threadResult.thread)?.threadId) ?? sessionKey;
1695
+ if (!sessionKey) {
1696
+ throw new Error("Codex app-server did not return a thread id");
1697
+ }
1698
+ await Promise.race([
1699
+ request("turn/start", {
1700
+ threadId: sessionKey,
1701
+ input: [{ type: "text", text: args.prompt }],
1702
+ cwd: args.cwd,
1703
+ approvalPolicy: "never",
1704
+ personality: "pragmatic"
1705
+ }),
1706
+ waitForExit
1707
+ ]);
1708
+ await Promise.race([turnCompleted, waitForExit]);
1709
+ const gitInfo = getGitInfo(args.cwd);
1710
+ return {
1711
+ provider: "codex",
1712
+ providerLabel: "Codex",
1713
+ sessionKey,
1714
+ cwd: args.cwd,
1715
+ ...gitInfo,
1716
+ title: summarizeTitle(void 0, args.cwd),
1717
+ mode: "managed",
1718
+ status: "waiting",
1719
+ supportsInboundMessages: true,
1720
+ responseText: finalAssistantText.trim() || void 0,
1721
+ launchCommand: args.launchCommand
1722
+ };
1723
+ } finally {
1724
+ for (const entry of pending.values()) {
1725
+ entry.reject(
1726
+ new Error("codex app-server closed before request resolved")
1727
+ );
1728
+ }
1729
+ pending.clear();
1730
+ child.kill();
1731
+ }
1732
+ }
1733
+ async function runClaudeSdkTurn(args) {
1734
+ const { query } = await import("@anthropic-ai/claude-agent-sdk");
1735
+ const stream = query({
1736
+ prompt: args.prompt,
1737
+ options: {
1738
+ cwd: args.cwd,
1739
+ resume: args.sessionKey,
1740
+ persistSession: true,
1741
+ permissionMode: "bypassPermissions",
1742
+ allowDangerouslySkipPermissions: true,
1743
+ env: {
1744
+ ...process.env,
1745
+ CLAUDE_AGENT_SDK_CLIENT_APP: `vector-bridge/${VECTOR_BRIDGE_CLIENT_VERSION}`
1746
+ }
1747
+ }
1748
+ });
1749
+ let sessionKey = args.sessionKey;
1750
+ let responseText = "";
1751
+ let model;
1752
+ try {
1753
+ for await (const message of stream) {
1754
+ if (!message || typeof message !== "object") {
1755
+ continue;
1756
+ }
1757
+ sessionKey = asString(message.session_id) ?? sessionKey;
1758
+ if (message.type === "assistant") {
1759
+ const assistantText = extractClaudeMessageTexts(
1760
+ message.message
1761
+ ).join("\n\n").trim();
1762
+ if (assistantText) {
1763
+ responseText = assistantText;
1764
+ }
1765
+ continue;
1766
+ }
1767
+ if (message.type !== "result") {
1768
+ continue;
1769
+ }
1770
+ if (message.subtype === "success") {
1771
+ const resultText = asString(message.result);
1772
+ if (resultText) {
1773
+ responseText = resultText;
1774
+ }
1775
+ model = firstObjectKey(
1776
+ message.modelUsage
1777
+ );
1778
+ continue;
1779
+ }
1780
+ const errors = message.errors;
1781
+ const detail = Array.isArray(errors) && errors.length > 0 ? errors.join("\n") : "Claude execution failed";
1782
+ throw new Error(detail);
1783
+ }
1784
+ } finally {
1785
+ stream.close();
1786
+ }
1787
+ if (!sessionKey) {
1788
+ throw new Error("Claude Agent SDK did not return a session id");
1789
+ }
1790
+ const gitInfo = getGitInfo(args.cwd);
1791
+ return {
1792
+ provider: "claude_code",
1793
+ providerLabel: "Claude",
1794
+ sessionKey,
1795
+ cwd: args.cwd,
1796
+ ...gitInfo,
1797
+ title: summarizeTitle(void 0, args.cwd),
1798
+ model,
1799
+ mode: "managed",
1800
+ status: "waiting",
1801
+ supportsInboundMessages: true,
1802
+ responseText: responseText.trim() || void 0,
1803
+ launchCommand: args.launchCommand
1804
+ };
1805
+ }
1806
+ function discoverCodexSessions() {
1807
+ const historyBySession = buildCodexHistoryIndex();
1808
+ return listLiveProcessIds("codex").flatMap((pid) => {
1809
+ const transcriptPath = getCodexTranscriptPath(pid);
1810
+ if (!transcriptPath) {
1811
+ return [];
1812
+ }
1813
+ const processCwd = getProcessCwd(pid);
1814
+ const parsed = parseObservedCodexSession(
1815
+ pid,
1816
+ transcriptPath,
1817
+ processCwd,
1818
+ historyBySession
1819
+ );
1820
+ return parsed ? [parsed] : [];
1821
+ }).sort(compareObservedSessions);
1822
+ }
1823
+ function discoverClaudeSessions() {
1824
+ const historyBySession = buildClaudeHistoryIndex();
1825
+ return listLiveProcessIds("claude").flatMap((pid) => {
1826
+ const sessionMeta = readClaudePidSession(pid);
1827
+ if (!sessionMeta?.sessionId) {
1828
+ return [];
1829
+ }
1830
+ const transcriptPath = findClaudeTranscriptPath(sessionMeta.sessionId);
1831
+ const parsed = parseObservedClaudeSession(
1832
+ pid,
1833
+ sessionMeta,
1834
+ transcriptPath,
1835
+ historyBySession
1836
+ );
1837
+ return parsed ? [parsed] : [];
1838
+ }).sort(compareObservedSessions);
1839
+ }
1840
+ function discoverTmuxSessions() {
1841
+ try {
1842
+ const output = execSync(
1843
+ "tmux list-panes -a -F '#{pane_id} #{pane_pid} #{session_name} #{window_name} #{pane_current_path} #{pane_current_command} #{pane_title}'",
1844
+ {
1845
+ encoding: "utf-8",
1846
+ timeout: 3e3
1847
+ }
1848
+ );
1849
+ return output.split("\n").map((line) => line.trim()).filter(Boolean).flatMap((line) => {
1850
+ const [
1851
+ paneId,
1852
+ panePid,
1853
+ sessionName,
1854
+ windowName,
1855
+ cwd,
1856
+ currentCommand,
1857
+ paneTitle
1858
+ ] = line.split(" ");
1859
+ if (!paneId || !panePid || !sessionName || !windowName || !cwd) {
1860
+ return [];
1861
+ }
1862
+ const normalizedCommand = (currentCommand ?? "").trim().toLowerCase();
1863
+ if (normalizedCommand === "codex" || normalizedCommand === "claude") {
1864
+ return [];
1865
+ }
1866
+ const gitInfo = getGitInfo(cwd);
1867
+ const title = summarizeTitle(
1868
+ buildTmuxPaneTitle({
1869
+ paneTitle,
1870
+ sessionName,
1871
+ windowName,
1872
+ cwd,
1873
+ currentCommand
1874
+ }),
1875
+ cwd
1876
+ );
1877
+ return [
1878
+ {
1879
+ provider: "vector_cli",
1880
+ providerLabel: "Tmux",
1881
+ localProcessId: panePid,
1882
+ sessionKey: `tmux:${paneId}`,
1883
+ cwd,
1884
+ ...gitInfo,
1885
+ title,
1886
+ tmuxSessionName: sessionName,
1887
+ tmuxWindowName: windowName,
1888
+ tmuxPaneId: paneId,
1889
+ mode: "observed",
1890
+ status: "observed",
1891
+ supportsInboundMessages: true
1892
+ }
1893
+ ];
1894
+ }).sort(compareObservedSessions);
1895
+ } catch {
1896
+ return [];
1897
+ }
1898
+ }
1899
+ function getCodexHistoryFile() {
1900
+ return join(getRealHomeDir(), ".codex", "history.jsonl");
1901
+ }
1902
+ function getClaudeProjectsDir() {
1903
+ return join(getRealHomeDir(), ".claude", "projects");
1904
+ }
1905
+ function getClaudeSessionStateDir() {
1906
+ return join(getRealHomeDir(), ".claude", "sessions");
1907
+ }
1908
+ function getClaudeHistoryFile() {
1909
+ return join(getRealHomeDir(), ".claude", "history.jsonl");
1910
+ }
1911
+ function getRealHomeDir() {
1912
+ try {
1913
+ const realHome = userInfo().homedir?.trim();
1914
+ if (realHome) {
1915
+ return realHome;
1916
+ }
1917
+ } catch {
1918
+ }
1919
+ return homedir2();
1920
+ }
1921
+ function resolveExecutable(fallbackCommand, absoluteCandidates) {
1922
+ for (const candidate of absoluteCandidates) {
1923
+ if (existsSync2(candidate)) {
1924
+ return candidate;
1925
+ }
1926
+ }
1927
+ try {
1928
+ const output = execSync(`command -v ${fallbackCommand}`, {
1929
+ encoding: "utf-8",
1930
+ timeout: 1e3
1931
+ }).trim();
1932
+ return output || void 0;
1933
+ } catch {
1934
+ return void 0;
1935
+ }
1936
+ }
1937
+ function listLiveProcessIds(commandName) {
1938
+ try {
1939
+ const output = execSync("ps -axo pid=,comm=", {
1940
+ encoding: "utf-8",
1941
+ timeout: 3e3
1942
+ });
1943
+ 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);
1944
+ } catch {
1945
+ return [];
1946
+ }
1947
+ }
1948
+ function getProcessCwd(pid) {
1949
+ const lsofCommand = resolveExecutable("lsof", LSOF_PATHS);
1950
+ if (!lsofCommand) {
1951
+ return void 0;
1952
+ }
1953
+ try {
1954
+ const output = execSync(`${lsofCommand} -a -p ${pid} -Fn -d cwd`, {
1955
+ encoding: "utf-8",
1956
+ timeout: 3e3
1957
+ });
1958
+ return output.split("\n").map((line) => line.trim()).find((line) => line.startsWith("n"))?.slice(1);
1959
+ } catch {
1960
+ return void 0;
1961
+ }
1962
+ }
1963
+ function getCodexTranscriptPath(pid) {
1964
+ const lsofCommand = resolveExecutable("lsof", LSOF_PATHS);
1965
+ if (!lsofCommand) {
1966
+ return void 0;
1967
+ }
1968
+ try {
1969
+ const output = execSync(`${lsofCommand} -p ${pid} -Fn`, {
1970
+ encoding: "utf-8",
1971
+ timeout: 3e3
1972
+ });
1973
+ return output.split("\n").map((line) => line.trim()).find(
1974
+ (line) => line.startsWith("n") && line.includes("/.codex/sessions/") && line.endsWith(".jsonl")
1975
+ )?.slice(1);
1976
+ } catch {
1977
+ return void 0;
1978
+ }
1979
+ }
1980
+ function readClaudePidSession(pid) {
1981
+ const path3 = join(getClaudeSessionStateDir(), `${pid}.json`);
1982
+ if (!existsSync2(path3)) {
1983
+ return null;
1984
+ }
1985
+ try {
1986
+ const payload = JSON.parse(readFileSync(path3, "utf-8"));
1987
+ const sessionId = asString(payload.sessionId);
1988
+ if (!sessionId) {
1989
+ return null;
1990
+ }
1991
+ return {
1992
+ sessionId,
1993
+ cwd: asString(payload.cwd),
1994
+ startedAt: typeof payload.startedAt === "number" ? payload.startedAt : void 0
1995
+ };
1996
+ } catch {
1997
+ return null;
1998
+ }
1999
+ }
2000
+ function findClaudeTranscriptPath(sessionId) {
2001
+ return findJsonlFileByStem(getClaudeProjectsDir(), sessionId);
2002
+ }
2003
+ function findJsonlFileByStem(root, stem) {
2004
+ if (!existsSync2(root)) {
2005
+ return void 0;
2006
+ }
2007
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
2008
+ const path3 = join(root, entry.name);
2009
+ if (entry.isDirectory()) {
2010
+ const nested = findJsonlFileByStem(path3, stem);
2011
+ if (nested) {
2012
+ return nested;
2013
+ }
2014
+ continue;
2015
+ }
2016
+ if (entry.isFile() && entry.name === `${stem}.jsonl`) {
2017
+ return path3;
2018
+ }
2019
+ }
2020
+ return void 0;
2021
+ }
2022
+ function readJsonLines(path3) {
2023
+ try {
2024
+ return readFileSync(path3, "utf-8").split("\n").map((line) => line.trim()).filter(Boolean).map(tryParseJson).filter(Boolean);
2025
+ } catch {
2026
+ return [];
2027
+ }
2028
+ }
2029
+ function tryParseJson(value) {
2030
+ try {
2031
+ return JSON.parse(value);
2032
+ } catch {
2033
+ return null;
2034
+ }
2035
+ }
2036
+ function dedupeSessions(sessions) {
2037
+ const seen = /* @__PURE__ */ new Set();
2038
+ return sessions.filter((session) => {
2039
+ const key = `${session.provider}:${session.localProcessId ?? session.sessionKey}`;
2040
+ if (seen.has(key)) {
2041
+ return false;
2042
+ }
2043
+ seen.add(key);
2044
+ return true;
2045
+ });
2046
+ }
2047
+ function compareObservedSessions(a, b) {
2048
+ return Number(b.localProcessId ?? 0) - Number(a.localProcessId ?? 0);
2049
+ }
2050
+ function parseObservedCodexSession(pid, transcriptPath, processCwd, historyBySession) {
2051
+ const entries = readJsonLines(transcriptPath);
2052
+ let sessionKey;
2053
+ let cwd = processCwd;
2054
+ const userMessages = [];
2055
+ const assistantMessages = [];
2056
+ for (const rawEntry of entries) {
2057
+ const entry = asObject(rawEntry);
2058
+ if (!entry) {
2059
+ continue;
2060
+ }
2061
+ if (entry.type === "session_meta") {
2062
+ const payload = asObject(entry.payload);
2063
+ sessionKey = asString(payload?.id) ?? sessionKey;
2064
+ cwd = asString(payload?.cwd) ?? cwd;
2065
+ }
2066
+ if (entry.type === "event_msg") {
2067
+ const payload = asObject(entry.payload);
2068
+ if (payload?.type === "user_message") {
2069
+ pushIfPresent(userMessages, payload.message);
2070
+ }
2071
+ }
2072
+ if (entry.type === "response_item" && asObject(entry.payload)?.type === "message" && asObject(entry.payload)?.role === "user") {
2073
+ userMessages.push(
2074
+ ...extractTextSegments(asObject(entry.payload)?.content)
2075
+ );
2076
+ }
2077
+ if (entry.type === "event_msg") {
2078
+ const payload = asObject(entry.payload);
2079
+ if (payload?.type === "agent_message") {
2080
+ pushIfPresent(assistantMessages, payload.message);
2081
+ }
2082
+ }
2083
+ if (entry.type === "response_item" && asObject(entry.payload)?.type === "message" && asObject(entry.payload)?.role === "assistant") {
2084
+ assistantMessages.push(
2085
+ ...extractTextSegments(asObject(entry.payload)?.content)
2086
+ );
2087
+ }
2088
+ }
2089
+ if (!sessionKey) {
2090
+ return null;
2091
+ }
2092
+ const gitInfo = cwd ? getGitInfo(cwd) : {};
2093
+ const historyTitle = sessionKey ? selectSessionTitle(historyBySession?.get(sessionKey) ?? []) : void 0;
2094
+ return {
2095
+ provider: "codex",
2096
+ providerLabel: "Codex",
2097
+ localProcessId: pid,
2098
+ sessionKey,
2099
+ cwd,
2100
+ ...gitInfo,
2101
+ title: summarizeTitle(
2102
+ historyTitle ?? selectSessionTitle(userMessages) ?? selectSessionTitle(assistantMessages),
2103
+ cwd
2104
+ ),
2105
+ mode: "observed",
2106
+ status: "observed",
2107
+ supportsInboundMessages: true
2108
+ };
2109
+ }
2110
+ function parseObservedClaudeSession(pid, sessionMeta, transcriptPath, historyBySession) {
2111
+ const entries = transcriptPath ? readJsonLines(transcriptPath) : [];
2112
+ let cwd = sessionMeta.cwd;
2113
+ let branch;
2114
+ let model;
2115
+ const userMessages = [];
2116
+ const assistantMessages = [];
2117
+ for (const rawEntry of entries) {
2118
+ const entry = asObject(rawEntry);
2119
+ if (!entry) {
2120
+ continue;
2121
+ }
2122
+ cwd = asString(entry.cwd) ?? cwd;
2123
+ branch = asString(entry.gitBranch) ?? branch;
2124
+ if (entry.type === "user") {
2125
+ userMessages.push(...extractClaudeMessageTexts(entry.message));
2126
+ }
2127
+ if (entry.type === "assistant") {
2128
+ const message = asObject(entry.message);
2129
+ model = asString(message?.model) ?? model;
2130
+ assistantMessages.push(...extractClaudeMessageTexts(entry.message));
2131
+ }
2132
+ }
2133
+ const gitInfo = cwd ? getGitInfo(cwd) : {};
2134
+ const historyTitle = selectSessionTitle(
2135
+ historyBySession?.get(sessionMeta.sessionId) ?? []
2136
+ );
2137
+ return {
2138
+ provider: "claude_code",
2139
+ providerLabel: "Claude",
2140
+ localProcessId: pid,
2141
+ sessionKey: sessionMeta.sessionId,
2142
+ cwd,
2143
+ repoRoot: gitInfo.repoRoot,
2144
+ branch: branch ?? gitInfo.branch,
2145
+ title: summarizeTitle(
2146
+ historyTitle ?? selectSessionTitle(userMessages) ?? selectSessionTitle(assistantMessages),
2147
+ cwd
2148
+ ),
2149
+ model,
2150
+ mode: "observed",
2151
+ status: "observed",
2152
+ supportsInboundMessages: true
2153
+ };
2154
+ }
2155
+ function summarizeTitle(message, cwd) {
2156
+ if (message) {
2157
+ return truncate(message.replace(/\s+/g, " ").trim(), 96);
2158
+ }
2159
+ if (cwd) {
2160
+ return basename(cwd);
2161
+ }
2162
+ return "Local session";
2163
+ }
2164
+ function buildTmuxPaneTitle(args) {
2165
+ const paneTitle = cleanSessionTitleCandidate(args.paneTitle ?? "");
2166
+ if (paneTitle) {
2167
+ return paneTitle;
2168
+ }
2169
+ const command = asString(args.currentCommand);
2170
+ if (command && !["zsh", "bash", "fish", "sh", "nu"].includes(command)) {
2171
+ return `${command} in ${basename(args.cwd)}`;
2172
+ }
2173
+ return `${basename(args.cwd)} (${args.sessionName}:${args.windowName})`;
2174
+ }
2175
+ function truncate(value, maxLength) {
2176
+ return value.length > maxLength ? `${value.slice(0, maxLength - 3).trimEnd()}...` : value;
2177
+ }
2178
+ function firstObjectKey(value) {
2179
+ if (!value || typeof value !== "object") {
2180
+ return void 0;
2181
+ }
2182
+ const [firstKey] = Object.keys(value);
2183
+ return firstKey ? normalizeModelKey(firstKey) : void 0;
2184
+ }
2185
+ function normalizeModelKey(value) {
2186
+ const normalized = stripAnsi(value).replace(/\[\d+(?:;\d+)*m$/g, "").trim();
2187
+ return normalized || void 0;
2188
+ }
2189
+ function asObject(value) {
2190
+ return value && typeof value === "object" ? value : void 0;
2191
+ }
2192
+ function asString(value) {
2193
+ return typeof value === "string" && value.trim() ? value : void 0;
2194
+ }
2195
+ function pushIfPresent(target, value) {
2196
+ const text2 = asString(value);
2197
+ if (text2) {
2198
+ target.push(text2);
2199
+ }
2200
+ }
2201
+ function extractClaudeMessageTexts(message) {
2202
+ if (!message || typeof message !== "object") {
2203
+ return [];
2204
+ }
2205
+ return extractTextSegments(message.content);
2206
+ }
2207
+ function extractTextSegments(value) {
2208
+ if (typeof value === "string") {
2209
+ return [value];
2210
+ }
2211
+ if (!Array.isArray(value)) {
2212
+ return [];
2213
+ }
2214
+ return value.flatMap(extractTextSegmentFromBlock).filter(Boolean);
2215
+ }
2216
+ function extractTextSegmentFromBlock(block) {
2217
+ if (!block || typeof block !== "object") {
2218
+ return [];
2219
+ }
2220
+ const typedBlock = block;
2221
+ const blockType = asString(typedBlock.type);
2222
+ if (blockType && isIgnoredContentBlockType(blockType)) {
2223
+ return [];
2224
+ }
2225
+ const directText = asString(typedBlock.text);
2226
+ if (directText) {
2227
+ return [directText];
2228
+ }
2229
+ if (typeof typedBlock.content === "string") {
2230
+ return [typedBlock.content];
2231
+ }
2232
+ return [];
2233
+ }
2234
+ function isIgnoredContentBlockType(blockType) {
2235
+ return [
2236
+ "tool_result",
2237
+ "tool_use",
2238
+ "image",
2239
+ "thinking",
2240
+ "reasoning",
2241
+ "contextCompaction"
2242
+ ].includes(blockType);
2243
+ }
2244
+ function buildCodexHistoryIndex() {
2245
+ const historyBySession = /* @__PURE__ */ new Map();
2246
+ for (const rawEntry of readJsonLines(getCodexHistoryFile())) {
2247
+ const entry = asObject(rawEntry);
2248
+ if (!entry) {
2249
+ continue;
2250
+ }
2251
+ const sessionId = asString(entry.session_id);
2252
+ const text2 = asString(entry.text);
2253
+ if (!sessionId || !text2) {
2254
+ continue;
2255
+ }
2256
+ appendHistoryEntry(historyBySession, sessionId, text2);
2257
+ }
2258
+ return historyBySession;
2259
+ }
2260
+ function buildClaudeHistoryIndex() {
2261
+ const historyBySession = /* @__PURE__ */ new Map();
2262
+ for (const rawEntry of readJsonLines(getClaudeHistoryFile())) {
2263
+ const entry = asObject(rawEntry);
2264
+ if (!entry) {
2265
+ continue;
2266
+ }
2267
+ const sessionId = asString(entry.sessionId);
2268
+ if (!sessionId) {
2269
+ continue;
2270
+ }
2271
+ const texts = extractClaudeHistoryTexts(entry);
2272
+ for (const text2 of texts) {
2273
+ appendHistoryEntry(historyBySession, sessionId, text2);
2274
+ }
2275
+ }
2276
+ return historyBySession;
2277
+ }
2278
+ function appendHistoryEntry(historyBySession, sessionId, text2) {
2279
+ const existing = historyBySession.get(sessionId);
2280
+ if (existing) {
2281
+ existing.push(text2);
2282
+ return;
2283
+ }
2284
+ historyBySession.set(sessionId, [text2]);
2285
+ }
2286
+ function extractClaudeHistoryTexts(entry) {
2287
+ if (!entry || typeof entry !== "object") {
2288
+ return [];
2289
+ }
2290
+ const record = entry;
2291
+ const pastedTexts = extractClaudePastedTexts(record.pastedContents);
2292
+ if (pastedTexts.length > 0) {
2293
+ return pastedTexts;
2294
+ }
2295
+ const display = asString(record.display);
2296
+ return display ? [display] : [];
2297
+ }
2298
+ function extractClaudePastedTexts(value) {
2299
+ if (!value || typeof value !== "object") {
2300
+ return [];
2301
+ }
2302
+ return Object.values(value).flatMap((item) => {
2303
+ if (!item || typeof item !== "object") {
2304
+ return [];
2305
+ }
2306
+ const record = item;
2307
+ return record.type === "text" && typeof record.content === "string" ? [record.content] : [];
2308
+ }).filter(Boolean);
2309
+ }
2310
+ function selectSessionTitle(messages) {
2311
+ for (const message of messages) {
2312
+ const cleaned = cleanSessionTitleCandidate(message);
2313
+ if (cleaned) {
2314
+ return cleaned;
2315
+ }
2316
+ }
2317
+ return void 0;
2318
+ }
2319
+ function cleanSessionTitleCandidate(message) {
2320
+ const normalized = stripAnsi(message).replace(/\s+/g, " ").trim();
2321
+ if (!normalized) {
2322
+ return void 0;
2323
+ }
2324
+ if (normalized.length < 4) {
2325
+ return void 0;
2326
+ }
2327
+ if (normalized.startsWith("/") || looksLikeGeneratedTagEnvelope(normalized) || looksLikeGeneratedImageSummary(normalized) || looksLikeStandaloneImagePath(normalized) || looksLikeInstructionScaffold(normalized)) {
2328
+ return void 0;
2329
+ }
2330
+ return normalized;
2331
+ }
2332
+ function looksLikeGeneratedTagEnvelope(value) {
2333
+ return /^<[\w:-]+>[\s\S]*<\/[\w:-]+>$/.test(value);
2334
+ }
2335
+ function looksLikeGeneratedImageSummary(value) {
2336
+ return /^\[image:/i.test(value) || /displayed at/i.test(value) && /coordinates/i.test(value);
2337
+ }
2338
+ function looksLikeStandaloneImagePath(value) {
2339
+ return /^\/\S+\.(png|jpe?g|gif|webp|heic|bmp)$/i.test(value) || /^file:\S+\.(png|jpe?g|gif|webp|heic|bmp)$/i.test(value);
2340
+ }
2341
+ function looksLikeInstructionScaffold(value) {
2342
+ if (value.length < 700) {
2343
+ return false;
2344
+ }
2345
+ const headingCount = value.match(/^#{1,3}\s/gm)?.length ?? 0;
2346
+ const tagCount = value.match(/<\/?[\w:-]+>/g)?.length ?? 0;
2347
+ const bulletCount = value.match(/^\s*[-*]\s/gm)?.length ?? 0;
2348
+ return headingCount + tagCount + bulletCount >= 6;
2349
+ }
2350
+ function stripAnsi(value) {
2351
+ return value.replace(/\u001B\[[0-9;]*m/g, "");
2352
+ }
2353
+ function getGitInfo(cwd) {
2354
+ try {
2355
+ const repoRoot = execSync("git rev-parse --show-toplevel", {
2356
+ encoding: "utf-8",
2357
+ cwd,
2358
+ timeout: 3e3
2359
+ }).trim();
2360
+ const branch = execSync("git rev-parse --abbrev-ref HEAD", {
2361
+ encoding: "utf-8",
2362
+ cwd,
2363
+ timeout: 3e3
2364
+ }).trim();
2365
+ return {
2366
+ repoRoot: repoRoot || void 0,
2367
+ branch: branch || void 0
2368
+ };
2369
+ } catch {
2370
+ return {};
2371
+ }
2372
+ }
2373
+
2374
+ // src/bridge-service.ts
2375
+ var CONFIG_DIR = process.env.VECTOR_HOME?.trim() || join2(homedir3(), ".vector");
2376
+ var BRIDGE_CONFIG_FILE = join2(CONFIG_DIR, "bridge.json");
2377
+ var DEVICE_KEY_FILE = join2(CONFIG_DIR, "device-key");
2378
+ var PID_FILE = join2(CONFIG_DIR, "bridge.pid");
2379
+ var LIVE_ACTIVITIES_CACHE = join2(CONFIG_DIR, "live-activities.json");
2380
+ var LAUNCHAGENT_DIR = join2(homedir3(), "Library", "LaunchAgents");
2381
+ var LAUNCHAGENT_PLIST = join2(LAUNCHAGENT_DIR, "com.vector.bridge.plist");
2382
+ var LAUNCHAGENT_LABEL = "com.vector.bridge";
2383
+ var LEGACY_MENUBAR_LAUNCHAGENT_LABEL = "com.vector.menubar";
2384
+ var LEGACY_MENUBAR_LAUNCHAGENT_PLIST = join2(
2385
+ LAUNCHAGENT_DIR,
2386
+ `${LEGACY_MENUBAR_LAUNCHAGENT_LABEL}.plist`
2387
+ );
2388
+ var HEARTBEAT_INTERVAL_MS = 3e4;
2389
+ var COMMAND_POLL_INTERVAL_MS = 5e3;
2390
+ var LIVE_ACTIVITY_SYNC_INTERVAL_MS = 5e3;
2391
+ var PROCESS_DISCOVERY_INTERVAL_MS = 6e4;
2392
+ function loadBridgeConfig() {
2393
+ if (!existsSync3(BRIDGE_CONFIG_FILE)) return null;
2394
+ try {
2395
+ return JSON.parse(readFileSync2(BRIDGE_CONFIG_FILE, "utf-8"));
2396
+ } catch {
2397
+ return null;
2398
+ }
2399
+ }
2400
+ function saveBridgeConfig(config) {
2401
+ if (!existsSync3(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
2402
+ writeFileSync(BRIDGE_CONFIG_FILE, JSON.stringify(config, null, 2));
2403
+ persistDeviceKey(config.deviceKey);
2404
+ }
2405
+ function writeLiveActivitiesCache(activities) {
2406
+ if (!existsSync3(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
2407
+ writeFileSync(LIVE_ACTIVITIES_CACHE, JSON.stringify(activities, null, 2));
2408
+ }
2409
+ var BridgeService = class {
2410
+ constructor(config) {
2411
+ this.timers = [];
2412
+ this.terminalPeer = null;
2413
+ this.config = config;
2414
+ this.client = new ConvexHttpClient2(config.convexUrl);
2415
+ }
2416
+ async heartbeat() {
2417
+ await this.client.mutation(api.agentBridge.bridgePublic.heartbeat, {
2418
+ deviceId: this.config.deviceId,
2419
+ deviceSecret: this.config.deviceSecret
2420
+ });
2421
+ }
2422
+ async pollCommands() {
2423
+ const commands = await this.client.query(
2424
+ api.agentBridge.bridgePublic.getPendingCommands,
2425
+ {
2426
+ deviceId: this.config.deviceId,
2427
+ deviceSecret: this.config.deviceSecret
2428
+ }
2429
+ );
2430
+ if (commands.length > 0) {
2431
+ console.log(`[${ts2()}] ${commands.length} pending command(s)`);
2432
+ }
2433
+ for (const cmd of commands) {
2434
+ await this.handleCommand(cmd);
2435
+ }
2436
+ }
2437
+ async handleCommand(cmd) {
2438
+ const claimed = await this.client.mutation(
2439
+ api.agentBridge.bridgePublic.claimCommand,
2440
+ {
2441
+ deviceId: this.config.deviceId,
2442
+ deviceSecret: this.config.deviceSecret,
2443
+ commandId: cmd._id
2444
+ }
2445
+ );
2446
+ if (!claimed) {
2447
+ return;
2448
+ }
2449
+ console.log(` ${cmd.kind}: ${cmd._id}`);
2450
+ try {
2451
+ switch (cmd.kind) {
2452
+ case "message":
2453
+ await this.handleMessageCommand(cmd);
2454
+ await this.completeCommand(cmd._id, "delivered");
2455
+ return;
2456
+ case "launch":
2457
+ await this.handleLaunchCommand(cmd);
2458
+ await this.completeCommand(cmd._id, "delivered");
2459
+ return;
2460
+ case "resize":
2461
+ await this.handleResizeCommand(cmd);
2462
+ await this.completeCommand(cmd._id, "delivered");
2463
+ return;
2464
+ default:
2465
+ throw new Error(`Unsupported bridge command: ${cmd.kind}`);
2466
+ }
2467
+ } catch (error) {
2468
+ const message = error instanceof Error ? error.message : "Unknown bridge error";
2469
+ console.error(` ! ${message}`);
2470
+ await this.postCommandError(cmd, message);
2471
+ await this.completeCommand(cmd._id, "failed");
2472
+ }
2473
+ }
2474
+ async reportProcesses() {
2475
+ const processes = discoverAttachableSessions();
2476
+ const activeSessionKeys = processes.map((proc) => proc.sessionKey).filter((value) => Boolean(value));
2477
+ const activeLocalProcessIds = processes.map((proc) => proc.localProcessId).filter((value) => Boolean(value));
2478
+ for (const proc of processes) {
2479
+ try {
2480
+ await this.reportProcess(proc);
2481
+ } catch {
2482
+ }
2483
+ }
2484
+ try {
2485
+ await this.client.mutation(
2486
+ api.agentBridge.bridgePublic.reconcileObservedProcesses,
2487
+ {
2488
+ deviceId: this.config.deviceId,
2489
+ deviceSecret: this.config.deviceSecret,
2490
+ activeSessionKeys,
2491
+ activeLocalProcessIds
2492
+ }
2493
+ );
2494
+ } catch {
2495
+ }
2496
+ if (processes.length > 0) {
2497
+ console.log(
2498
+ `[${ts2()}] Discovered ${processes.length} attachable session(s)`
2499
+ );
2500
+ }
2501
+ }
2502
+ async refreshLiveActivities() {
2503
+ try {
2504
+ const activities = await this.client.query(
2505
+ api.agentBridge.bridgePublic.getDeviceLiveActivities,
2506
+ {
2507
+ deviceId: this.config.deviceId,
2508
+ deviceSecret: this.config.deviceSecret
2509
+ }
2510
+ );
2511
+ writeLiveActivitiesCache(activities);
2512
+ if (this.terminalPeer) {
2513
+ for (const activity of activities) {
2514
+ if (activity.workSessionId && activity.tmuxSessionName) {
2515
+ this.terminalPeer.watchSession(
2516
+ activity.workSessionId,
2517
+ activity.tmuxSessionName,
2518
+ activity.tmuxPaneId
2519
+ );
2520
+ }
2521
+ }
2522
+ }
2523
+ } catch {
2524
+ }
2525
+ }
2526
+ async syncWorkSessionTerminals(activities) {
2527
+ for (const activity of activities) {
2528
+ if (!activity.workSessionId || !activity.tmuxPaneId) {
2529
+ continue;
2530
+ }
2531
+ try {
2532
+ await this.refreshWorkSessionTerminal(activity.workSessionId, {
2533
+ tmuxPaneId: activity.tmuxPaneId,
2534
+ cwd: activity.cwd,
2535
+ repoRoot: activity.repoRoot,
2536
+ branch: activity.branch,
2537
+ agentProvider: activity.agentProvider,
2538
+ agentSessionKey: activity.agentSessionKey
2539
+ });
2540
+ await this.verifyManagedWorkSession(activity);
2541
+ } catch {
2542
+ }
2543
+ }
2544
+ }
2545
+ async verifyManagedWorkSession(activity) {
2546
+ if (!activity.workSessionId || !activity.tmuxPaneId || !activity.agentProvider || !isBridgeProvider(activity.agentProvider) || activity.agentProcessId) {
2547
+ return;
2548
+ }
2549
+ const workspacePath = activity.workspacePath ?? activity.cwd ?? activity.repoRoot;
2550
+ if (!workspacePath) {
2551
+ return;
2552
+ }
2553
+ const attachedSession = await this.attachObservedAgentSession(
2554
+ activity.agentProvider,
2555
+ workspacePath
2556
+ );
2557
+ if (!attachedSession) {
2558
+ return;
2559
+ }
2560
+ await this.refreshWorkSessionTerminal(activity.workSessionId, {
2561
+ tmuxPaneId: activity.tmuxPaneId,
2562
+ cwd: attachedSession.process.cwd ?? activity.cwd ?? workspacePath,
2563
+ repoRoot: attachedSession.process.repoRoot ?? activity.repoRoot ?? workspacePath,
2564
+ branch: attachedSession.process.branch ?? activity.branch,
2565
+ agentProvider: attachedSession.process.provider,
2566
+ agentSessionKey: attachedSession.process.sessionKey
2567
+ });
2568
+ await this.postAgentMessage(
2569
+ activity._id,
2570
+ "status",
2571
+ `Verified ${providerLabel(attachedSession.process.provider)} in ${activity.tmuxPaneId}`
2572
+ );
2573
+ await this.updateLiveActivity(activity._id, {
2574
+ status: "active",
2575
+ latestSummary: `Verified ${providerLabel(attachedSession.process.provider)} in ${activity.tmuxPaneId}`,
2576
+ processId: attachedSession.processId,
2577
+ title: activity.title
2578
+ });
2579
+ }
2580
+ async refreshWorkSessionTerminal(workSessionId, metadata) {
2581
+ if (!workSessionId || !metadata.tmuxPaneId) {
2582
+ return;
2583
+ }
2584
+ const terminalSnapshot = captureTmuxPane(metadata.tmuxPaneId);
2585
+ await this.client.mutation(
2586
+ api.agentBridge.bridgePublic.updateWorkSessionTerminal,
2587
+ {
2588
+ deviceId: this.config.deviceId,
2589
+ deviceSecret: this.config.deviceSecret,
2590
+ workSessionId,
2591
+ terminalSnapshot,
2592
+ tmuxSessionName: metadata.tmuxSessionName,
2593
+ tmuxWindowName: metadata.tmuxWindowName,
2594
+ tmuxPaneId: metadata.tmuxPaneId,
2595
+ cwd: metadata.cwd,
2596
+ repoRoot: metadata.repoRoot,
2597
+ branch: metadata.branch,
2598
+ agentProvider: metadata.agentProvider,
2599
+ agentSessionKey: metadata.agentSessionKey
2600
+ }
2601
+ );
2602
+ }
2603
+ async run() {
2604
+ console.log("Vector Bridge Service");
2605
+ console.log(
2606
+ ` Device: ${this.config.displayName} (${this.config.deviceId})`
2607
+ );
2608
+ console.log(` Convex: ${this.config.convexUrl}`);
2609
+ console.log(` PID: ${process.pid}`);
2610
+ console.log("");
2611
+ if (!existsSync3(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
2612
+ writeFileSync(PID_FILE, String(process.pid));
2613
+ try {
2614
+ this.terminalPeer = new TerminalPeerManager({
2615
+ deviceId: this.config.deviceId,
2616
+ deviceSecret: this.config.deviceSecret,
2617
+ convexUrl: this.config.convexUrl,
2618
+ tunnelHost: this.config.tunnelHost
2619
+ });
2620
+ console.log(
2621
+ ` Terminal: ready${this.config.tunnelHost ? ` (tunnel: ${this.config.tunnelHost})` : ""}`
2622
+ );
2623
+ } catch (e) {
2624
+ console.error(
2625
+ ` WebRTC: failed (${e instanceof Error ? e.message : "unknown"})`
2626
+ );
2627
+ }
2628
+ console.log("");
2629
+ await this.heartbeat();
2630
+ await this.reportProcesses();
2631
+ await this.refreshLiveActivities();
2632
+ console.log(`[${ts2()}] Service running. Ctrl+C to stop.
2633
+ `);
2634
+ this.timers.push(
2635
+ setInterval(() => {
2636
+ this.heartbeat().catch(
2637
+ (e) => console.error(`[${ts2()}] Heartbeat error:`, e.message)
2638
+ );
2639
+ }, HEARTBEAT_INTERVAL_MS)
2640
+ );
2641
+ this.timers.push(
2642
+ setInterval(() => {
2643
+ this.pollCommands().catch(
2644
+ (e) => console.error(`[${ts2()}] Command poll error:`, e.message)
2645
+ );
2646
+ }, COMMAND_POLL_INTERVAL_MS)
2647
+ );
2648
+ this.timers.push(
2649
+ setInterval(() => {
2650
+ this.refreshLiveActivities().catch(
2651
+ (e) => console.error(`[${ts2()}] Live activity sync error:`, e.message)
2652
+ );
2653
+ }, LIVE_ACTIVITY_SYNC_INTERVAL_MS)
2654
+ );
2655
+ this.timers.push(
2656
+ setInterval(() => {
2657
+ this.reportProcesses().catch(
2658
+ (e) => console.error(`[${ts2()}] Discovery error:`, e.message)
2659
+ );
2660
+ }, PROCESS_DISCOVERY_INTERVAL_MS)
2661
+ );
2662
+ const shutdown = () => {
2663
+ console.log(`
2664
+ [${ts2()}] Shutting down...`);
2665
+ for (const t of this.timers) clearInterval(t);
2666
+ this.terminalPeer?.stop();
2667
+ try {
2668
+ unlinkSync(PID_FILE);
2669
+ } catch {
2670
+ }
2671
+ try {
2672
+ writeLiveActivitiesCache([]);
2673
+ } catch {
2674
+ }
2675
+ process.exit(0);
2676
+ };
2677
+ process.on("SIGINT", shutdown);
2678
+ process.on("SIGTERM", shutdown);
2679
+ await new Promise(() => {
2680
+ });
2681
+ }
2682
+ async handleMessageCommand(cmd) {
2683
+ if (!cmd.liveActivityId) {
2684
+ throw new Error("Message command is missing liveActivityId");
2685
+ }
2686
+ const payload = cmd.payload;
2687
+ const body = payload?.body?.trim();
2688
+ if (!body) {
2689
+ throw new Error("Message command is missing a body");
2690
+ }
2691
+ const process9 = cmd.process;
2692
+ console.log(` > "${truncateForLog(body)}"`);
2693
+ if (cmd.workSession?.tmuxPaneId) {
2694
+ sendTextToTmuxPane(cmd.workSession.tmuxPaneId, body);
2695
+ const attachedSession = cmd.workSession.agentProvider && isBridgeProvider(cmd.workSession.agentProvider) ? await this.attachObservedAgentSession(
2696
+ cmd.workSession.agentProvider,
2697
+ cmd.workSession.workspacePath ?? cmd.workSession.cwd ?? process9?.cwd
2698
+ ) : null;
2699
+ await this.postAgentMessage(
2700
+ cmd.liveActivityId,
2701
+ "status",
2702
+ "Sent input to work session terminal"
2703
+ );
2704
+ await this.refreshWorkSessionTerminal(cmd.workSession._id, {
2705
+ tmuxSessionName: cmd.workSession.tmuxSessionName,
2706
+ tmuxWindowName: cmd.workSession.tmuxWindowName,
2707
+ tmuxPaneId: cmd.workSession.tmuxPaneId,
2708
+ cwd: cmd.workSession.cwd,
2709
+ repoRoot: cmd.workSession.repoRoot,
2710
+ branch: cmd.workSession.branch,
2711
+ agentProvider: attachedSession?.process.provider ?? cmd.workSession.agentProvider,
2712
+ agentSessionKey: attachedSession?.process.sessionKey ?? cmd.workSession.agentSessionKey
2713
+ });
2714
+ await this.updateLiveActivity(cmd.liveActivityId, {
2715
+ status: "waiting_for_input",
2716
+ latestSummary: `Input sent to ${cmd.workSession.tmuxPaneId}`,
2717
+ title: cmd.liveActivity?.title,
2718
+ processId: attachedSession?.processId ?? process9?._id
2719
+ });
2720
+ return;
2721
+ }
2722
+ if (!process9 || !process9.supportsInboundMessages || !process9.sessionKey || !process9.cwd || !isBridgeProvider(process9.provider)) {
2723
+ throw new Error("No resumable local session is attached to this issue");
2724
+ }
2725
+ await this.reportProcess({
2726
+ provider: process9.provider,
2727
+ providerLabel: process9.providerLabel ?? providerLabel(process9.provider),
2728
+ sessionKey: process9.sessionKey,
2729
+ cwd: process9.cwd,
2730
+ repoRoot: process9.repoRoot,
2731
+ branch: process9.branch,
2732
+ title: process9.title,
2733
+ model: process9.model,
2734
+ mode: "managed",
2735
+ status: "waiting",
2736
+ supportsInboundMessages: true
2737
+ });
2738
+ await this.updateLiveActivity(cmd.liveActivityId, {
2739
+ status: "active",
2740
+ processId: process9._id,
2741
+ title: cmd.liveActivity?.title ?? process9.title
2742
+ });
2743
+ const result = await resumeProviderSession(
2744
+ process9.provider,
2745
+ process9.sessionKey,
2746
+ process9.cwd,
2747
+ body
2748
+ );
2749
+ const processId = await this.reportProcess(result);
2750
+ if (result.responseText) {
2751
+ await this.postAgentMessage(
2752
+ cmd.liveActivityId,
2753
+ "assistant",
2754
+ result.responseText
2755
+ );
2756
+ console.log(` < "${truncateForLog(result.responseText)}"`);
2757
+ }
2758
+ await this.updateLiveActivity(cmd.liveActivityId, {
2759
+ processId,
2760
+ status: "waiting_for_input",
2761
+ latestSummary: summarizeMessage(result.responseText),
2762
+ title: cmd.liveActivity?.title ?? process9.title
2763
+ });
2764
+ }
2765
+ async handleResizeCommand(cmd) {
2766
+ const payload = cmd.payload;
2767
+ const cols = payload?.cols;
2768
+ const rows = payload?.rows;
2769
+ const paneId = cmd.workSession?.tmuxPaneId;
2770
+ if (!paneId || !cols || !rows) {
2771
+ throw new Error("Resize command missing paneId, cols, or rows");
2772
+ }
2773
+ console.log(` Resize ${paneId} \u2192 ${cols}x${rows}`);
2774
+ resizeTmuxPane(paneId, cols, rows);
2775
+ if (cmd.workSession) {
2776
+ await this.refreshWorkSessionTerminal(cmd.workSession._id, {
2777
+ tmuxSessionName: cmd.workSession.tmuxSessionName,
2778
+ tmuxWindowName: cmd.workSession.tmuxWindowName,
2779
+ tmuxPaneId: paneId,
2780
+ cwd: cmd.workSession.cwd,
2781
+ repoRoot: cmd.workSession.repoRoot,
2782
+ branch: cmd.workSession.branch,
2783
+ agentProvider: cmd.workSession.agentProvider,
2784
+ agentSessionKey: cmd.workSession.agentSessionKey
2785
+ });
2786
+ }
2787
+ }
2788
+ async handleLaunchCommand(cmd) {
2789
+ if (!cmd.liveActivityId) {
2790
+ throw new Error("Launch command is missing liveActivityId");
2791
+ }
2792
+ const payload = cmd.payload;
2793
+ const workspacePath = payload?.workspacePath?.trim();
2794
+ if (!workspacePath) {
2795
+ throw new Error("Launch command is missing workspacePath");
2796
+ }
2797
+ const requestedProvider = payload?.provider;
2798
+ const provider = requestedProvider && isBridgeProvider(requestedProvider) ? requestedProvider : void 0;
2799
+ const issueKey = payload?.issueKey ?? cmd.liveActivity?.issueKey ?? "ISSUE";
2800
+ const issueTitle = payload?.issueTitle ?? cmd.liveActivity?.issueTitle ?? "Untitled issue";
2801
+ const issueDescription = payload?.issueDescription;
2802
+ const prompt2 = buildLaunchPrompt(
2803
+ issueKey,
2804
+ issueTitle,
2805
+ workspacePath,
2806
+ issueDescription
2807
+ );
2808
+ const launchLabel = provider ? providerLabel(provider) : "shell session";
2809
+ const workSessionTitle = `${issueKey}: ${issueTitle}`;
2810
+ await this.updateLiveActivity(cmd.liveActivityId, {
2811
+ status: "active",
2812
+ latestSummary: `Launching ${launchLabel} in ${workspacePath}`,
2813
+ delegatedRunId: payload?.delegatedRunId,
2814
+ launchStatus: "launching",
2815
+ title: workSessionTitle
2816
+ });
2817
+ const tmuxSession = createTmuxWorkSession({
2818
+ workspacePath,
2819
+ issueKey,
2820
+ issueTitle,
2821
+ provider,
2822
+ prompt: prompt2
2823
+ });
2824
+ await this.refreshWorkSessionTerminal(cmd.workSession?._id, {
2825
+ tmuxSessionName: tmuxSession.sessionName,
2826
+ tmuxWindowName: tmuxSession.windowName,
2827
+ tmuxPaneId: tmuxSession.paneId,
2828
+ cwd: workspacePath,
2829
+ repoRoot: workspacePath,
2830
+ branch: currentGitBranch(workspacePath),
2831
+ agentProvider: provider
2832
+ });
2833
+ await this.updateLiveActivity(cmd.liveActivityId, {
2834
+ status: "active",
2835
+ latestSummary: `Running ${launchLabel} in ${tmuxSession.sessionName}`,
2836
+ delegatedRunId: payload?.delegatedRunId,
2837
+ launchStatus: "running",
2838
+ title: workSessionTitle
2839
+ });
2840
+ }
2841
+ async attachObservedAgentSession(provider, workspacePath, sessionsBeforeLaunch = [], paneProcessId) {
2842
+ if (!workspacePath) {
2843
+ return null;
2844
+ }
2845
+ const existingKeys = new Set(
2846
+ sessionsBeforeLaunch.map(sessionIdentityKey).filter(Boolean)
2847
+ );
2848
+ for (let attempt = 0; attempt < 10; attempt += 1) {
2849
+ const observedSessions = listObservedSessionsForWorkspace(
2850
+ provider,
2851
+ workspacePath
2852
+ );
2853
+ const candidate = (paneProcessId ? findObservedSessionInProcessTree(observedSessions, paneProcessId) : void 0) ?? observedSessions.find(
2854
+ (session) => !existingKeys.has(sessionIdentityKey(session))
2855
+ ) ?? (attempt === 9 ? observedSessions[0] : void 0);
2856
+ if (candidate) {
2857
+ const processId = await this.reportProcess(candidate);
2858
+ return {
2859
+ process: candidate,
2860
+ processId
2861
+ };
2862
+ }
2863
+ await sleep(750);
2864
+ }
2865
+ return null;
2866
+ }
2867
+ async reportProcess(process9) {
2868
+ const {
2869
+ provider,
2870
+ providerLabel: providerLabel2,
2871
+ localProcessId,
2872
+ sessionKey,
2873
+ cwd,
2874
+ repoRoot,
2875
+ branch,
2876
+ title,
2877
+ model,
2878
+ tmuxSessionName,
2879
+ tmuxWindowName,
2880
+ tmuxPaneId,
2881
+ mode,
2882
+ status,
2883
+ supportsInboundMessages
2884
+ } = process9;
2885
+ return await this.client.mutation(
2886
+ api.agentBridge.bridgePublic.reportProcess,
2887
+ {
2888
+ deviceId: this.config.deviceId,
2889
+ deviceSecret: this.config.deviceSecret,
2890
+ provider,
2891
+ providerLabel: providerLabel2,
2892
+ localProcessId,
2893
+ sessionKey,
2894
+ cwd,
2895
+ repoRoot,
2896
+ branch,
2897
+ title,
2898
+ model,
2899
+ tmuxSessionName,
2900
+ tmuxWindowName,
2901
+ tmuxPaneId,
2902
+ mode,
2903
+ status,
2904
+ supportsInboundMessages
2905
+ }
2906
+ );
2907
+ }
2908
+ async updateLiveActivity(liveActivityId, args) {
2909
+ await this.client.mutation(
2910
+ api.agentBridge.bridgePublic.updateLiveActivityState,
2911
+ {
2912
+ deviceId: this.config.deviceId,
2913
+ deviceSecret: this.config.deviceSecret,
2914
+ liveActivityId,
2915
+ ...args
2916
+ }
2917
+ );
2918
+ }
2919
+ async postAgentMessage(liveActivityId, role, body) {
2920
+ await this.client.mutation(api.agentBridge.bridgePublic.postAgentMessage, {
2921
+ deviceId: this.config.deviceId,
2922
+ deviceSecret: this.config.deviceSecret,
2923
+ liveActivityId,
2924
+ role,
2925
+ body
2926
+ });
2927
+ }
2928
+ async completeCommand(commandId, status) {
2929
+ await this.client.mutation(api.agentBridge.bridgePublic.completeCommand, {
2930
+ deviceId: this.config.deviceId,
2931
+ deviceSecret: this.config.deviceSecret,
2932
+ commandId,
2933
+ status
2934
+ });
2935
+ }
2936
+ async postCommandError(cmd, errorMessage) {
2937
+ if (cmd.kind === "launch" && cmd.liveActivityId) {
2938
+ const payload = cmd.payload;
2939
+ await this.updateLiveActivity(cmd.liveActivityId, {
2940
+ status: "failed",
2941
+ latestSummary: errorMessage,
2942
+ delegatedRunId: payload?.delegatedRunId,
2943
+ launchStatus: "failed"
2944
+ });
2945
+ await this.postAgentMessage(cmd.liveActivityId, "status", errorMessage);
2946
+ return;
2947
+ }
2948
+ if (cmd.kind === "message" && cmd.liveActivityId) {
2949
+ await this.postAgentMessage(cmd.liveActivityId, "status", errorMessage);
2950
+ await this.updateLiveActivity(cmd.liveActivityId, {
2951
+ status: "waiting_for_input",
2952
+ latestSummary: errorMessage
2953
+ });
2954
+ }
2955
+ }
2956
+ };
2957
+ function createTmuxWorkSession(args) {
2958
+ const slug = sanitizeTmuxName(args.issueKey.toLowerCase());
2959
+ const sessionName = `vector-${slug}-${randomUUID2().slice(0, 8)}`;
2960
+ const windowName = sanitizeTmuxName(
2961
+ args.provider === "codex" ? "codex" : args.provider === "claude_code" ? "claude" : "shell"
2962
+ );
2963
+ execFileSync2("tmux", [
2964
+ "new-session",
2965
+ "-d",
2966
+ "-s",
2967
+ sessionName,
2968
+ "-n",
2969
+ windowName,
2970
+ "-c",
2971
+ args.workspacePath
2972
+ ]);
2973
+ const paneId = execFileSync2(
2974
+ "tmux",
2975
+ [
2976
+ "display-message",
2977
+ "-p",
2978
+ "-t",
2979
+ `${sessionName}:${windowName}.0`,
2980
+ "#{pane_id}"
2981
+ ],
2982
+ { encoding: "utf-8" }
2983
+ ).trim();
2984
+ const paneProcessId = execFileSync2(
2985
+ "tmux",
2986
+ ["display-message", "-p", "-t", paneId, "#{pane_pid}"],
2987
+ { encoding: "utf-8" }
2988
+ ).trim();
2989
+ if (args.provider) {
2990
+ execFileSync2("tmux", [
2991
+ "send-keys",
2992
+ "-t",
2993
+ paneId,
2994
+ buildManagedLaunchCommand(args.provider, args.prompt),
2995
+ "Enter"
2996
+ ]);
2997
+ } else {
2998
+ execFileSync2("tmux", [
2999
+ "send-keys",
3000
+ "-t",
3001
+ paneId,
3002
+ `printf '%s\\n\\n' ${shellQuote(args.prompt)}`,
3003
+ "Enter"
3004
+ ]);
3005
+ }
3006
+ return {
3007
+ sessionName,
3008
+ windowName,
3009
+ paneId,
3010
+ paneProcessId
3011
+ };
3012
+ }
3013
+ function sendTextToTmuxPane(paneId, text2) {
3014
+ execFileSync2("tmux", ["set-buffer", "--", text2]);
3015
+ execFileSync2("tmux", ["paste-buffer", "-t", paneId]);
3016
+ execFileSync2("tmux", ["send-keys", "-t", paneId, "Enter"]);
3017
+ execFileSync2("tmux", ["delete-buffer"]);
3018
+ }
3019
+ function captureTmuxPane(paneId) {
3020
+ return execFileSync2(
3021
+ "tmux",
3022
+ ["capture-pane", "-p", "-e", "-t", paneId, "-S", "-120"],
3023
+ { encoding: "utf-8" }
3024
+ ).trimEnd();
3025
+ }
3026
+ function resizeTmuxPane(paneId, cols, rows) {
3027
+ try {
3028
+ execFileSync2("tmux", [
3029
+ "resize-pane",
3030
+ "-t",
3031
+ paneId,
3032
+ "-x",
3033
+ String(cols),
3034
+ "-y",
3035
+ String(rows)
3036
+ ]);
3037
+ } catch (e) {
3038
+ console.error(`Failed to resize pane ${paneId}:`, e);
3039
+ }
3040
+ }
3041
+ function currentGitBranch(cwd) {
3042
+ try {
3043
+ return execSync2("git rev-parse --abbrev-ref HEAD", {
3044
+ encoding: "utf-8",
3045
+ cwd,
3046
+ timeout: 3e3
3047
+ }).trim();
3048
+ } catch {
3049
+ return void 0;
3050
+ }
3051
+ }
3052
+ function buildManagedLaunchCommand(provider, prompt2) {
3053
+ if (provider === "codex") {
3054
+ return `codex --no-alt-screen -a never ${shellQuote(prompt2)}`;
3055
+ }
3056
+ return `claude --permission-mode bypassPermissions --dangerously-skip-permissions ${shellQuote(prompt2)}`;
3057
+ }
3058
+ function sanitizeTmuxName(value) {
3059
+ return value.replace(/[^a-z0-9_-]+/gi, "-").replace(/^-+|-+$/g, "") || "work";
3060
+ }
3061
+ function shellQuote(value) {
3062
+ return `'${value.replace(/'/g, `'"'"'`)}'`;
3063
+ }
3064
+ async function setupBridgeDevice(client, convexUrl) {
3065
+ const deviceKey = getStableDeviceKey();
3066
+ const displayName = `${process.env.USER ?? "user"}'s ${platform() === "darwin" ? "Mac" : "machine"}`;
3067
+ const result = await client.mutation(
3068
+ api.agentBridge.mutations.registerBridgeDevice,
3069
+ {
3070
+ deviceKey,
3071
+ displayName,
3072
+ hostname: hostname(),
3073
+ platform: platform(),
3074
+ serviceType: "foreground",
3075
+ cliVersion: "0.1.0",
3076
+ capabilities: ["codex", "claude_code"]
3077
+ }
3078
+ );
3079
+ const config = {
3080
+ deviceId: result.deviceId,
3081
+ deviceKey,
3082
+ deviceSecret: result.deviceSecret,
3083
+ userId: result.userId,
3084
+ displayName,
3085
+ convexUrl,
3086
+ registeredAt: (/* @__PURE__ */ new Date()).toISOString()
3087
+ };
3088
+ saveBridgeConfig(config);
3089
+ return config;
3090
+ }
3091
+ function getStableDeviceKey() {
3092
+ const existingConfig = loadBridgeConfig();
3093
+ const existingKey = existingConfig?.deviceKey?.trim();
3094
+ if (existingKey) {
3095
+ persistDeviceKey(existingKey);
3096
+ return existingKey;
3097
+ }
3098
+ if (existsSync3(DEVICE_KEY_FILE)) {
3099
+ const savedKey = readFileSync2(DEVICE_KEY_FILE, "utf-8").trim();
3100
+ if (savedKey) {
3101
+ return savedKey;
3102
+ }
3103
+ }
3104
+ const generatedKey = `${hostname()}-${randomUUID2().slice(0, 8)}`;
3105
+ persistDeviceKey(generatedKey);
3106
+ return generatedKey;
3107
+ }
3108
+ function persistDeviceKey(deviceKey) {
3109
+ if (!existsSync3(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
3110
+ writeFileSync(DEVICE_KEY_FILE, `${deviceKey}
3111
+ `);
3112
+ }
3113
+ function buildLaunchPrompt(issueKey, issueTitle, workspacePath, issueDescription) {
3114
+ const lines = [`You are working on issue ${issueKey}: ${issueTitle}`];
3115
+ if (issueDescription?.trim()) {
3116
+ lines.push("", "Issue description:", issueDescription.trim());
3117
+ }
3118
+ lines.push(
3119
+ "",
3120
+ `The repository is at ${workspacePath}.`,
3121
+ "Do exactly and only what the issue describes \u2014 nothing more, nothing less.",
3122
+ "If anything is unclear or ambiguous, ask clarifying questions before making changes.",
3123
+ 'Do not refactor, clean up, or "improve" code that is not part of the issue scope.'
3124
+ );
3125
+ return lines.join("\n");
3126
+ }
3127
+ function summarizeMessage(message) {
3128
+ if (!message) {
3129
+ return void 0;
3130
+ }
3131
+ return message.length > 120 ? `${message.slice(0, 117).trimEnd()}...` : message;
3132
+ }
3133
+ function truncateForLog(message) {
3134
+ return message.length > 80 ? `${message.slice(0, 77).trimEnd()}...` : message;
3135
+ }
3136
+ function listObservedSessionsForWorkspace(provider, workspacePath) {
3137
+ return discoverAttachableSessions().filter(
3138
+ (session) => session.provider === provider && matchesWorkspacePath(session, workspacePath)
3139
+ ).sort(compareLocalSessionRecency);
3140
+ }
3141
+ function findObservedSessionInProcessTree(sessions, paneProcessId) {
3142
+ const descendantIds = listDescendantProcessIds(paneProcessId);
3143
+ if (descendantIds.size === 0) {
3144
+ return void 0;
3145
+ }
3146
+ return sessions.find(
3147
+ (session) => session.localProcessId ? descendantIds.has(session.localProcessId) : false
3148
+ );
3149
+ }
3150
+ function listDescendantProcessIds(rootPid) {
3151
+ const descendants = /* @__PURE__ */ new Set([rootPid]);
3152
+ try {
3153
+ const output = execSync2("ps -axo pid=,ppid=", {
3154
+ encoding: "utf-8",
3155
+ timeout: 3e3
3156
+ });
3157
+ const parentToChildren = /* @__PURE__ */ new Map();
3158
+ for (const line of output.split("\n").map((value) => value.trim()).filter(Boolean)) {
3159
+ const [pid, ppid] = line.split(/\s+/, 2);
3160
+ if (!pid || !ppid) {
3161
+ continue;
3162
+ }
3163
+ const children = parentToChildren.get(ppid) ?? [];
3164
+ children.push(pid);
3165
+ parentToChildren.set(ppid, children);
3166
+ }
3167
+ const queue = [rootPid];
3168
+ while (queue.length > 0) {
3169
+ const currentPid = queue.shift();
3170
+ if (!currentPid) {
3171
+ continue;
3172
+ }
3173
+ for (const childPid of parentToChildren.get(currentPid) ?? []) {
3174
+ if (descendants.has(childPid)) {
3175
+ continue;
3176
+ }
3177
+ descendants.add(childPid);
3178
+ queue.push(childPid);
3179
+ }
3180
+ }
3181
+ } catch {
3182
+ return descendants;
3183
+ }
3184
+ return descendants;
3185
+ }
3186
+ function matchesWorkspacePath(session, workspacePath) {
3187
+ const normalizedWorkspace = normalizePath(workspacePath);
3188
+ const candidatePaths = [session.cwd, session.repoRoot].filter((value) => Boolean(value)).map(normalizePath);
3189
+ return candidatePaths.some((path3) => path3 === normalizedWorkspace);
3190
+ }
3191
+ function normalizePath(value) {
3192
+ return value.replace(/\/+$/, "");
3193
+ }
3194
+ function sessionIdentityKey(session) {
3195
+ return [
3196
+ session.provider,
3197
+ session.sessionKey,
3198
+ session.localProcessId,
3199
+ session.cwd
3200
+ ].filter(Boolean).join("::");
3201
+ }
3202
+ function compareLocalSessionRecency(a, b) {
3203
+ return Number(b.localProcessId ?? 0) - Number(a.localProcessId ?? 0);
3204
+ }
3205
+ function sleep(ms) {
3206
+ return new Promise((resolve) => setTimeout(resolve, ms));
3207
+ }
3208
+ function isBridgeProvider(provider) {
3209
+ return provider === "codex" || provider === "claude_code";
3210
+ }
3211
+ function providerLabel(provider) {
3212
+ if (provider === "codex") {
3213
+ return "Codex";
3214
+ }
3215
+ if (provider === "claude_code") {
3216
+ return "Claude";
3217
+ }
3218
+ return "Vector CLI";
3219
+ }
3220
+ function installLaunchAgent(vcliPath) {
3221
+ if (platform() !== "darwin") {
3222
+ console.error("LaunchAgent is macOS only. Use systemd on Linux.");
3223
+ return;
3224
+ }
3225
+ const programArguments = getLaunchAgentProgramArguments(vcliPath);
3226
+ const environmentVariables = [
3227
+ " <key>PATH</key>",
3228
+ " <string>/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>",
3229
+ ...process.env.VECTOR_HOME?.trim() ? [
3230
+ " <key>VECTOR_HOME</key>",
3231
+ ` <string>${process.env.VECTOR_HOME.trim()}</string>`
3232
+ ] : []
3233
+ ].join("\n");
3234
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
3235
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3236
+ <plist version="1.0">
3237
+ <dict>
3238
+ <key>Label</key>
3239
+ <string>${LAUNCHAGENT_LABEL}</string>
3240
+ <key>ProgramArguments</key>
3241
+ ${programArguments}
3242
+ <key>RunAtLoad</key>
3243
+ <true/>
3244
+ <key>KeepAlive</key>
3245
+ <true/>
3246
+ <key>StandardOutPath</key>
3247
+ <string>${CONFIG_DIR}/bridge.log</string>
3248
+ <key>StandardErrorPath</key>
3249
+ <string>${CONFIG_DIR}/bridge.err.log</string>
3250
+ <key>EnvironmentVariables</key>
3251
+ <dict>
3252
+ ${environmentVariables}
3253
+ </dict>
3254
+ </dict>
3255
+ </plist>`;
3256
+ if (!existsSync3(LAUNCHAGENT_DIR)) {
3257
+ mkdirSync(LAUNCHAGENT_DIR, { recursive: true });
3258
+ }
3259
+ removeLegacyMenuBarLaunchAgent();
3260
+ writeFileSync(LAUNCHAGENT_PLIST, plist);
3261
+ console.log(`Installed LaunchAgent: ${LAUNCHAGENT_PLIST}`);
3262
+ }
3263
+ function getLaunchAgentProgramArguments(vcliPath) {
3264
+ const args = resolveCliInvocation(vcliPath);
3265
+ return [
3266
+ "<array>",
3267
+ ...args.map((arg) => ` <string>${arg}</string>`),
3268
+ " <string>service</string>",
3269
+ " <string>run</string>",
3270
+ " </array>"
3271
+ ].join("\n");
3272
+ }
3273
+ function resolveCliInvocation(vcliPath) {
3274
+ if (vcliPath.endsWith(".js")) {
3275
+ return [process.execPath, vcliPath];
3276
+ }
3277
+ if (vcliPath.endsWith(".ts")) {
3278
+ const tsxPath = join2(
3279
+ import.meta.dirname ?? process.cwd(),
3280
+ "..",
3281
+ "..",
3282
+ "..",
3283
+ "node_modules",
3284
+ ".bin",
3285
+ "tsx"
3286
+ );
3287
+ if (existsSync3(tsxPath)) {
3288
+ return [tsxPath, vcliPath];
3289
+ }
3290
+ }
3291
+ return [vcliPath];
3292
+ }
3293
+ function loadLaunchAgent() {
3294
+ if (runLaunchctl(["bootstrap", launchctlGuiDomain(), LAUNCHAGENT_PLIST])) {
3295
+ runLaunchctl([
3296
+ "kickstart",
3297
+ "-k",
3298
+ `${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`
3299
+ ]);
3300
+ console.log(
3301
+ "LaunchAgent loaded. Bridge will start automatically on login."
3302
+ );
3303
+ return;
3304
+ }
3305
+ if (runLaunchctl([
3306
+ "kickstart",
3307
+ "-k",
3308
+ `${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`
3309
+ ]) || runLaunchctl(["load", LAUNCHAGENT_PLIST])) {
3310
+ console.log(
3311
+ "LaunchAgent loaded. Bridge will start automatically on login."
3312
+ );
3313
+ return;
3314
+ }
3315
+ console.error("Failed to load LaunchAgent");
3316
+ }
3317
+ function unloadLaunchAgent() {
3318
+ if (runLaunchctl(["bootout", `${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`]) || runLaunchctl(["bootout", launchctlGuiDomain(), LAUNCHAGENT_PLIST]) || runLaunchctl(["unload", LAUNCHAGENT_PLIST])) {
3319
+ console.log("LaunchAgent unloaded.");
3320
+ return true;
3321
+ }
3322
+ console.error("Failed to unload LaunchAgent (may not be loaded)");
3323
+ return false;
3324
+ }
3325
+ function uninstallLaunchAgent() {
3326
+ unloadLaunchAgent();
3327
+ removeLegacyMenuBarLaunchAgent();
3328
+ try {
3329
+ unlinkSync(LAUNCHAGENT_PLIST);
3330
+ console.log("LaunchAgent removed.");
3331
+ } catch {
3332
+ }
3333
+ }
3334
+ var MENUBAR_PID_FILE = join2(CONFIG_DIR, "menubar.pid");
3335
+ function removeLegacyMenuBarLaunchAgent() {
3336
+ if (platform() !== "darwin" || !existsSync3(LEGACY_MENUBAR_LAUNCHAGENT_PLIST)) {
3337
+ return;
3338
+ }
3339
+ try {
3340
+ execSync2(`launchctl unload ${LEGACY_MENUBAR_LAUNCHAGENT_PLIST}`, {
3341
+ stdio: "pipe"
3342
+ });
3343
+ } catch {
3344
+ }
3345
+ try {
3346
+ unlinkSync(LEGACY_MENUBAR_LAUNCHAGENT_PLIST);
3347
+ } catch {
3348
+ }
3349
+ }
3350
+ function launchctlGuiDomain() {
3351
+ const uid = typeof process.getuid === "function" ? process.getuid() : typeof process.geteuid === "function" ? process.geteuid() : 0;
3352
+ return `gui/${uid}`;
3353
+ }
3354
+ function runLaunchctl(args) {
3355
+ try {
3356
+ execFileSync2("launchctl", args, {
3357
+ stdio: "ignore"
3358
+ });
3359
+ return true;
3360
+ } catch {
3361
+ return false;
3362
+ }
3363
+ }
3364
+ function findCliEntrypoint() {
3365
+ const candidates = [
3366
+ join2(import.meta.dirname ?? "", "index.js"),
3367
+ join2(import.meta.dirname ?? "", "index.ts"),
3368
+ join2(import.meta.dirname ?? "", "..", "dist", "index.js")
3369
+ ];
3370
+ for (const p of candidates) {
3371
+ if (existsSync3(p)) return p;
3372
+ }
3373
+ return null;
3374
+ }
3375
+ function getCurrentCliInvocation() {
3376
+ const entrypoint = findCliEntrypoint();
3377
+ if (!entrypoint) {
3378
+ return null;
3379
+ }
3380
+ return resolveCliInvocation(entrypoint);
3381
+ }
3382
+ function findMenuBarExecutable() {
3383
+ const candidates = [
3384
+ join2(
3385
+ import.meta.dirname ?? "",
3386
+ "..",
3387
+ "native",
3388
+ "VectorMenuBar.app",
3389
+ "Contents",
3390
+ "MacOS",
3391
+ "VectorMenuBar"
3392
+ ),
3393
+ join2(
3394
+ import.meta.dirname ?? "",
3395
+ "native",
3396
+ "VectorMenuBar.app",
3397
+ "Contents",
3398
+ "MacOS",
3399
+ "VectorMenuBar"
3400
+ )
3401
+ ];
3402
+ for (const p of candidates) {
3403
+ if (existsSync3(p)) {
3404
+ return p;
3405
+ }
3406
+ }
3407
+ return null;
3408
+ }
3409
+ function isKnownMenuBarProcess(pid) {
3410
+ try {
3411
+ const command = execSync2(`ps -p ${pid} -o args=`, {
3412
+ encoding: "utf-8",
3413
+ timeout: 3e3
3414
+ });
3415
+ return command.includes("menubar.js") || command.includes("menubar.ts") || command.includes("VectorMenuBar");
3416
+ } catch {
3417
+ return false;
3418
+ }
3419
+ }
3420
+ function killExistingMenuBar() {
3421
+ if (existsSync3(MENUBAR_PID_FILE)) {
3422
+ try {
3423
+ const pid = Number(readFileSync2(MENUBAR_PID_FILE, "utf-8").trim());
3424
+ if (Number.isFinite(pid) && pid > 0 && isKnownMenuBarProcess(pid)) {
3425
+ process.kill(pid, "SIGTERM");
3426
+ }
3427
+ } catch {
3428
+ }
3429
+ try {
3430
+ unlinkSync(MENUBAR_PID_FILE);
3431
+ } catch {
3432
+ }
3433
+ }
3434
+ }
3435
+ async function launchMenuBar() {
3436
+ if (platform() !== "darwin") return;
3437
+ removeLegacyMenuBarLaunchAgent();
3438
+ const executable = findMenuBarExecutable();
3439
+ const cliInvocation = getCurrentCliInvocation();
3440
+ if (!executable || !cliInvocation) return;
3441
+ killExistingMenuBar();
3442
+ try {
3443
+ const { spawn: spawnChild } = await import("child_process");
3444
+ const child = spawnChild(executable, [], {
3445
+ detached: true,
3446
+ stdio: "ignore",
3447
+ env: {
3448
+ ...process.env,
3449
+ VECTOR_CLI_COMMAND: cliInvocation[0],
3450
+ VECTOR_CLI_ARGS_JSON: JSON.stringify(cliInvocation.slice(1))
3451
+ }
3452
+ });
3453
+ child.unref();
3454
+ if (child.pid) {
3455
+ writeFileSync(MENUBAR_PID_FILE, String(child.pid));
3456
+ }
3457
+ } catch {
277
3458
  }
278
3459
  }
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
- );
3460
+ function stopMenuBar() {
3461
+ killExistingMenuBar();
287
3462
  }
288
- async function clearSession(profile = "default") {
289
- await rm(getSessionPath(profile), { force: true });
3463
+ function getBridgeStatus() {
3464
+ const config = loadBridgeConfig();
3465
+ if (!config) return { configured: false, running: false, starting: false };
3466
+ let running = false;
3467
+ let starting = false;
3468
+ let pid;
3469
+ if (existsSync3(PID_FILE)) {
3470
+ const pidStr = readFileSync2(PID_FILE, "utf-8").trim();
3471
+ pid = Number(pidStr);
3472
+ try {
3473
+ process.kill(pid, 0);
3474
+ running = true;
3475
+ } catch {
3476
+ running = false;
3477
+ }
3478
+ }
3479
+ if (!running && platform() === "darwin") {
3480
+ starting = runLaunchctl(["print", `${launchctlGuiDomain()}/${LAUNCHAGENT_LABEL}`]) || runLaunchctl(["list", LAUNCHAGENT_LABEL]);
3481
+ }
3482
+ return { configured: true, running, starting, pid, config };
290
3483
  }
291
- function createEmptySession() {
292
- return {
293
- version: 1,
294
- cookies: {}
295
- };
3484
+ function stopBridge(options) {
3485
+ if (options?.includeMenuBar) {
3486
+ killExistingMenuBar();
3487
+ }
3488
+ try {
3489
+ writeLiveActivitiesCache([]);
3490
+ } catch {
3491
+ }
3492
+ if (!existsSync3(PID_FILE)) return false;
3493
+ const pid = Number(readFileSync2(PID_FILE, "utf-8").trim());
3494
+ try {
3495
+ process.kill(pid, "SIGTERM");
3496
+ return true;
3497
+ } catch {
3498
+ return false;
3499
+ }
3500
+ }
3501
+ function ts2() {
3502
+ return (/* @__PURE__ */ new Date()).toLocaleTimeString();
296
3503
  }
297
3504
 
298
- // ../../src/cli/index.ts
3505
+ // src/index.ts
3506
+ import { platform as osPlatform } from "os";
299
3507
  loadEnv({ path: ".env.local", override: false });
300
3508
  loadEnv({ path: ".env", override: false });
301
3509
  var cliApi = {
@@ -404,7 +3612,103 @@ function buildPaginationOptions(limit, cursor) {
404
3612
  function normalizeMatch(value) {
405
3613
  return value?.trim().toLowerCase();
406
3614
  }
407
- async function fetchConvexUrl(appUrl) {
3615
+ function parseDate(value) {
3616
+ const ms = Date.parse(value);
3617
+ if (!Number.isFinite(ms)) {
3618
+ throw new Error(`Invalid date: ${value}`);
3619
+ }
3620
+ return ms;
3621
+ }
3622
+ function applyListFilters(items, options) {
3623
+ let result = [...items];
3624
+ if (options.createdAfter) {
3625
+ const threshold = parseDate(options.createdAfter);
3626
+ result = result.filter(
3627
+ (item) => typeof item.createdAt === "number" && item.createdAt >= threshold
3628
+ );
3629
+ }
3630
+ if (options.createdBefore) {
3631
+ const threshold = parseDate(options.createdBefore);
3632
+ result = result.filter(
3633
+ (item) => typeof item.createdAt === "number" && item.createdAt <= threshold
3634
+ );
3635
+ }
3636
+ if (options.updatedAfter) {
3637
+ const threshold = parseDate(options.updatedAfter);
3638
+ result = result.filter(
3639
+ (item) => typeof item.lastEditedAt === "number" && item.lastEditedAt >= threshold
3640
+ );
3641
+ }
3642
+ if (options.updatedBefore) {
3643
+ const threshold = parseDate(options.updatedBefore);
3644
+ result = result.filter(
3645
+ (item) => typeof item.lastEditedAt === "number" && item.lastEditedAt <= threshold
3646
+ );
3647
+ }
3648
+ if (options.sort) {
3649
+ const field = options.sort;
3650
+ const desc = options.order?.toLowerCase() === "desc";
3651
+ result.sort((a, b) => {
3652
+ const aVal = a[field];
3653
+ const bVal = b[field];
3654
+ if (aVal == null && bVal == null) return 0;
3655
+ if (aVal == null) return 1;
3656
+ if (bVal == null) return -1;
3657
+ if (typeof aVal === "number" && typeof bVal === "number")
3658
+ return desc ? bVal - aVal : aVal - bVal;
3659
+ return desc ? String(bVal).localeCompare(String(aVal)) : String(aVal).localeCompare(String(bVal));
3660
+ });
3661
+ }
3662
+ if (options.limit) {
3663
+ const limit = Number(options.limit);
3664
+ if (Number.isFinite(limit) && limit > 0) {
3665
+ result = result.slice(0, limit);
3666
+ }
3667
+ }
3668
+ return result;
3669
+ }
3670
+ function addEntityUrls(items, appUrl, orgSlug, entityType) {
3671
+ return items.map((item) => {
3672
+ let path3;
3673
+ switch (entityType) {
3674
+ case "issues":
3675
+ path3 = `/${orgSlug}/issues/${item.key}`;
3676
+ break;
3677
+ case "projects":
3678
+ path3 = `/${orgSlug}/projects/${item.key}`;
3679
+ break;
3680
+ case "teams":
3681
+ path3 = `/${orgSlug}/teams/${item.key}`;
3682
+ break;
3683
+ case "documents":
3684
+ path3 = `/${orgSlug}/documents/${item.id}`;
3685
+ break;
3686
+ case "folders":
3687
+ path3 = `/${orgSlug}/documents/folders/${item.id}`;
3688
+ break;
3689
+ }
3690
+ return { ...item, url: `${appUrl}${path3}` };
3691
+ });
3692
+ }
3693
+ function normalizeAppUrl(raw) {
3694
+ let url = raw.trim();
3695
+ if (!/^https?:\/\//i.test(url)) {
3696
+ const isLocal = /^localhost(:\d+)?/i.test(url) || /^127\.0\.0\.1(:\d+)?/.test(url);
3697
+ url = isLocal ? `http://${url}` : `https://${url}`;
3698
+ }
3699
+ return url.replace(/\/+$/, "");
3700
+ }
3701
+ async function resolveAppUrl(raw) {
3702
+ const url = normalizeAppUrl(raw);
3703
+ try {
3704
+ const response = await fetch(url, { method: "HEAD", redirect: "follow" });
3705
+ const resolved = new URL(response.url).origin;
3706
+ return resolved;
3707
+ } catch {
3708
+ return url;
3709
+ }
3710
+ }
3711
+ async function fetchAppConfig(appUrl) {
408
3712
  try {
409
3713
  const url = new URL("/api/config", appUrl).toString();
410
3714
  const response = await fetch(url);
@@ -413,21 +3717,29 @@ async function fetchConvexUrl(appUrl) {
413
3717
  }
414
3718
  const data = await response.json();
415
3719
  if (data.convexUrl) {
416
- return data.convexUrl;
3720
+ return {
3721
+ convexUrl: data.convexUrl,
3722
+ tunnelHost: data.tunnelHost || void 0
3723
+ };
417
3724
  }
418
3725
  } catch {
419
3726
  }
420
- return "http://127.0.0.1:3210";
3727
+ return { convexUrl: "http://127.0.0.1:3210" };
3728
+ }
3729
+ async function fetchConvexUrl(appUrl) {
3730
+ const config = await fetchAppConfig(appUrl);
3731
+ return config.convexUrl;
421
3732
  }
422
3733
  async function getRuntime(command) {
423
3734
  const options = command.optsWithGlobals();
424
- const profile = options.profile ?? "default";
3735
+ const profile = options.profile ?? await readDefaultProfile();
425
3736
  const session = await readSession(profile);
426
3737
  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;
3738
+ const appUrl = await resolveAppUrl(requiredString(appUrlSource, "app URL"));
3739
+ let convexUrl = options.convexUrl ?? session?.convexUrl;
429
3740
  if (!convexUrl) {
430
- convexUrl = await fetchConvexUrl(appUrl);
3741
+ const fetchedUrl = await fetchConvexUrl(appUrl);
3742
+ convexUrl = fetchedUrl !== "http://127.0.0.1:3210" ? fetchedUrl : process.env.NEXT_PUBLIC_CONVEX_URL ?? process.env.CONVEX_URL ?? fetchedUrl;
431
3743
  }
432
3744
  return {
433
3745
  appUrl,
@@ -439,7 +3751,7 @@ async function getRuntime(command) {
439
3751
  };
440
3752
  }
441
3753
  function requireSession(runtime) {
442
- if (!runtime.session || Object.keys(runtime.session.cookies).length === 0) {
3754
+ if (!runtime.session || Object.keys(runtime.session.cookies).length === 0 && !runtime.session.bearerToken) {
443
3755
  throw new Error("Not logged in. Run `vcli auth login` first.");
444
3756
  }
445
3757
  return runtime.session;
@@ -453,6 +3765,80 @@ function requireOrg(runtime, explicit) {
453
3765
  }
454
3766
  return orgSlug;
455
3767
  }
3768
+ function hostForAppUrl(appUrl) {
3769
+ if (!appUrl) {
3770
+ return void 0;
3771
+ }
3772
+ try {
3773
+ const url = new URL(appUrl);
3774
+ return url.port ? `${url.hostname}:${url.port}` : url.hostname;
3775
+ } catch {
3776
+ return void 0;
3777
+ }
3778
+ }
3779
+ function decodeSessionClaims(session) {
3780
+ const jwt = session?.cookies?.["__Secure-better-auth.convex_jwt"];
3781
+ if (!jwt) {
3782
+ return {};
3783
+ }
3784
+ const parts = jwt.split(".");
3785
+ if (parts.length < 2) {
3786
+ return {};
3787
+ }
3788
+ let payload = parts[1].replace(/-/g, "+").replace(/_/g, "/");
3789
+ while (payload.length % 4 !== 0) {
3790
+ payload += "=";
3791
+ }
3792
+ try {
3793
+ const decoded = JSON.parse(
3794
+ Buffer.from(payload, "base64").toString("utf8")
3795
+ );
3796
+ return {
3797
+ email: decoded.email,
3798
+ userId: decoded.sub ?? decoded.userId
3799
+ };
3800
+ } catch {
3801
+ return {};
3802
+ }
3803
+ }
3804
+ function buildMenuSessionInfo(session) {
3805
+ const claims = decodeSessionClaims(session);
3806
+ return {
3807
+ orgSlug: session?.activeOrgSlug ?? "oss-lab",
3808
+ appUrl: session?.appUrl,
3809
+ appDomain: hostForAppUrl(session?.appUrl),
3810
+ email: claims.email,
3811
+ userId: claims.userId
3812
+ };
3813
+ }
3814
+ function parseAgentProvider(value) {
3815
+ if (value === "codex" || value === "claude_code" || value === "vector_cli") {
3816
+ return value;
3817
+ }
3818
+ throw new Error("provider must be one of: codex, claude_code, vector_cli");
3819
+ }
3820
+ function isBridgeDeviceAuthError(error) {
3821
+ if (!error || typeof error !== "object") {
3822
+ return false;
3823
+ }
3824
+ const maybeData = error.data;
3825
+ return maybeData === "INVALID_DEVICE_SECRET" || maybeData === "DEVICE_NOT_FOUND";
3826
+ }
3827
+ async function validateStoredBridgeConfig(config) {
3828
+ const client = new ConvexHttpClient3(config.convexUrl);
3829
+ try {
3830
+ await client.mutation(api.agentBridge.bridgePublic.heartbeat, {
3831
+ deviceId: config.deviceId,
3832
+ deviceSecret: config.deviceSecret
3833
+ });
3834
+ return true;
3835
+ } catch (error) {
3836
+ if (isBridgeDeviceAuthError(error)) {
3837
+ return false;
3838
+ }
3839
+ throw error;
3840
+ }
3841
+ }
456
3842
  async function getClient(command) {
457
3843
  const runtime = await getRuntime(command);
458
3844
  const session = requireSession(runtime);
@@ -463,6 +3849,43 @@ async function getClient(command) {
463
3849
  );
464
3850
  return { client, runtime, session };
465
3851
  }
3852
+ async function ensureBridgeConfig(command) {
3853
+ let config = loadBridgeConfig();
3854
+ try {
3855
+ const runtime = await getRuntime(command);
3856
+ const session = requireSession(runtime);
3857
+ const client = await createConvexClient(
3858
+ session,
3859
+ runtime.appUrl,
3860
+ runtime.convexUrl
3861
+ );
3862
+ const user = await runQuery(client, api.users.currentUser);
3863
+ if (!user) {
3864
+ throw new Error("Not logged in. Run `vcli auth login` first.");
3865
+ }
3866
+ const backendDevice = config ? await runQuery(client, api.agentBridge.queries.getDevice, {
3867
+ deviceId: config.deviceId
3868
+ }) : null;
3869
+ const needsRegistration = !config || config.userId !== user._id || config.convexUrl !== runtime.convexUrl || !backendDevice || !await validateStoredBridgeConfig(config);
3870
+ if (needsRegistration) {
3871
+ config = await setupBridgeDevice(client, runtime.convexUrl);
3872
+ }
3873
+ if (!config) {
3874
+ throw new Error("Bridge device is not configured.");
3875
+ }
3876
+ const appConfig = await fetchAppConfig(runtime.appUrl);
3877
+ if (appConfig.tunnelHost) {
3878
+ config.tunnelHost = appConfig.tunnelHost;
3879
+ }
3880
+ saveBridgeConfig(config);
3881
+ return config;
3882
+ } catch (error) {
3883
+ if (config) {
3884
+ return config;
3885
+ }
3886
+ throw error;
3887
+ }
3888
+ }
466
3889
  async function resolveMemberId(client, orgSlug, ref) {
467
3890
  const members = await runQuery(
468
3891
  client,
@@ -638,10 +4061,19 @@ async function parseEstimatedTimes(client, orgSlug, value) {
638
4061
  return estimatedTimes;
639
4062
  }
640
4063
  var program = new Command();
641
- program.name("vcli").description("Vector CLI").showHelpAfterError().option(
4064
+ function readPackageVersionSync() {
4065
+ try {
4066
+ const dir = import.meta.dirname ?? dirname(fileURLToPath2(import.meta.url));
4067
+ const raw = readFileSync3(join3(dir, "..", "package.json"), "utf8");
4068
+ return JSON.parse(raw).version ?? "unknown";
4069
+ } catch {
4070
+ return "unknown";
4071
+ }
4072
+ }
4073
+ program.name("vcli").description("Vector CLI").version(readPackageVersionSync(), "-v, --version").showHelpAfterError().option(
642
4074
  "--app-url <url>",
643
4075
  "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");
4076
+ ).option("--convex-url <url>", "Convex deployment URL").option("--org <slug>", "Organization slug override").option("--profile <name>", "CLI profile name").option("--json", "Output JSON");
645
4077
  var authCommand = program.command("auth").description("Authentication");
646
4078
  authCommand.command("signup").option("--email <email>", "Email address").option("--username <username>", "Username").option("--password <password>", "Password").action(async (options, command) => {
647
4079
  const runtime = await getRuntime(command);
@@ -682,19 +4114,48 @@ authCommand.command("signup").option("--email <email>", "Email address").option(
682
4114
  runtime.json
683
4115
  );
684
4116
  });
685
- authCommand.command("login [identifier]").option("--password <password>", "Password").action(async (identifier, options, command) => {
4117
+ authCommand.command("login [identifier]").option("--password <password>", "Password (uses device flow if omitted)").action(async (identifier, options, command) => {
686
4118
  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
4119
  let session = createEmptySession();
690
4120
  session.appUrl = runtime.appUrl;
691
4121
  session.convexUrl = runtime.convexUrl;
692
- session = await loginWithPassword(
693
- session,
694
- runtime.appUrl,
695
- loginId,
696
- password
697
- );
4122
+ const usePassword = Boolean(identifier || options.password);
4123
+ if (usePassword) {
4124
+ const loginId = identifier?.trim() || await prompt("Email or username: ");
4125
+ const password = options.password?.trim() || await promptSecret("Password: ");
4126
+ session = await loginWithPassword(
4127
+ session,
4128
+ runtime.appUrl,
4129
+ loginId,
4130
+ password
4131
+ );
4132
+ } else {
4133
+ const deviceResp = await requestDeviceCode(runtime.appUrl, "vcli");
4134
+ const verifyUrl = `${runtime.appUrl}/device?user_code=${deviceResp.user_code}`;
4135
+ console.log();
4136
+ console.log(` Open this URL in your browser to log in:`);
4137
+ console.log();
4138
+ console.log(` ${verifyUrl}`);
4139
+ console.log();
4140
+ console.log(` Or go to ${runtime.appUrl}/device and enter code:`);
4141
+ console.log();
4142
+ console.log(` ${deviceResp.user_code}`);
4143
+ console.log();
4144
+ const open2 = await Promise.resolve().then(() => (init_open(), open_exports)).then((m) => m.default).catch(() => null);
4145
+ if (open2) {
4146
+ await open2(verifyUrl).catch(() => {
4147
+ });
4148
+ }
4149
+ console.log(" Waiting for authorization...");
4150
+ session = await pollDeviceToken(
4151
+ session,
4152
+ runtime.appUrl,
4153
+ deviceResp.device_code,
4154
+ "vcli",
4155
+ deviceResp.interval,
4156
+ deviceResp.expires_in
4157
+ );
4158
+ }
698
4159
  const authState = await fetchAuthSession(session, runtime.appUrl);
699
4160
  session = authState.session;
700
4161
  const client = await createConvexClient(
@@ -735,6 +4196,38 @@ authCommand.command("whoami").action(async (_options, command) => {
735
4196
  runtime.json
736
4197
  );
737
4198
  });
4199
+ authCommand.command("profiles").action(async (_options, command) => {
4200
+ const options = command.optsWithGlobals();
4201
+ const explicitProfile = options.profile?.trim();
4202
+ const defaultProfile = await readDefaultProfile();
4203
+ const profiles = await listProfiles();
4204
+ const activeProfile = explicitProfile || defaultProfile;
4205
+ printOutput(
4206
+ {
4207
+ activeProfile,
4208
+ defaultProfile,
4209
+ profiles
4210
+ },
4211
+ Boolean(options.json)
4212
+ );
4213
+ });
4214
+ authCommand.command("use-profile <name>").action(async (name, _options, command) => {
4215
+ const options = command.optsWithGlobals();
4216
+ const profile = name.trim();
4217
+ if (!profile) {
4218
+ throw new Error("Profile name is required.");
4219
+ }
4220
+ await writeDefaultProfile(profile);
4221
+ const session = await readSession(profile);
4222
+ printOutput(
4223
+ {
4224
+ ok: true,
4225
+ defaultProfile: profile,
4226
+ hasSession: session !== null
4227
+ },
4228
+ Boolean(options.json)
4229
+ );
4230
+ });
738
4231
  var orgCommand = program.command("org").description("Organizations");
739
4232
  orgCommand.command("list").action(async (_options, command) => {
740
4233
  const { client, runtime } = await getClient(command);
@@ -1065,6 +4558,75 @@ permissionCommand.command("check-many <permissions>").option("--team <teamKey>")
1065
4558
  printOutput(result, runtime.json);
1066
4559
  });
1067
4560
  var activityCommand = program.command("activity").description("Activity feed");
4561
+ activityCommand.command("list").description(
4562
+ "List org-wide activity with optional filters by entity type, event type, and time range"
4563
+ ).option(
4564
+ "--entity-type <type>",
4565
+ "Filter by entity type: issue, project, team, document"
4566
+ ).option(
4567
+ "--event-type <type>",
4568
+ "Filter by event type (e.g. issue_created, issue_priority_changed)"
4569
+ ).option(
4570
+ "--since <datetime>",
4571
+ "Start of time range (ISO date or shorthand: today, yesterday, 7d, 30d)"
4572
+ ).option(
4573
+ "--until <datetime>",
4574
+ "End of time range (ISO date or shorthand: today, now)"
4575
+ ).option("--limit <n>").option("--cursor <cursor>").action(async (options, command) => {
4576
+ const { client, runtime } = await getClient(command);
4577
+ const orgSlug = requireOrg(runtime);
4578
+ function parseTimeArg(value, bound) {
4579
+ if (!value) return void 0;
4580
+ const now = /* @__PURE__ */ new Date();
4581
+ const startOfToday = new Date(
4582
+ now.getFullYear(),
4583
+ now.getMonth(),
4584
+ now.getDate()
4585
+ );
4586
+ const endOfToday = new Date(
4587
+ now.getFullYear(),
4588
+ now.getMonth(),
4589
+ now.getDate(),
4590
+ 23,
4591
+ 59,
4592
+ 59,
4593
+ 999
4594
+ );
4595
+ switch (value) {
4596
+ case "now":
4597
+ return now.getTime();
4598
+ case "today":
4599
+ return bound === "start" ? startOfToday.getTime() : endOfToday.getTime();
4600
+ case "yesterday":
4601
+ return bound === "start" ? startOfToday.getTime() - 864e5 : startOfToday.getTime() - 1;
4602
+ default: {
4603
+ const daysMatch = value.match(/^(\d+)d$/);
4604
+ if (daysMatch) {
4605
+ return now.getTime() - Number(daysMatch[1]) * 864e5;
4606
+ }
4607
+ const parsed = new Date(value).getTime();
4608
+ if (Number.isNaN(parsed)) {
4609
+ throw new Error(`Invalid time value: ${value}`);
4610
+ }
4611
+ return parsed;
4612
+ }
4613
+ }
4614
+ }
4615
+ const result = await runQuery(
4616
+ client,
4617
+ api.activities.queries.listOrgActivity,
4618
+ {
4619
+ orgSlug,
4620
+ entityType: options.entityType ?? void 0,
4621
+ eventType: options.eventType ?? void 0,
4622
+ since: parseTimeArg(options.since, "start"),
4623
+ until: parseTimeArg(options.until, "end"),
4624
+ limit: optionalNumber(options.limit, "limit") ?? void 0,
4625
+ cursor: options.cursor ?? void 0
4626
+ }
4627
+ );
4628
+ printOutput(result, runtime.json);
4629
+ });
1068
4630
  activityCommand.command("project <projectKey>").option("--limit <n>").option("--cursor <cursor>").action(async (projectKey, options, command) => {
1069
4631
  const { client, runtime } = await getClient(command);
1070
4632
  const orgSlug = requireOrg(runtime);
@@ -1521,13 +5083,14 @@ adminCommand.command("sync-disposable-domains").action(async (_options, command)
1521
5083
  printOutput(result, runtime.json);
1522
5084
  });
1523
5085
  var teamCommand = program.command("team").description("Teams");
1524
- teamCommand.command("list [slug]").option("--limit <n>").action(async (slug, options, command) => {
5086
+ 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
5087
  const { client, runtime } = await getClient(command);
1526
5088
  const orgSlug = requireOrg(runtime, slug);
1527
- const result = await runAction(client, cliApi.listTeams, {
1528
- orgSlug,
1529
- limit: options.limit ? Number(options.limit) : void 0
5089
+ const raw = await runAction(client, cliApi.listTeams, {
5090
+ orgSlug
1530
5091
  });
5092
+ const filtered = applyListFilters(raw, options);
5093
+ const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "teams");
1531
5094
  printOutput(result, runtime.json);
1532
5095
  });
1533
5096
  teamCommand.command("get <teamKey>").action(async (teamKey, _options, command) => {
@@ -1621,14 +5184,15 @@ teamCommand.command("set-lead <teamKey> <member>").action(async (teamKey, member
1621
5184
  printOutput(result, runtime.json);
1622
5185
  });
1623
5186
  var projectCommand = program.command("project").description("Projects");
1624
- projectCommand.command("list [slug]").option("--team <teamKey>").option("--limit <n>").action(async (slug, options, command) => {
5187
+ 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
5188
  const { client, runtime } = await getClient(command);
1626
5189
  const orgSlug = requireOrg(runtime, slug);
1627
- const result = await runAction(client, cliApi.listProjects, {
5190
+ const raw = await runAction(client, cliApi.listProjects, {
1628
5191
  orgSlug,
1629
- teamKey: options.team,
1630
- limit: options.limit ? Number(options.limit) : void 0
5192
+ teamKey: options.team
1631
5193
  });
5194
+ const filtered = applyListFilters(raw, options);
5195
+ const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "projects");
1632
5196
  printOutput(result, runtime.json);
1633
5197
  });
1634
5198
  projectCommand.command("get <projectKey>").action(async (projectKey, _options, command) => {
@@ -1728,15 +5292,17 @@ projectCommand.command("set-lead <projectKey> <member>").action(async (projectKe
1728
5292
  printOutput(result, runtime.json);
1729
5293
  });
1730
5294
  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) => {
5295
+ 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
5296
  const { client, runtime } = await getClient(command);
1733
5297
  const orgSlug = requireOrg(runtime, slug);
1734
- const result = await runAction(client, cliApi.listIssues, {
5298
+ const raw = await runAction(client, cliApi.listIssues, {
1735
5299
  orgSlug,
1736
5300
  projectKey: options.project,
1737
5301
  teamKey: options.team,
1738
- limit: options.limit ? Number(options.limit) : void 0
5302
+ assigneeName: options.assignee
1739
5303
  });
5304
+ const filtered = applyListFilters(raw, options);
5305
+ const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "issues");
1740
5306
  printOutput(result, runtime.json);
1741
5307
  });
1742
5308
  issueCommand.command("get <issueKey>").action(async (issueKey, _options, command) => {
@@ -1933,15 +5499,40 @@ issueCommand.command("comment <issueKey>").requiredOption("--body <body>").actio
1933
5499
  });
1934
5500
  printOutput(result, runtime.json);
1935
5501
  });
5502
+ 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) => {
5503
+ const { client, runtime } = await getClient(command);
5504
+ const orgSlug = requireOrg(runtime);
5505
+ await runAction(client, api.github.actions.linkArtifactByUrl, {
5506
+ orgSlug,
5507
+ issueKey,
5508
+ url
5509
+ });
5510
+ printOutput({ success: true, issueKey, url }, runtime.json);
5511
+ });
1936
5512
  var documentCommand = program.command("document").description("Documents");
1937
- documentCommand.command("list [slug]").option("--folder-id <id>").option("--limit <n>").action(async (slug, options, command) => {
5513
+ 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(
5514
+ "--updated-after <date>",
5515
+ "Filter: last edited on or after date (ISO)"
5516
+ ).option(
5517
+ "--updated-before <date>",
5518
+ "Filter: last edited on or before date (ISO)"
5519
+ ).option(
5520
+ "--sort <field>",
5521
+ "Sort by field (e.g. createdAt, title, lastEditedAt)"
5522
+ ).option("--order <direction>", "Sort order: asc or desc (default: asc)").action(async (slug, options, command) => {
1938
5523
  const { client, runtime } = await getClient(command);
1939
5524
  const orgSlug = requireOrg(runtime, slug);
1940
- const result = await runAction(client, cliApi.listDocuments, {
5525
+ const raw = await runAction(client, cliApi.listDocuments, {
1941
5526
  orgSlug,
1942
- folderId: options.folderId,
1943
- limit: options.limit ? Number(options.limit) : void 0
5527
+ folderId: options.folderId
1944
5528
  });
5529
+ const filtered = applyListFilters(raw, options);
5530
+ const result = addEntityUrls(
5531
+ filtered,
5532
+ runtime.appUrl,
5533
+ orgSlug,
5534
+ "documents"
5535
+ );
1945
5536
  printOutput(result, runtime.json);
1946
5537
  });
1947
5538
  documentCommand.command("get <documentId>").action(async (documentId, _options, command) => {
@@ -2007,10 +5598,12 @@ documentCommand.command("delete <documentId>").action(async (documentId, _option
2007
5598
  printOutput(result, runtime.json);
2008
5599
  });
2009
5600
  var folderCommand = program.command("folder").description("Document folders");
2010
- folderCommand.command("list [slug]").action(async (slug, _options, command) => {
5601
+ 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
5602
  const { client, runtime } = await getClient(command);
2012
5603
  const orgSlug = requireOrg(runtime, slug);
2013
- const result = await runAction(client, cliApi.listFolders, { orgSlug });
5604
+ const raw = await runAction(client, cliApi.listFolders, { orgSlug });
5605
+ const filtered = applyListFilters(raw, options);
5606
+ const result = addEntityUrls(filtered, runtime.appUrl, orgSlug, "folders");
2014
5607
  printOutput(result, runtime.json);
2015
5608
  });
2016
5609
  folderCommand.command("create").requiredOption("--name <name>").option("--description <description>").option("--icon <icon>").option("--color <color>").action(async (options, command) => {
@@ -2050,6 +5643,372 @@ folderCommand.command("delete <folderId>").action(async (folderId, _options, com
2050
5643
  });
2051
5644
  printOutput(result, runtime.json);
2052
5645
  });
5646
+ var VECTOR_HOME = process.env.VECTOR_HOME?.trim() || `${process.env.HOME ?? "~"}/.vector`;
5647
+ var serviceCommand = program.command("service").description("Manage the local bridge service");
5648
+ serviceCommand.command("start").description("Start the bridge service via LaunchAgent (macOS) or foreground").action(async (_options, command) => {
5649
+ const existing = getBridgeStatus();
5650
+ if (existing.running) {
5651
+ console.log(`Bridge is already running (PID ${existing.pid}).`);
5652
+ return;
5653
+ }
5654
+ const { spinner } = await import("@clack/prompts");
5655
+ const s = spinner();
5656
+ s.start("Ensuring device registration...");
5657
+ const config = await ensureBridgeConfig(command);
5658
+ s.stop(`Device ready: ${config.displayName}`);
5659
+ if (osPlatform() === "darwin") {
5660
+ s.start("Starting bridge service...");
5661
+ const vcliPath = process.argv[1] ?? "vcli";
5662
+ installLaunchAgent(vcliPath);
5663
+ loadLaunchAgent();
5664
+ s.stop("Bridge service started.");
5665
+ } else {
5666
+ console.log(
5667
+ "Starting bridge in foreground (use systemd for background)..."
5668
+ );
5669
+ const bridge = new BridgeService(config);
5670
+ await bridge.run();
5671
+ }
5672
+ });
5673
+ serviceCommand.command("run").description("Run the bridge service in the foreground (used by LaunchAgent)").action(async (_options, command) => {
5674
+ const config = await ensureBridgeConfig(command);
5675
+ if (osPlatform() === "darwin") {
5676
+ await launchMenuBar();
5677
+ }
5678
+ const bridge = new BridgeService(config);
5679
+ await bridge.run();
5680
+ });
5681
+ serviceCommand.command("stop").description("Stop the bridge service").action(() => {
5682
+ let unloaded = false;
5683
+ if (osPlatform() === "darwin") {
5684
+ unloaded = unloadLaunchAgent();
5685
+ }
5686
+ if (stopBridge() || unloaded) {
5687
+ console.log("Bridge stopped.");
5688
+ } else if (osPlatform() !== "darwin") {
5689
+ console.log("Bridge is not running.");
5690
+ } else {
5691
+ console.log("Bridge is not running.");
5692
+ }
5693
+ });
5694
+ serviceCommand.command("status").description("Show bridge service status").action((_options, command) => {
5695
+ const status = getBridgeStatus();
5696
+ if (!status.configured) {
5697
+ console.log("Bridge not configured. Run: vcli service start");
5698
+ return;
5699
+ }
5700
+ console.log("Vector Bridge");
5701
+ console.log(
5702
+ ` Device: ${status.config.displayName} (${status.config.deviceId})`
5703
+ );
5704
+ console.log(` User: ${status.config.userId}`);
5705
+ const statusLabel = status.running ? `Running (PID ${status.pid})` : status.starting ? "Starting..." : "Not running";
5706
+ console.log(` Status: ${statusLabel}`);
5707
+ console.log(` Config: ${VECTOR_HOME}/bridge.json`);
5708
+ });
5709
+ serviceCommand.command("menu-state").description("Return JSON state for the macOS tray").action(async (_options, command) => {
5710
+ const status = getBridgeStatus();
5711
+ const globalOptions = command.optsWithGlobals();
5712
+ const profile = globalOptions.profile ?? await readDefaultProfile();
5713
+ const session = await readSession(profile);
5714
+ const profiles = await listProfiles();
5715
+ const defaultProfile = await readDefaultProfile();
5716
+ let workspaces = [];
5717
+ let workSessions = [];
5718
+ let detectedSessions = [];
5719
+ try {
5720
+ const runtime = await getRuntime(command);
5721
+ if (runtime.session && status.config?.deviceId) {
5722
+ const client = await createConvexClient(
5723
+ runtime.session,
5724
+ runtime.appUrl,
5725
+ runtime.convexUrl
5726
+ );
5727
+ workspaces = await runQuery(
5728
+ client,
5729
+ api.agentBridge.queries.listDeviceWorkspaces,
5730
+ {
5731
+ deviceId: status.config.deviceId
5732
+ }
5733
+ );
5734
+ workSessions = await runQuery(
5735
+ client,
5736
+ api.agentBridge.queries.listDeviceWorkSessions,
5737
+ {
5738
+ deviceId: status.config.deviceId
5739
+ }
5740
+ );
5741
+ const devices = await runQuery(
5742
+ client,
5743
+ api.agentBridge.queries.listProcessesForAttach,
5744
+ {}
5745
+ );
5746
+ const currentDevice = devices.find(
5747
+ (entry) => entry.device._id === status.config?.deviceId
5748
+ );
5749
+ detectedSessions = currentDevice?.processes ?? [];
5750
+ }
5751
+ } catch {
5752
+ workspaces = [];
5753
+ workSessions = [];
5754
+ detectedSessions = [];
5755
+ }
5756
+ printOutput(
5757
+ {
5758
+ configured: status.configured,
5759
+ running: status.running,
5760
+ starting: status.starting,
5761
+ pid: status.pid,
5762
+ config: status.config,
5763
+ sessionInfo: buildMenuSessionInfo(session),
5764
+ activeProfile: profile,
5765
+ defaultProfile,
5766
+ profiles,
5767
+ workspaces,
5768
+ workSessions,
5769
+ detectedSessions
5770
+ },
5771
+ Boolean(globalOptions.json)
5772
+ );
5773
+ });
5774
+ serviceCommand.command("set-default-workspace").description("Set the default workspace for this device").requiredOption("--workspace-id <id>").action(async (options, command) => {
5775
+ const { client, runtime } = await getClient(command);
5776
+ const workspaceId = await runMutation(
5777
+ client,
5778
+ api.agentBridge.mutations.setDefaultWorkspace,
5779
+ {
5780
+ workspaceId: options.workspaceId
5781
+ }
5782
+ );
5783
+ printOutput({ ok: true, workspaceId }, runtime.json);
5784
+ });
5785
+ serviceCommand.command("search-issues <query>").description("Search issues for tray attach actions").option("--limit <n>").action(async (query, options, command) => {
5786
+ const { client, runtime } = await getClient(command);
5787
+ const orgSlug = requireOrg(runtime);
5788
+ const result = await runQuery(client, api.search.queries.searchEntities, {
5789
+ orgSlug,
5790
+ query,
5791
+ limit: optionalNumber(options.limit, "limit") ?? 8
5792
+ });
5793
+ printOutput(result.issues ?? [], runtime.json);
5794
+ });
5795
+ 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) => {
5796
+ const { client, runtime } = await getClient(command);
5797
+ const liveActivityId = await runMutation(
5798
+ client,
5799
+ api.agentBridge.mutations.attachLiveActivity,
5800
+ {
5801
+ issueId: options.issueId,
5802
+ deviceId: options.deviceId,
5803
+ processId: options.processId,
5804
+ provider: parseAgentProvider(options.provider),
5805
+ title: options.title?.trim() || void 0
5806
+ }
5807
+ );
5808
+ printOutput({ ok: true, liveActivityId }, runtime.json);
5809
+ });
5810
+ serviceCommand.command("install").description("Install the bridge as a system service (macOS LaunchAgent)").action(async (_options, command) => {
5811
+ if (osPlatform() !== "darwin") {
5812
+ console.error("Service install is currently macOS only (LaunchAgent).");
5813
+ console.error("On Linux, use systemd --user manually for now.");
5814
+ return;
5815
+ }
5816
+ const { spinner } = await import("@clack/prompts");
5817
+ const s = spinner();
5818
+ s.start("Ensuring device registration...");
5819
+ const config = await ensureBridgeConfig(command);
5820
+ s.stop(`Device ready: ${config.displayName}`);
5821
+ s.start("Installing LaunchAgent...");
5822
+ const vcliPath = process.argv[1] ?? "vcli";
5823
+ installLaunchAgent(vcliPath);
5824
+ s.stop("LaunchAgent installed");
5825
+ s.start("Starting bridge service...");
5826
+ loadLaunchAgent();
5827
+ s.stop("Bridge service started");
5828
+ console.log("");
5829
+ console.log(
5830
+ "Bridge installed and running. Will start automatically on login."
5831
+ );
5832
+ });
5833
+ serviceCommand.command("uninstall").description("Stop the bridge and uninstall the system service").action(() => {
5834
+ stopBridge({ includeMenuBar: true });
5835
+ uninstallLaunchAgent();
5836
+ stopMenuBar();
5837
+ console.log("Bridge stopped and service uninstalled.");
5838
+ });
5839
+ serviceCommand.command("logs").description("Show bridge service logs").action(async () => {
5840
+ const fs7 = await import("fs");
5841
+ const p = await import("path");
5842
+ const logPath = p.join(VECTOR_HOME, "bridge.log");
5843
+ if (fs7.existsSync(logPath)) {
5844
+ const content = fs7.readFileSync(logPath, "utf-8");
5845
+ const lines = content.split("\n");
5846
+ console.log(lines.slice(-50).join("\n"));
5847
+ } else {
5848
+ console.log(`No log file found at ${logPath}`);
5849
+ }
5850
+ });
5851
+ serviceCommand.command("enable").description("Enable bridge to start at login (macOS LaunchAgent)").action(async () => {
5852
+ if (osPlatform() !== "darwin") {
5853
+ console.error("Login item is macOS only.");
5854
+ return;
5855
+ }
5856
+ const vcliPath = process.argv[1] ?? "vcli";
5857
+ installLaunchAgent(vcliPath);
5858
+ loadLaunchAgent();
5859
+ console.log("Bridge will start automatically on login.");
5860
+ });
5861
+ serviceCommand.command("disable").description("Disable bridge from starting at login").action(() => {
5862
+ uninstallLaunchAgent();
5863
+ stopMenuBar();
5864
+ console.log("Bridge will no longer start at login.");
5865
+ });
5866
+ var bridgeCommand = program.command("bridge").description("Start/stop the local agent bridge");
5867
+ bridgeCommand.command("start").description("Register device, install service, and start the bridge").action(async (_options, command) => {
5868
+ const existingConfig = loadBridgeConfig();
5869
+ const config = await ensureBridgeConfig(command);
5870
+ if (!existingConfig || existingConfig.deviceId !== config.deviceId || existingConfig.userId !== config.userId) {
5871
+ console.log(
5872
+ `Device registered: ${config.displayName} (${config.deviceId})`
5873
+ );
5874
+ }
5875
+ if (osPlatform() === "darwin") {
5876
+ const vcliPath = process.argv[1] ?? "vcli";
5877
+ installLaunchAgent(vcliPath);
5878
+ loadLaunchAgent();
5879
+ console.log("\nBridge installed and started as LaunchAgent.");
5880
+ console.log("It will restart automatically on login.");
5881
+ console.log("Run `vcli service status` to check.");
5882
+ } else {
5883
+ console.log("Starting bridge in foreground...");
5884
+ const bridge = new BridgeService(config);
5885
+ await bridge.run();
5886
+ }
5887
+ });
5888
+ bridgeCommand.command("stop").description("Stop the bridge service").action(() => {
5889
+ let unloaded = false;
5890
+ if (osPlatform() === "darwin") {
5891
+ uninstallLaunchAgent();
5892
+ unloaded = true;
5893
+ }
5894
+ if (stopBridge() || unloaded) {
5895
+ console.log("Bridge stopped.");
5896
+ } else {
5897
+ console.log("Bridge is not running.");
5898
+ }
5899
+ });
5900
+ bridgeCommand.command("status").description("Show bridge status").action(() => {
5901
+ const s = getBridgeStatus();
5902
+ if (!s.configured) {
5903
+ console.log("Bridge not configured. Run: vcli bridge start");
5904
+ return;
5905
+ }
5906
+ console.log("Vector Bridge");
5907
+ console.log(` Device: ${s.config.displayName} (${s.config.deviceId})`);
5908
+ console.log(
5909
+ ` Status: ${s.running ? `Running (PID ${s.pid})` : "Not running"}`
5910
+ );
5911
+ });
5912
+ function detectInstallMethod(version) {
5913
+ const execPath = process.argv[1] ?? "";
5914
+ const pkg = `@rehpic/vcli@${version}`;
5915
+ if (execPath.includes(".volta")) {
5916
+ return {
5917
+ method: "volta",
5918
+ command: ["volta", "install", pkg]
5919
+ };
5920
+ }
5921
+ if (execPath.includes("pnpm")) {
5922
+ return {
5923
+ method: "pnpm",
5924
+ command: ["pnpm", "add", "-g", pkg]
5925
+ };
5926
+ }
5927
+ if (execPath.includes("yarn")) {
5928
+ return {
5929
+ method: "yarn",
5930
+ command: ["yarn", "global", "add", pkg]
5931
+ };
5932
+ }
5933
+ return {
5934
+ method: "npm",
5935
+ command: ["npm", "install", "-g", pkg]
5936
+ };
5937
+ }
5938
+ async function checkForUpdate() {
5939
+ try {
5940
+ const { execSync: exec } = await import("child_process");
5941
+ const tagsRaw = exec("npm view @rehpic/vcli dist-tags --json", {
5942
+ encoding: "utf-8",
5943
+ timeout: 1e4
5944
+ }).trim();
5945
+ const tags = JSON.parse(tagsRaw);
5946
+ const latest = tags.latest?.includes("beta") ? tags.beta ?? tags.latest : tags.latest ?? tags.beta ?? "";
5947
+ const pkg = await Promise.resolve().then(() => (init_package(), package_exports));
5948
+ const current = pkg.default?.version ?? pkg.version ?? "0.0.0";
5949
+ return {
5950
+ current,
5951
+ latest,
5952
+ hasUpdate: Boolean(latest) && latest !== current
5953
+ };
5954
+ } catch {
5955
+ return null;
5956
+ }
5957
+ }
5958
+ program.command("update").description("Update the CLI to the latest version").action(async () => {
5959
+ const { spinner, log } = await import("@clack/prompts");
5960
+ const s = spinner();
5961
+ s.start("Checking for updates...");
5962
+ const updateInfo = await checkForUpdate();
5963
+ if (!updateInfo) {
5964
+ s.stop("Could not check for updates.");
5965
+ return;
5966
+ }
5967
+ if (!updateInfo.hasUpdate) {
5968
+ s.stop(`Already on the latest version (${updateInfo.current}).`);
5969
+ return;
5970
+ }
5971
+ s.stop(`Update available: ${updateInfo.current} \u2192 ${updateInfo.latest}`);
5972
+ const install = detectInstallMethod(updateInfo.latest);
5973
+ log.info(`Install method: ${install.method}`);
5974
+ s.start("Stopping bridge service...");
5975
+ const wasRunning = getBridgeStatus().running;
5976
+ if (wasRunning) {
5977
+ stopBridge({ includeMenuBar: true });
5978
+ if (osPlatform() === "darwin") {
5979
+ unloadLaunchAgent();
5980
+ }
5981
+ stopMenuBar();
5982
+ }
5983
+ s.stop(wasRunning ? "Bridge stopped." : "Bridge was not running.");
5984
+ s.start(`Updating via ${install.method}...`);
5985
+ try {
5986
+ const { execFileSync: exec } = await import("child_process");
5987
+ exec(install.command[0], install.command.slice(1), {
5988
+ stdio: "inherit",
5989
+ timeout: 12e4
5990
+ });
5991
+ s.stop("CLI updated successfully.");
5992
+ } catch (err) {
5993
+ s.stop("Update failed.");
5994
+ log.error(`Run manually: ${install.command.join(" ")}`);
5995
+ return;
5996
+ }
5997
+ if (wasRunning) {
5998
+ s.start("Restarting bridge service...");
5999
+ try {
6000
+ const { execFileSync: exec } = await import("child_process");
6001
+ exec("vcli", ["service", "start"], {
6002
+ stdio: "inherit",
6003
+ timeout: 3e4
6004
+ });
6005
+ s.stop("Bridge restarted.");
6006
+ } catch {
6007
+ s.stop("Could not auto-restart. Run: vcli service start");
6008
+ }
6009
+ }
6010
+ log.success(`Updated to v${updateInfo.latest}`);
6011
+ });
2053
6012
  async function main() {
2054
6013
  await program.parseAsync(process.argv);
2055
6014
  }