@opencode/browse 0.0.11-dev.76 → 0.0.11-dev.77
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/{cli-qpkh40gh.mjs → cli-mx6tbg2m.mjs} +63 -52
- package/dist/cli.mjs +30 -19
- package/dist/{helpers-kp0j46jt.mjs → helpers-hgm1z9h5.mjs} +2 -2
- package/dist/{index-0dcypq31.mjs → index-yzz55kxm.mjs} +1 -1
- package/dist/{main-brv9dhy5.mjs → main-1fdejpga.mjs} +9 -9
- package/dist/{main-ajza8egc.mjs → main-6chyyr6j.mjs} +44 -39
- package/dist/{main-rt6g5418.mjs → main-8z9d979q.mjs} +15 -15
- package/dist/{setup-j76yv51b.mjs → main-b7g6460c.mjs} +3608 -4406
- package/dist/{main-gevbt7h7.mjs → main-csnx585b.mjs} +151 -151
- package/dist/{main-nqmm7pdz.mjs → main-cymarjp4.mjs} +47 -47
- package/dist/main-j2ehvkhk.mjs +465 -0
- package/dist/main-r3a6053j.mjs +157 -0
- package/dist/main-s7017yah.mjs +161 -0
- package/dist/main-sjrzyg3x.mjs +73 -0
- package/dist/main-vgzr4689.mjs +61 -0
- package/dist/{main-eej5z0y5.mjs → main-zq79yb8r.mjs} +6 -6
- package/dist/main-zya5ttbr.mjs +4 -0
- package/dist/{mcp-sy8qgkyr.mjs → mcp-h0qcxhqc.mjs} +138 -137
- package/dist/migrate-pgckfkg5.mjs +233 -0
- package/dist/{relay-ateyg5ax.mjs → relay-gafgjtav.mjs} +128 -123
- package/dist/runtime-update-p2pnfdy1.mjs +156 -0
- package/dist/setup-fhhjnx9r.mjs +956 -0
- package/dist/{skill-text-x7sccp6h.mjs → skill-text-6p6scqwe.mjs} +2 -2
- package/dist/{supervisor-0rvjpf4e.mjs → supervisor-06t66v4t.mjs} +38 -17
- package/dist/{update-rbd2025v.mjs → update-7hagfdc0.mjs} +3 -3
- package/dist/{version-4cjr3wpp.mjs → version-hhcvk9wm.mjs} +1 -1
- package/package.json +1 -1
- package/skills/browse/SKILL.md +2 -2
- package/dist/main-7wgmq04v.mjs +0 -303
- package/dist/main-exnm62gg.mjs +0 -4
- package/dist/main-hm4fcpfz.mjs +0 -131
- package/dist/main-rn7hdcq2.mjs +0 -805
- package/dist/runtime-update-70gqzynp.mjs +0 -200
|
@@ -0,0 +1,956 @@
|
|
|
1
|
+
import {
|
|
2
|
+
agentLabels,
|
|
3
|
+
agentNames,
|
|
4
|
+
agentName,
|
|
5
|
+
callingAgent,
|
|
6
|
+
agentLocations,
|
|
7
|
+
editAgentConfig,
|
|
8
|
+
settings,
|
|
9
|
+
isCancel,
|
|
10
|
+
T$1,
|
|
11
|
+
S_BAR,
|
|
12
|
+
S_BAR_END,
|
|
13
|
+
S_CHECKBOX_SELECTED,
|
|
14
|
+
S_CHECKBOX_INACTIVE,
|
|
15
|
+
symbol,
|
|
16
|
+
limitOptions,
|
|
17
|
+
intro,
|
|
18
|
+
outro,
|
|
19
|
+
note,
|
|
20
|
+
spinner,
|
|
21
|
+
STORE_IDS,
|
|
22
|
+
STORE_URL,
|
|
23
|
+
MCP_NAME,
|
|
24
|
+
LEGACY_MCP_NAME,
|
|
25
|
+
home,
|
|
26
|
+
configRoot,
|
|
27
|
+
paths,
|
|
28
|
+
files,
|
|
29
|
+
fromSource,
|
|
30
|
+
checkoutExtensionDirs,
|
|
31
|
+
dev,
|
|
32
|
+
unpackedFolder,
|
|
33
|
+
connectedMessage,
|
|
34
|
+
pairedOfflineMessage,
|
|
35
|
+
manualPair,
|
|
36
|
+
findOnPath,
|
|
37
|
+
findOpencode,
|
|
38
|
+
readJson,
|
|
39
|
+
tilde,
|
|
40
|
+
rail,
|
|
41
|
+
log,
|
|
42
|
+
fail,
|
|
43
|
+
installWaitTimeout,
|
|
44
|
+
waitTimeout,
|
|
45
|
+
addToPath,
|
|
46
|
+
removeBinaryInstall,
|
|
47
|
+
oldStoreBuild,
|
|
48
|
+
detectBrowsers,
|
|
49
|
+
parseJson,
|
|
50
|
+
defaultBrowser,
|
|
51
|
+
blockedReason,
|
|
52
|
+
revealFolder,
|
|
53
|
+
systemEffects,
|
|
54
|
+
configFile,
|
|
55
|
+
restartOutdatedRelay,
|
|
56
|
+
mcpServers,
|
|
57
|
+
configureMcp,
|
|
58
|
+
removeMcp,
|
|
59
|
+
legacyBrowserControl,
|
|
60
|
+
removeLegacyHost,
|
|
61
|
+
installRuntime,
|
|
62
|
+
installedRuntime,
|
|
63
|
+
manualMcpEntry
|
|
64
|
+
} from "./main-b7g6460c.mjs";
|
|
65
|
+
import {
|
|
66
|
+
opencodeBrowserBuildId2
|
|
67
|
+
} from "./main-zya5ttbr.mjs";
|
|
68
|
+
import {
|
|
69
|
+
installedBinaryPath,
|
|
70
|
+
oldStoreMarker,
|
|
71
|
+
compiledBinary,
|
|
72
|
+
scriptEntry,
|
|
73
|
+
entryCommand,
|
|
74
|
+
runningEntry,
|
|
75
|
+
cliCommand,
|
|
76
|
+
devExtensionFolder,
|
|
77
|
+
installCommand,
|
|
78
|
+
autoUpdateStatus,
|
|
79
|
+
describeAutoUpdate,
|
|
80
|
+
runCommand
|
|
81
|
+
} from "./main-j2ehvkhk.mjs";
|
|
82
|
+
import"./main-vgzr4689.mjs";
|
|
83
|
+
import {
|
|
84
|
+
pairingCodeTtlMs,
|
|
85
|
+
bundledPairingCodeTtlMs,
|
|
86
|
+
formatPairingCode,
|
|
87
|
+
pairingCodeKey,
|
|
88
|
+
mintPairingCode,
|
|
89
|
+
pendingPairingCodeKeys,
|
|
90
|
+
writeExtensionPairing,
|
|
91
|
+
readBrowserPairings,
|
|
92
|
+
revokeBrowserToken,
|
|
93
|
+
legacyPairingCode,
|
|
94
|
+
removeLegacyPairingCode
|
|
95
|
+
} from "./main-r3a6053j.mjs";
|
|
96
|
+
import {
|
|
97
|
+
unpackedExtensionId,
|
|
98
|
+
extensionProtocolSkew,
|
|
99
|
+
extensionProtocolAdvice
|
|
100
|
+
} from "./main-mrew6jy8.mjs";
|
|
101
|
+
import {
|
|
102
|
+
parseHostname,
|
|
103
|
+
readRelayConfig,
|
|
104
|
+
writeRelayConfig,
|
|
105
|
+
syncDevExtension
|
|
106
|
+
} from "./main-s7017yah.mjs";
|
|
107
|
+
import {
|
|
108
|
+
relayAuthorization
|
|
109
|
+
} from "./main-sjrzyg3x.mjs";
|
|
110
|
+
|
|
111
|
+
// src/setup.ts
|
|
112
|
+
import { mkdirSync as mkdirSync2, rmSync as rmSync2, writeFileSync } from "node:fs";
|
|
113
|
+
import path2 from "node:path";
|
|
114
|
+
|
|
115
|
+
// src/setup/agent-picker.ts
|
|
116
|
+
import { styleText } from "node:util";
|
|
117
|
+
function agentFlags(args) {
|
|
118
|
+
const requested = new Set;
|
|
119
|
+
let all = args.includes("--all-agents");
|
|
120
|
+
let none = false;
|
|
121
|
+
for (let i = 0;i < args.length; i++) {
|
|
122
|
+
if (args[i] !== "-a" && args[i] !== "--agent")
|
|
123
|
+
continue;
|
|
124
|
+
if (!args[i + 1] || args[i + 1].startsWith("-"))
|
|
125
|
+
throw new Error(`${args[i]} needs at least one agent name (or '*' or 'none').`);
|
|
126
|
+
while (args[i + 1] && !args[i + 1].startsWith("-")) {
|
|
127
|
+
const arg = args[++i];
|
|
128
|
+
if (arg === "*") {
|
|
129
|
+
all = true;
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (arg === "none") {
|
|
133
|
+
none = true;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
const name = agentName(arg);
|
|
137
|
+
if (!name)
|
|
138
|
+
throw new Error(`Unknown agent ${JSON.stringify(arg)}. Choose ${agentNames.join(", ")}, or none to add browse to another agent yourself.`);
|
|
139
|
+
requested.add(name);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return { requested: all ? [...agentNames] : [...requested], none: none && !all && !requested.size, yes: args.includes("--yes") || args.includes("-y") };
|
|
143
|
+
}
|
|
144
|
+
function agentPlan(locations, flags, tty, caller, remembered) {
|
|
145
|
+
const detected = locations.filter((a) => a.installed).map((a) => a.name);
|
|
146
|
+
if (flags.none)
|
|
147
|
+
return { picker: false, selected: [] };
|
|
148
|
+
if (flags.requested.length)
|
|
149
|
+
return { picker: false, selected: flags.requested };
|
|
150
|
+
if (caller)
|
|
151
|
+
return { picker: false, selected: [caller] };
|
|
152
|
+
if (flags.yes)
|
|
153
|
+
return { picker: false, selected: detected };
|
|
154
|
+
if (!tty)
|
|
155
|
+
return { picker: false, selected: [] };
|
|
156
|
+
return { picker: true, selected: remembered?.filter((n) => agentNames.includes(n)) ?? detected };
|
|
157
|
+
}
|
|
158
|
+
function agentRow(option, active, selected) {
|
|
159
|
+
const box = selected.includes(option.value) ? styleText("green", S_CHECKBOX_SELECTED) : styleText("dim", S_CHECKBOX_INACTIVE);
|
|
160
|
+
if (active)
|
|
161
|
+
return `${styleText("cyan", "❯")} ${box} ${option.label}`;
|
|
162
|
+
return ` ${box} ${styleText("dim", option.label)}`;
|
|
163
|
+
}
|
|
164
|
+
function agentSummary(labels) {
|
|
165
|
+
return labels.length ? labels.join(", ") : "none";
|
|
166
|
+
}
|
|
167
|
+
async function pickAgents(locations, initial) {
|
|
168
|
+
const ordered = [...locations].sort((a, b) => Number(b.name === "opencode") - Number(a.name === "opencode") || Number(b.installed) - Number(a.installed) || agentLabels[a.name].localeCompare(agentLabels[b.name]));
|
|
169
|
+
const all = ordered.map((a) => ({ value: a.name, label: agentLabels[a.name] }));
|
|
170
|
+
const shown = all.filter((_, i) => ordered[i].installed || initial.includes(ordered[i].name));
|
|
171
|
+
let last = { query: "", list: shown };
|
|
172
|
+
const start = [...initial].sort((a, b) => Number(a === "opencode") - Number(b === "opencode"));
|
|
173
|
+
const prompt = new T$1({
|
|
174
|
+
options() {
|
|
175
|
+
const query = this.userInput.trim().toLowerCase();
|
|
176
|
+
if (query === last.query)
|
|
177
|
+
return last.list;
|
|
178
|
+
last = { query, list: query ? all.filter((o) => fuzzy(query, o.label) || fuzzy(query, o.value)) : shown };
|
|
179
|
+
return last.list;
|
|
180
|
+
},
|
|
181
|
+
filter: () => true,
|
|
182
|
+
multiple: true,
|
|
183
|
+
initialValue: start,
|
|
184
|
+
render() {
|
|
185
|
+
const guide = settings.withGuide;
|
|
186
|
+
const head = `${guide ? `${styleText("gray", S_BAR)}
|
|
187
|
+
` : ""}${symbol(this.state)} Set browse up in these agents for you?`;
|
|
188
|
+
const summary = agentSummary(ordered.filter((agent) => this.selectedValues.includes(agent.name)).map((agent) => agentLabels[agent.name]));
|
|
189
|
+
if (this.state === "submit")
|
|
190
|
+
return `${head}
|
|
191
|
+
${guide ? `${styleText("gray", S_BAR)} ` : ""}${styleText("dim", summary)}`;
|
|
192
|
+
if (this.state === "cancel")
|
|
193
|
+
return `${head}
|
|
194
|
+
${guide ? `${styleText("gray", S_BAR)} ` : ""}${styleText(["strikethrough", "dim"], this.userInput)}`;
|
|
195
|
+
const color = this.state === "error" ? "yellow" : "cyan";
|
|
196
|
+
const rail = guide ? styleText(color, S_BAR) : "";
|
|
197
|
+
const at = guide ? `${rail} ` : "";
|
|
198
|
+
const count = this.filteredOptions.length !== this.options.length ? ` (${this.filteredOptions.length} match${this.filteredOptions.length === 1 ? "" : "es"})` : "";
|
|
199
|
+
const search = this.isNavigating || this.userInput === "" ? styleText("dim", this.userInput) : this.userInputWithCursor;
|
|
200
|
+
const top = [
|
|
201
|
+
...head.split(`
|
|
202
|
+
`),
|
|
203
|
+
`${at}${styleText("dim", "Search:")} ${search}${styleText("dim", count)}`,
|
|
204
|
+
...this.filteredOptions.length === 0 && this.userInput ? [`${at}${styleText("yellow", "No matches found")}`] : [],
|
|
205
|
+
...this.state === "error" ? [`${at}${styleText("yellow", this.error)}`] : []
|
|
206
|
+
];
|
|
207
|
+
const footer = [
|
|
208
|
+
`${at}${styleText("dim", "↑/↓")} to navigate • ${styleText("dim", this.isNavigating ? "Space/Tab:" : "Tab:")} select • ${styleText("dim", "Enter:")} confirm • ${styleText("dim", "Type:")} to search`,
|
|
209
|
+
guide ? styleText(color, S_BAR_END) : ""
|
|
210
|
+
];
|
|
211
|
+
const rows = limitOptions({
|
|
212
|
+
cursor: this.cursor,
|
|
213
|
+
options: this.filteredOptions,
|
|
214
|
+
style: (option, active) => agentRow(option, active, this.selectedValues),
|
|
215
|
+
maxItems: 10,
|
|
216
|
+
columnPadding: guide ? 3 : 0,
|
|
217
|
+
rowPadding: top.length + footer.length
|
|
218
|
+
});
|
|
219
|
+
return [...top, ...rows.map((row) => `${at}${row}`), ...footer].join(`
|
|
220
|
+
`);
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
const result = await prompt.prompt();
|
|
224
|
+
if (isCancel(result) || !result)
|
|
225
|
+
return;
|
|
226
|
+
return ordered.map((a) => a.name).filter((name) => result.includes(name));
|
|
227
|
+
}
|
|
228
|
+
function fuzzy(query, text) {
|
|
229
|
+
let pos = 0;
|
|
230
|
+
for (const c of text.toLowerCase())
|
|
231
|
+
if (query[pos] === c)
|
|
232
|
+
pos++;
|
|
233
|
+
return pos === query.length;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// src/setup/commands.ts
|
|
237
|
+
import { spawnSync } from "node:child_process";
|
|
238
|
+
import { randomUUID } from "node:crypto";
|
|
239
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
|
|
240
|
+
import { networkInterfaces } from "node:os";
|
|
241
|
+
import path from "node:path";
|
|
242
|
+
import { createInterface } from "node:readline/promises";
|
|
243
|
+
|
|
244
|
+
// src/setup/guidance.ts
|
|
245
|
+
function locateExtension(options, effects = systemEffects) {
|
|
246
|
+
const { log } = effects;
|
|
247
|
+
const listing = options.storeUrl ?? STORE_URL;
|
|
248
|
+
if (options.pairedOffline)
|
|
249
|
+
return log(pairedOfflineMessage), "ready";
|
|
250
|
+
if (options.connected)
|
|
251
|
+
return log(connectedMessage), "ready";
|
|
252
|
+
if (!options.env.ssh && options.detections.some((detection) => detection.enabled.length))
|
|
253
|
+
return "ready";
|
|
254
|
+
const off = options.detections.flatMap((detection) => detection.disabled);
|
|
255
|
+
if (off.length) {
|
|
256
|
+
log(`! browse is turned off in ${off.map((match) => `${match.browser.name} (${match.profile.name})`).join(", ")}. Turn it on in the browser's extensions page.`);
|
|
257
|
+
return "off";
|
|
258
|
+
}
|
|
259
|
+
const blocked = options.detections.filter((detection) => detection.blocked).map((detection) => detection.browser.name);
|
|
260
|
+
if (blocked.length)
|
|
261
|
+
log(`! Couldn't check ${blocked.join(", ")} for browse (${blockedReason()})`);
|
|
262
|
+
const target = options.preferred ?? options.detections.find((detection) => !detection.blocked)?.browser;
|
|
263
|
+
const interactive = options.allowOpen && options.env.display && !options.env.ssh;
|
|
264
|
+
const opened = interactive && !blocked.length && (target ? effects.open(target, listing) : effects.openDefault?.(listing));
|
|
265
|
+
log(`Add browse to ${target?.name ?? "your browser"} from the Chrome Web Store${opened ? " (opened)" : ""}: ${listing}`);
|
|
266
|
+
return "guided";
|
|
267
|
+
}
|
|
268
|
+
function pairStoreExtension(options, effects = systemEffects) {
|
|
269
|
+
const ids = options.storeIds ?? STORE_IDS;
|
|
270
|
+
const matches = options.detections.flatMap((detection) => detection.enabled).filter((match) => ids.includes(match.id) && !oldStoreBuild(match));
|
|
271
|
+
const match = matches.find((candidate) => candidate.browser.name === options.preferred?.name) ?? matches[0];
|
|
272
|
+
if (!match)
|
|
273
|
+
return "none";
|
|
274
|
+
const interactive = options.allowOpen && options.env.display && !options.env.ssh;
|
|
275
|
+
if (interactive && effects.open(match.browser, `chrome-extension://${match.id}/welcome.html#code=${options.code()}`, match.profile.dir)) {
|
|
276
|
+
effects.log(`✓ Opened browse in ${match.browser.name} to connect it`);
|
|
277
|
+
return "opened";
|
|
278
|
+
}
|
|
279
|
+
effects.log(`To connect browse in ${match.browser.name}: ${manualPair(options.code())}`);
|
|
280
|
+
return "manual";
|
|
281
|
+
}
|
|
282
|
+
async function waitForExtension(options) {
|
|
283
|
+
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
284
|
+
for (let waited = 0;; waited += options.intervalMs) {
|
|
285
|
+
if (await options.connected())
|
|
286
|
+
return true;
|
|
287
|
+
if (waited >= options.timeoutMs)
|
|
288
|
+
return false;
|
|
289
|
+
await sleep(options.intervalMs);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// src/setup/commands.ts
|
|
294
|
+
var relayBase = () => `http://127.0.0.1:${Number(process.env.OPENCODE_BROWSER_PORT) || 19988}`;
|
|
295
|
+
var relayHeaders = () => {
|
|
296
|
+
try {
|
|
297
|
+
return { authorization: relayAuthorization() };
|
|
298
|
+
} catch {
|
|
299
|
+
return {};
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
function ensureRelay(entry) {
|
|
303
|
+
const [file, ...prefix] = entryCommand(entry);
|
|
304
|
+
const started = spawnSync(file, [...prefix, "session", "list", "--json"], {
|
|
305
|
+
encoding: "utf8",
|
|
306
|
+
timeout: 30000
|
|
307
|
+
});
|
|
308
|
+
if (started.status !== 0)
|
|
309
|
+
fail(started.stderr?.trim() || `Couldn't reach the browse relay: ${started.error?.message || `run ${cliCommand("doctor")}`}`);
|
|
310
|
+
}
|
|
311
|
+
var extensionStatus = (installWaiting = false) => fetch(`${relayBase()}/extension/status`, {
|
|
312
|
+
headers: { ...relayHeaders(), ...installWaiting ? { "x-browse-install": "waiting" } : {} },
|
|
313
|
+
signal: AbortSignal.timeout(3000)
|
|
314
|
+
}).then((response) => response.ok ? response.json() : undefined).catch(() => {
|
|
315
|
+
return;
|
|
316
|
+
});
|
|
317
|
+
async function settledExtensionStatus(entry) {
|
|
318
|
+
let status = await extensionStatus();
|
|
319
|
+
if (!status && Object.keys(readBrowserPairings()).length) {
|
|
320
|
+
ensureRelay(entry);
|
|
321
|
+
status = await extensionStatus();
|
|
322
|
+
}
|
|
323
|
+
for (let attempt = 0;status?.connected === false && attempt < 10; attempt++) {
|
|
324
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
325
|
+
status = await extensionStatus();
|
|
326
|
+
}
|
|
327
|
+
return status;
|
|
328
|
+
}
|
|
329
|
+
async function reloadOutdatedExtension(before, folder) {
|
|
330
|
+
if (before.origin !== `chrome-extension://${unpackedExtensionId}`)
|
|
331
|
+
return "current";
|
|
332
|
+
const bundled = readJson(path.join(folder, "build.json"))?.build;
|
|
333
|
+
if (bundled && before.build === bundled)
|
|
334
|
+
return "current";
|
|
335
|
+
const sent = await fetch(`${relayBase()}/extension/reload`, {
|
|
336
|
+
method: "POST",
|
|
337
|
+
body: "{}",
|
|
338
|
+
headers: { "content-type": "application/json", ...relayHeaders() },
|
|
339
|
+
signal: AbortSignal.timeout(5000)
|
|
340
|
+
}).then((response) => response.ok, () => false);
|
|
341
|
+
if (!sent)
|
|
342
|
+
return "stale";
|
|
343
|
+
for (let attempt = 0;attempt < 20; attempt++) {
|
|
344
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
345
|
+
const after = await extensionStatus();
|
|
346
|
+
if (after?.connected && after.build !== before.build)
|
|
347
|
+
return "reloaded";
|
|
348
|
+
}
|
|
349
|
+
return "stale";
|
|
350
|
+
}
|
|
351
|
+
async function syncDev() {
|
|
352
|
+
if (!dev)
|
|
353
|
+
return;
|
|
354
|
+
try {
|
|
355
|
+
await syncDevExtension(dev, { root: paths.cache });
|
|
356
|
+
} catch (error) {
|
|
357
|
+
fail(`Could not get the dev extension: ${error.message}`);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
function pairUnpacked() {
|
|
361
|
+
const directories = [...checkoutExtensionDirs, ...dev ? [devExtensionFolder(paths.cache)] : []].filter((directory) => existsSync(path.join(directory, "manifest.json")));
|
|
362
|
+
if (directories.length === 0)
|
|
363
|
+
return;
|
|
364
|
+
const code = mintPairingCode(undefined, { ttlMs: bundledPairingCodeTtlMs });
|
|
365
|
+
for (const directory of directories)
|
|
366
|
+
writeExtensionPairing(directory, code);
|
|
367
|
+
}
|
|
368
|
+
async function extension() {
|
|
369
|
+
const folder = unpackedFolder();
|
|
370
|
+
if (!folder) {
|
|
371
|
+
if (!STORE_URL)
|
|
372
|
+
fail("This package doesn't know its Chrome Web Store item. Install a released version (`npx @opencode/browse install`), or set up browse from a checkout.");
|
|
373
|
+
log(`Install browse from the Chrome Web Store: ${STORE_URL}`);
|
|
374
|
+
log(`Then run \`${cliCommand("install")}\` again to pair it.`);
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
await syncDev();
|
|
378
|
+
if (!existsSync(path.join(folder, "manifest.json")))
|
|
379
|
+
fail(`${folder} has no built extension. Run \`${installCommand()}\` first.`);
|
|
380
|
+
pairUnpacked();
|
|
381
|
+
revealFolder(folder);
|
|
382
|
+
log(`Load unpacked from: ${folder}`);
|
|
383
|
+
}
|
|
384
|
+
async function pair(args) {
|
|
385
|
+
mkdirSync(files.dir, { recursive: true });
|
|
386
|
+
if (args[0] === "--list")
|
|
387
|
+
return listPairings();
|
|
388
|
+
if (args[0] === "--revoke")
|
|
389
|
+
return revokePairing(args[1]);
|
|
390
|
+
if (args.length && !(args.length === 2 && args[0] === "--wait-seconds")) {
|
|
391
|
+
log(`Usage: ${cliCommand("pair")} [--wait-seconds <seconds> | --list | --revoke <browser>]`);
|
|
392
|
+
process.exitCode = 1;
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
const timeoutMs = Math.min(waitTimeout(args), pairingCodeTtlMs);
|
|
396
|
+
ensureRelay(readJson(files.settings)?.entry ?? runningEntry());
|
|
397
|
+
const receipt = randomUUID();
|
|
398
|
+
const code = mintPairingCode(undefined, { receipt });
|
|
399
|
+
log(`Pairing code: ${formatPairingCode(code)}`);
|
|
400
|
+
log(`${manualPair(code)} It works once, within ${pairingCodeTtlMs / 60000} minutes.`);
|
|
401
|
+
log(`Waiting up to ${timeoutMs / 1000}s for that browser. Later, \`${cliCommand("pair --list")}\` shows paired browsers.`);
|
|
402
|
+
let paired;
|
|
403
|
+
await waitForExtension({
|
|
404
|
+
timeoutMs,
|
|
405
|
+
intervalMs: 500,
|
|
406
|
+
connected: async () => {
|
|
407
|
+
const match = Object.values(readBrowserPairings()).find((browser) => browser.receipt === receipt && browser.lastSeen !== undefined);
|
|
408
|
+
paired = match?.name ?? match?.id;
|
|
409
|
+
return paired !== undefined;
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
if (paired)
|
|
413
|
+
return log(`✓ Paired ${paired}.`);
|
|
414
|
+
log(`! Pairing not confirmed. For a fresh code run \`${cliCommand("pair")}\`.`);
|
|
415
|
+
process.exitCode = 1;
|
|
416
|
+
}
|
|
417
|
+
function pairedBrowsers() {
|
|
418
|
+
const known = readJson(path.join(files.dir, "browsers.json")) ?? {};
|
|
419
|
+
return Object.entries(readBrowserPairings()).map(([key, entry]) => ({
|
|
420
|
+
key,
|
|
421
|
+
id: known[key]?.id ?? entry.id,
|
|
422
|
+
name: known[key]?.name ?? entry.name,
|
|
423
|
+
pairedAt: entry.pairedAt,
|
|
424
|
+
lastSeen: entry.lastSeen
|
|
425
|
+
}));
|
|
426
|
+
}
|
|
427
|
+
function listPairings() {
|
|
428
|
+
const browsers = pairedBrowsers();
|
|
429
|
+
const date = (time) => time === undefined ? "never" : new Date(time).toLocaleString();
|
|
430
|
+
if (browsers.length === 0)
|
|
431
|
+
log(`No paired browsers. Run \`${cliCommand("pair")}\` for a code.`);
|
|
432
|
+
for (const browser of browsers) {
|
|
433
|
+
log(`${browser.id ?? "(not connected yet)"}${browser.name ? ` ${browser.name}` : ""}`);
|
|
434
|
+
log(` profile ${browser.key}`);
|
|
435
|
+
log(` paired ${date(browser.pairedAt)}`);
|
|
436
|
+
log(` last seen ${date(browser.lastSeen)}`);
|
|
437
|
+
}
|
|
438
|
+
if (legacyPairingCode() !== undefined) {
|
|
439
|
+
log("");
|
|
440
|
+
log("The shared pairing code of an earlier version is still accepted: browsers that still use it get their own key the");
|
|
441
|
+
log(`next time they connect. Once they all show up above, \`${cliCommand("pair --revoke legacy")}\` retires it.`);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
async function revokePairing(target) {
|
|
445
|
+
if (!target) {
|
|
446
|
+
log(`Usage: ${cliCommand("pair --revoke <browser id, name or profile>")} (see \`${cliCommand("pair --list")}\`)`);
|
|
447
|
+
process.exitCode = 1;
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
if (target === "legacy") {
|
|
451
|
+
log(removeLegacyPairingCode() ? "✓ The old shared pairing code is no longer accepted" : "The old shared pairing code was already gone.");
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
const wanted = target.trim().toLowerCase();
|
|
455
|
+
const browser = pairedBrowsers().find((entry) => entry.key === target || entry.id === wanted || entry.name?.toLowerCase() === wanted);
|
|
456
|
+
if (!browser || !revokeBrowserToken(browser.key)) {
|
|
457
|
+
log(`No paired browser "${target}". \`${cliCommand("pair --list")}\` shows them.`);
|
|
458
|
+
process.exitCode = 1;
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
const dropped = await fetch(`${relayBase()}/extension/revoke`, {
|
|
462
|
+
method: "POST",
|
|
463
|
+
body: JSON.stringify({ key: browser.key }),
|
|
464
|
+
headers: { "content-type": "application/json", ...relayHeaders() },
|
|
465
|
+
signal: AbortSignal.timeout(3000)
|
|
466
|
+
}).then(async (response) => response.ok ? (await response.json()).dropped === true : false, () => false);
|
|
467
|
+
log(`✓ Unpaired ${browser.id ?? browser.key}${dropped ? " and disconnected it" : ""}. To use it again, pair it with a new code.`);
|
|
468
|
+
}
|
|
469
|
+
async function set(args) {
|
|
470
|
+
const [key, value] = args;
|
|
471
|
+
const hostname = parseHostname(value);
|
|
472
|
+
if (key !== "hostname" || hostname === undefined) {
|
|
473
|
+
log(`Usage: ${cliCommand("set hostname <127.0.0.1|0.0.0.0>")}`);
|
|
474
|
+
log(" 127.0.0.1 only browsers on this computer can connect (the default)");
|
|
475
|
+
log(" 0.0.0.0 browsers on other computers can connect too, after pairing");
|
|
476
|
+
process.exitCode = 1;
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
writeRelayConfig({ ...readRelayConfig(), hostname });
|
|
480
|
+
log(`✓ hostname is ${hostname}`);
|
|
481
|
+
const running = await fetch(`${relayBase()}/version`, { signal: AbortSignal.timeout(2000) }).then((response) => response.ok, () => false);
|
|
482
|
+
if (running) {
|
|
483
|
+
const [file, ...prefix] = entryCommand(runningEntry());
|
|
484
|
+
const restarted = spawnSync(file, [...prefix, "relay", "restart"], { stdio: "inherit" });
|
|
485
|
+
if (restarted.status !== 0)
|
|
486
|
+
log(`! The relay is still running with the old hostname. Run \`${cliCommand("relay restart --force")}\` to apply it.`);
|
|
487
|
+
}
|
|
488
|
+
if (hostname === "127.0.0.1")
|
|
489
|
+
return;
|
|
490
|
+
const tailscale = Object.values(networkInterfaces()).flat().find((address) => address?.family === "IPv4" && /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./.test(address.address))?.address;
|
|
491
|
+
log("");
|
|
492
|
+
log("In the browser on the other computer, open browse's options (right-click its toolbar button, then Options),");
|
|
493
|
+
log("and under Connection enter:");
|
|
494
|
+
log(` Relay ${tailscale ?? "this computer's address"}`);
|
|
495
|
+
log(` Pairing code ${formatPairingCode(mintPairingCode())} (works once, within ${pairingCodeTtlMs / 60000} minutes; \`${cliCommand("pair")}\` prints another)`);
|
|
496
|
+
log("The connection isn't encrypted by browse: use it over Tailscale or a LAN you trust, not the open internet.");
|
|
497
|
+
}
|
|
498
|
+
async function confirmSecretRemoval(args) {
|
|
499
|
+
const secrets = path.join(files.dir, "secrets");
|
|
500
|
+
const profiles = existsSync(secrets) ? readdirSync(secrets).filter((name) => name.endsWith(".json")) : [];
|
|
501
|
+
if (profiles.length === 0 || args.includes("--yes") || args.includes("-y"))
|
|
502
|
+
return;
|
|
503
|
+
const notice = `Uninstalling deletes ${profiles.length} stored secret profile${profiles.length === 1 ? "" : "s"} in ${secrets}.`;
|
|
504
|
+
if (!process.stdin.isTTY)
|
|
505
|
+
fail(`${notice} Re-run with --yes to confirm.`);
|
|
506
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
507
|
+
const answer = await prompt.question(`${notice} Continue? [y/N] `).finally(() => prompt.close());
|
|
508
|
+
if (!/^y(es)?$/i.test(answer.trim()))
|
|
509
|
+
fail("Uninstall cancelled; nothing was removed.");
|
|
510
|
+
}
|
|
511
|
+
async function stopInstalledRelay() {
|
|
512
|
+
const base = relayBase();
|
|
513
|
+
const audit = path.join(paths.state, "relays", new URL(base).port, "lifecycle.jsonl");
|
|
514
|
+
if (!existsSync(audit))
|
|
515
|
+
return;
|
|
516
|
+
const probe = async () => {
|
|
517
|
+
try {
|
|
518
|
+
const response = await fetch(`${base}/version`, { redirect: "error", signal: AbortSignal.timeout(2000) });
|
|
519
|
+
return response.ok ? await response.json() : undefined;
|
|
520
|
+
} catch (error) {
|
|
521
|
+
const e = error;
|
|
522
|
+
if (error instanceof SyntaxError)
|
|
523
|
+
return;
|
|
524
|
+
if (["ECONNREFUSED", "ConnectionRefused"].includes(e.cause?.code ?? e.code ?? ""))
|
|
525
|
+
return;
|
|
526
|
+
throw error;
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
const relay = await probe();
|
|
530
|
+
if (!relay?.managed || !relay.instanceId)
|
|
531
|
+
return;
|
|
532
|
+
const ours = readFileSync(audit, "utf8").trim().split(`
|
|
533
|
+
`).some((line) => {
|
|
534
|
+
const event = JSON.parse(line);
|
|
535
|
+
return event._tag === "Ready" && event.instanceId === relay.instanceId;
|
|
536
|
+
});
|
|
537
|
+
if (!ours)
|
|
538
|
+
return;
|
|
539
|
+
if (relay.shutdownProtocol !== 2)
|
|
540
|
+
throw new Error("Stop the legacy relay manually, then run uninstall again.");
|
|
541
|
+
const response = await fetch(`${base}/shutdown`, {
|
|
542
|
+
method: "POST",
|
|
543
|
+
redirect: "error",
|
|
544
|
+
headers: { ...relayHeaders(), "content-type": "application/json" },
|
|
545
|
+
signal: AbortSignal.timeout(15000),
|
|
546
|
+
body: JSON.stringify({
|
|
547
|
+
instanceId: relay.instanceId,
|
|
548
|
+
requestId: randomUUID(),
|
|
549
|
+
reason: "explicit-restart",
|
|
550
|
+
force: true,
|
|
551
|
+
client: { kind: "cli", instanceId: randomUUID(), buildId: opencodeBrowserBuildId2 }
|
|
552
|
+
})
|
|
553
|
+
});
|
|
554
|
+
if (!response.ok || !(await response.json()).stopping)
|
|
555
|
+
throw new Error("The running relay refused shutdown. Stop it manually, then run uninstall again.");
|
|
556
|
+
for (let n = 0;n < 100; n++) {
|
|
557
|
+
const current = await probe();
|
|
558
|
+
if (!current)
|
|
559
|
+
return;
|
|
560
|
+
if (current.instanceId !== relay.instanceId)
|
|
561
|
+
throw new Error("Another relay started during uninstall; no files were removed.");
|
|
562
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
563
|
+
}
|
|
564
|
+
throw new Error("The relay is still stopping. Run uninstall again once it exits.");
|
|
565
|
+
}
|
|
566
|
+
async function uninstall(args) {
|
|
567
|
+
await confirmSecretRemoval(args);
|
|
568
|
+
await stopInstalledRelay();
|
|
569
|
+
const host = removeLegacyHost();
|
|
570
|
+
const settings = readJson(files.settings);
|
|
571
|
+
const mcp = (settings?.opencodeConfigs ?? [configFile()]).flatMap((file) => [MCP_NAME, LEGACY_MCP_NAME].filter((name) => removeMcp(name, settings?.entry, file)));
|
|
572
|
+
for (const receipt of settings?.agents ?? []) {
|
|
573
|
+
try {
|
|
574
|
+
const result = editAgentConfig(receipt, true);
|
|
575
|
+
log(result === "conflict" ? `! ${receipt.file} has a changed browse server; left unchanged.` : `✓ ${receipt.name}: ${result}`);
|
|
576
|
+
} catch {
|
|
577
|
+
fail(`Couldn't safely remove browse from ${receipt.file}. Check its syntax and permissions, then re-run uninstall.`);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
const binary = installedBinaryPath();
|
|
581
|
+
for (const directory of [paths.data, paths.config, paths.state, paths.cache]) {
|
|
582
|
+
try {
|
|
583
|
+
rmSync(directory, { recursive: true, force: true });
|
|
584
|
+
log(`✓ Removed ${directory}`);
|
|
585
|
+
} catch (error) {
|
|
586
|
+
if (process.platform !== "win32" || !["EBUSY", "EPERM", "EACCES"].includes(error.code ?? ""))
|
|
587
|
+
throw error;
|
|
588
|
+
log(`! Couldn't remove all of ${directory}; close running browse agents and remove the remaining files.`);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
if (existsSync(binary)) {
|
|
592
|
+
const left = removeBinaryInstall(binary);
|
|
593
|
+
log(left ? `! Couldn't remove ${left}. After uninstall exits, close any browse agents using the file(s) and delete them.` : `✓ Removed ${binary}`);
|
|
594
|
+
}
|
|
595
|
+
if (!compiledBinary() && !fromSource) {
|
|
596
|
+
const npm = await runCommand("npm", ["uninstall", "-g", "@opencode/browse"], { timeoutMs: 120000 });
|
|
597
|
+
log(npm.status === 0 ? "✓ Removed the global npm package" : `! Couldn't remove the global npm package: ${(npm.stderr || npm.stdout).trim() || "npm uninstall failed"}`);
|
|
598
|
+
}
|
|
599
|
+
if (host)
|
|
600
|
+
log("✓ Removed the native messaging host of an earlier version");
|
|
601
|
+
if (mcp.length)
|
|
602
|
+
log(`✓ Removed the ${mcp.map((name) => `"${name}"`).join(" and ")} MCP server${mcp.length === 1 ? "" : "s"}`);
|
|
603
|
+
log("Remove the extension from your browser to finish.");
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
// src/setup/remote.ts
|
|
607
|
+
import { spawnSync as spawnSync2 } from "node:child_process";
|
|
608
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
609
|
+
import { networkInterfaces as networkInterfaces2 } from "node:os";
|
|
610
|
+
var tailnetIPv4 = /^100\.(6[4-9]|[7-9]\d|1[01]\d|12[0-7])\./;
|
|
611
|
+
var virtualInterface = /^(lo|docker|br-|veth|virbr|vmnet|vboxnet|cni|flannel|podman|utun|awdl|llw|bridge)/;
|
|
612
|
+
function remoteRelayAddresses(interfaces, options = {}) {
|
|
613
|
+
const ipv4 = Object.entries(interfaces).filter(([name]) => !virtualInterface.test(name)).flatMap(([, addresses]) => addresses ?? []).filter((address) => address.family === "IPv4" && !address.internal && !address.address.startsWith("169.254.")).map((address) => address.address);
|
|
614
|
+
const tailnet = ipv4.filter((address) => tailnetIPv4.test(address));
|
|
615
|
+
const hosts = tailnet.length ? [...options.magicDns ? [options.magicDns] : [], ...tailnet] : ipv4;
|
|
616
|
+
const port = options.port && options.port !== 19988 ? `:${options.port}` : "";
|
|
617
|
+
return [...new Set(hosts)].map((host) => host + port);
|
|
618
|
+
}
|
|
619
|
+
function remoteRelayLines(addresses, code, ttlMs = pairingCodeTtlMs) {
|
|
620
|
+
return [
|
|
621
|
+
`Relay address ${addresses[0] ?? "this computer's IP address"}`,
|
|
622
|
+
...addresses.slice(1).map((address) => ` or ${address}`),
|
|
623
|
+
`Pairing code ${formatPairingCode(code)}`,
|
|
624
|
+
"",
|
|
625
|
+
`The code works once, within ${ttlMs / 60000} minutes. For a new one, run: ${cliCommand("pair")}`
|
|
626
|
+
];
|
|
627
|
+
}
|
|
628
|
+
function magicDnsName() {
|
|
629
|
+
const mac = "/Applications/Tailscale.app/Contents/MacOS/Tailscale";
|
|
630
|
+
const cli = findOnPath("tailscale") ?? (process.platform === "darwin" && existsSync2(mac) ? mac : undefined);
|
|
631
|
+
if (!cli)
|
|
632
|
+
return;
|
|
633
|
+
const status = spawnSync2(cli, ["status", "--json"], { encoding: "utf8", timeout: 5000 });
|
|
634
|
+
const name = parseJson(status.stdout)?.Self?.DNSName;
|
|
635
|
+
return typeof name === "string" && name ? name.replace(/\.$/, "") : undefined;
|
|
636
|
+
}
|
|
637
|
+
async function installRemote(entry, tty) {
|
|
638
|
+
const config = readRelayConfig();
|
|
639
|
+
if (config.hostname !== "0.0.0.0") {
|
|
640
|
+
writeRelayConfig({ ...config, hostname: "0.0.0.0" });
|
|
641
|
+
const running = await fetch(`${relayBase()}/version`, { signal: AbortSignal.timeout(2000) }).then((response) => response.ok, () => false);
|
|
642
|
+
const [file, ...prefix] = entryCommand(entry);
|
|
643
|
+
const restarted = running && spawnSync2(file, [...prefix, "relay", "restart"], { encoding: "utf8", timeout: 60000 }).status === 0;
|
|
644
|
+
if (running && !restarted) {
|
|
645
|
+
process.exitCode = 1;
|
|
646
|
+
log(`! The relay is still only reachable from this computer. When no agent is using it, run: ${cliCommand("relay restart --force")}`);
|
|
647
|
+
} else
|
|
648
|
+
log("✓ Opened the relay to other computers");
|
|
649
|
+
} else
|
|
650
|
+
log("✓ The relay is open to other computers");
|
|
651
|
+
ensureRelay(entry);
|
|
652
|
+
const port = Number(process.env.OPENCODE_BROWSER_PORT) || 19988;
|
|
653
|
+
const interfaces = networkInterfaces2();
|
|
654
|
+
const onTailnet = Object.values(interfaces).flat().some((address) => address?.family === "IPv4" && tailnetIPv4.test(address.address));
|
|
655
|
+
const addresses = remoteRelayAddresses(interfaces, { port, magicDns: onTailnet ? magicDnsName() : undefined });
|
|
656
|
+
const lines = remoteRelayLines(addresses, mintPairingCode());
|
|
657
|
+
const where = 'In Chrome on the other computer, open browse, choose "Connect an agent on another computer" and enter:';
|
|
658
|
+
if (rail.active)
|
|
659
|
+
note(lines.join(`
|
|
660
|
+
`), "Enter this in browse on the other computer");
|
|
661
|
+
else {
|
|
662
|
+
log("");
|
|
663
|
+
log(where);
|
|
664
|
+
for (const line of lines)
|
|
665
|
+
log(line && ` ${line}`);
|
|
666
|
+
log("");
|
|
667
|
+
}
|
|
668
|
+
if (!onTailnet)
|
|
669
|
+
log("! browse doesn't encrypt this connection: use it on a network you trust, or over Tailscale, not the open internet.");
|
|
670
|
+
if (!tty)
|
|
671
|
+
log("Agent: give the user the relay address and pairing code above to enter in browse in their browser. The code works once and expires; if it does, run `" + cliCommand("pair") + "` for a new one.");
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
// src/setup.ts
|
|
675
|
+
function checkNode() {
|
|
676
|
+
if (compiledBinary())
|
|
677
|
+
return;
|
|
678
|
+
if (process.versions.bun)
|
|
679
|
+
fail("browse runs on Node.js 22.19 or newer, but this ran under Bun (`bun run` uses Bun when `node` isn't on PATH). Install Node.js from https://nodejs.org, then run setup again.");
|
|
680
|
+
const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
|
|
681
|
+
if (major < 22 || major === 22 && minor < 19)
|
|
682
|
+
fail(`browse needs Node.js 22.19 or newer; this is ${process.version} (${process.execPath}). Update Node.js (https://nodejs.org), then run setup again.`);
|
|
683
|
+
}
|
|
684
|
+
async function install(args) {
|
|
685
|
+
const tty = !!(process.stdin.isTTY && process.stdout.isTTY);
|
|
686
|
+
const caller = callingAgent(process.env);
|
|
687
|
+
rail.active = tty && !caller;
|
|
688
|
+
if (rail.active)
|
|
689
|
+
intro("browse");
|
|
690
|
+
else if (caller)
|
|
691
|
+
log(`${agentLabels[caller]} is running this, so browse is set up for ${agentLabels[caller]}.`);
|
|
692
|
+
await installSteps(args, tty, caller);
|
|
693
|
+
if (!rail.active)
|
|
694
|
+
return;
|
|
695
|
+
rail.waiting?.stop();
|
|
696
|
+
outro(process.exitCode ? `browse isn't fully set up yet. Fix the steps above, then run ${installCommand()} again.` : byHand ? "Done. Add the MCP server above to your agent, then ask it to open a page." : "Done. Ask your agent to open a page.");
|
|
697
|
+
}
|
|
698
|
+
var byHand = false;
|
|
699
|
+
function showManualMcp(command, caller) {
|
|
700
|
+
const json = manualMcpEntry(command);
|
|
701
|
+
if (rail.active)
|
|
702
|
+
return note(json, "Any agent: add browse as an MCP server");
|
|
703
|
+
const intro = byHand ? "Add browse to your agent as an MCP server (stdio):" : caller ? "Using another agent too? Add browse to it as an MCP server (stdio):" : "Agent: if you weren't set up above, add browse to your own MCP config (stdio):";
|
|
704
|
+
log(`
|
|
705
|
+
${intro}
|
|
706
|
+
${json.split(`
|
|
707
|
+
`).map((line) => ` ${line}`).join(`
|
|
708
|
+
`)}
|
|
709
|
+
`);
|
|
710
|
+
}
|
|
711
|
+
async function installSteps(args, tty, caller) {
|
|
712
|
+
checkNode();
|
|
713
|
+
const timeoutMs = installWaitTimeout(args, tty);
|
|
714
|
+
let flags;
|
|
715
|
+
try {
|
|
716
|
+
flags = agentFlags(args);
|
|
717
|
+
} catch (error) {
|
|
718
|
+
fail(error.message);
|
|
719
|
+
}
|
|
720
|
+
const opencode = findOpencode(args);
|
|
721
|
+
const locations = agentLocations(home, configRoot, findOnPath, configFile(), opencode);
|
|
722
|
+
const previous = readJson(files.settings);
|
|
723
|
+
const remembered = previous?.selectedAgents ?? (previous?.declinedAgents?.length ? locations.filter((a) => a.installed && !previous.declinedAgents.includes(a.name)).map((a) => a.name) : undefined);
|
|
724
|
+
const plan = agentPlan(locations, flags, tty, caller, remembered);
|
|
725
|
+
mkdirSync2(path2.dirname(files.settings), { recursive: true, mode: 448 });
|
|
726
|
+
mkdirSync2(files.dir, { recursive: true, mode: 448 });
|
|
727
|
+
const { entry, version } = await installRuntime();
|
|
728
|
+
log(`✓ browse ${version} installed${fromSource ? " (from source)" : ""}`);
|
|
729
|
+
const onPath = args.includes("--no-modify-path") ? undefined : path2.isAbsolute(entry) && !scriptEntry(entry) ? addToPath(path2.dirname(entry)) : undefined;
|
|
730
|
+
if (onPath)
|
|
731
|
+
log(`✓ Added browse to your PATH (${tilde(onPath)}). Open a new terminal to use it.`);
|
|
732
|
+
const anyFound = locations.some((a) => a.installed);
|
|
733
|
+
byHand = plan.picker ? !anyFound : plan.selected.length === 0;
|
|
734
|
+
const undetected = !tty && !caller && !plan.selected.length && !flags.requested.length && !flags.yes && !flags.none;
|
|
735
|
+
if (undetected) {
|
|
736
|
+
log("! Couldn't detect which agent is running browse, so no agent was configured.");
|
|
737
|
+
log(` Agents: ${agentNames.join(", ")}. Rerun with \`${cliCommand("install --agent <name>")}\`, or add the MCP entry below by hand.`);
|
|
738
|
+
}
|
|
739
|
+
showManualMcp(entryCommand(entry, "node"), caller);
|
|
740
|
+
const selected = plan.picker ? anyFound ? await pickAgents(locations, plan.selected) : [] : plan.selected;
|
|
741
|
+
if (!selected) {
|
|
742
|
+
process.exitCode = 130;
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
if (plan.picker && anyFound)
|
|
746
|
+
byHand = selected.length === 0;
|
|
747
|
+
const agents = previous?.agents ?? [];
|
|
748
|
+
const opencodeConfigs = previous?.opencodeConfigs ?? (previous?.entry ? [configFile()] : []);
|
|
749
|
+
const selectedAgents = plan.picker ? selected : remembered;
|
|
750
|
+
const save = () => writeFileSync(files.settings, JSON.stringify({
|
|
751
|
+
...opencode ? { opencode } : {},
|
|
752
|
+
entry,
|
|
753
|
+
version,
|
|
754
|
+
agents,
|
|
755
|
+
opencodeConfigs,
|
|
756
|
+
...selectedAgents && { selectedAgents }
|
|
757
|
+
}, null, 2) + `
|
|
758
|
+
`);
|
|
759
|
+
save();
|
|
760
|
+
if (removeLegacyHost())
|
|
761
|
+
log("✓ Removed the native messaging host of an earlier version");
|
|
762
|
+
const node = scriptEntry(entry) ? "node" : undefined;
|
|
763
|
+
for (const agent of locations) {
|
|
764
|
+
const label = agentLabels[agent.name];
|
|
765
|
+
if (!selected.includes(agent.name)) {
|
|
766
|
+
if (!plan.picker && agent.installed && !flags.requested.length)
|
|
767
|
+
log(`To add ${label} too: ${cliCommand(`install --agent ${agent.name}`)}`);
|
|
768
|
+
continue;
|
|
769
|
+
}
|
|
770
|
+
if (agent.name === "opencode") {
|
|
771
|
+
const mcp = configureMcp(agent.file, entry, previous?.entry);
|
|
772
|
+
if (mcp && !opencodeConfigs.includes(agent.file)) {
|
|
773
|
+
opencodeConfigs.push(agent.file);
|
|
774
|
+
save();
|
|
775
|
+
}
|
|
776
|
+
if (!mcp)
|
|
777
|
+
process.exitCode = 1;
|
|
778
|
+
log(!mcp ? `! ${label} already has a different server named browse in ${tilde(agent.file)}; left it unchanged.` : mcp.includes("up to date") ? `✓ ${label} already has browse` : mcp.includes("added") ? `✓ Added browse to ${label} (${tilde(agent.file)})` : `✓ Updated browse in ${label} (${tilde(agent.file)})`);
|
|
779
|
+
continue;
|
|
780
|
+
}
|
|
781
|
+
const receipt = { name: agent.name, file: agent.file, entry, ...node ? { node } : {} };
|
|
782
|
+
try {
|
|
783
|
+
const prior = agents.find((a) => a.file === agent.file && a.name === agent.name);
|
|
784
|
+
if (prior && (prior.entry !== receipt.entry || prior.node !== receipt.node) && editAgentConfig(prior, true) === "removed") {
|
|
785
|
+
agents.splice(agents.indexOf(prior), 1);
|
|
786
|
+
save();
|
|
787
|
+
}
|
|
788
|
+
const result = editAgentConfig(receipt);
|
|
789
|
+
if (result === "added") {
|
|
790
|
+
const i = agents.findIndex((a) => a.file === agent.file);
|
|
791
|
+
if (i !== -1)
|
|
792
|
+
agents.splice(i, 1);
|
|
793
|
+
agents.push(receipt);
|
|
794
|
+
save();
|
|
795
|
+
}
|
|
796
|
+
if (result === "conflict")
|
|
797
|
+
process.exitCode = 1;
|
|
798
|
+
log(result === "conflict" ? `! ${label} already has a different server named browse in ${tilde(agent.file)}; left it unchanged.` : result === "added" ? `✓ Added browse to ${label} (${tilde(agent.file)})` : `✓ ${label} already has browse`);
|
|
799
|
+
} catch {
|
|
800
|
+
process.exitCode = 1;
|
|
801
|
+
log(`! Couldn't edit ${tilde(agent.file)} for ${label}. Check its syntax and permissions, then run ${cliCommand(`install --agent ${agent.name}`)}.`);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
for (const line of restartOutdatedRelay(entry) ?? [])
|
|
805
|
+
log(line);
|
|
806
|
+
const legacy = selected.includes("opencode") ? legacyBrowserControl() : [];
|
|
807
|
+
if (legacy.length)
|
|
808
|
+
log(`! Also configured: ${legacy.map((name) => `"${name}"`).join(", ")}, ${legacy.length === 1 ? "an older browser MCP server" : "older browser MCP servers"} that browse replaces. Remove ${legacy.length === 1 ? "it" : "them"} from ${configFile()} to avoid two sets of browser tools.`);
|
|
809
|
+
if (args.includes("--remote"))
|
|
810
|
+
return installRemote(entry, tty);
|
|
811
|
+
await syncDev();
|
|
812
|
+
const initial = await settledExtensionStatus(entry);
|
|
813
|
+
const connected = initial?.connected ? initial : undefined;
|
|
814
|
+
const pairedOffline = initial?.pairingState === "paired-offline";
|
|
815
|
+
const folder = unpackedFolder();
|
|
816
|
+
if (folder && !pairedOffline) {
|
|
817
|
+
pairUnpacked();
|
|
818
|
+
const reload = connected ? await reloadOutdatedExtension(connected, folder) : "current";
|
|
819
|
+
if (reload === "reloaded")
|
|
820
|
+
log("✓ Reloaded browse in your browser");
|
|
821
|
+
}
|
|
822
|
+
const reportMismatch = (status) => {
|
|
823
|
+
const advice = status.nextStep ?? extensionProtocolAdvice(status.protocolVersion, { install: installCommand() });
|
|
824
|
+
if (args.includes("--no-wait") && folder && status.origin === `chrome-extension://${unpackedExtensionId}` && extensionProtocolSkew(status.protocolVersion) === "extension-older")
|
|
825
|
+
return log(`! Not connected yet. ${advice}`);
|
|
826
|
+
fail(advice);
|
|
827
|
+
};
|
|
828
|
+
if (initial?.protocolCompatible === false && initial.origin)
|
|
829
|
+
return reportMismatch(initial);
|
|
830
|
+
log("");
|
|
831
|
+
const ssh = !!(process.env.SSH_CONNECTION || process.env.SSH_TTY);
|
|
832
|
+
const detections = ssh ? [] : detectBrowsers();
|
|
833
|
+
rmSync2(oldStoreMarker(), { force: true });
|
|
834
|
+
const checkStore = (scanned) => {
|
|
835
|
+
const matches = scanned.flatMap((d) => d.enabled).filter((m) => STORE_IDS.includes(m.id));
|
|
836
|
+
if (!matches.length || !matches.every(oldStoreBuild))
|
|
837
|
+
return true;
|
|
838
|
+
writeFileSync(oldStoreMarker(), `2
|
|
839
|
+
`);
|
|
840
|
+
ensureRelay(entry);
|
|
841
|
+
log(`! Found browse ${matches[0].version} in ${matches[0].browser.name}. ${extensionProtocolAdvice(2, { install: cliCommand("install") }, "store")}`);
|
|
842
|
+
process.exitCode = 1;
|
|
843
|
+
return false;
|
|
844
|
+
};
|
|
845
|
+
if (!connected && !checkStore(detections))
|
|
846
|
+
return;
|
|
847
|
+
const env = {
|
|
848
|
+
ssh,
|
|
849
|
+
display: process.platform !== "linux" || !!(process.env.DISPLAY || process.env.WAYLAND_DISPLAY),
|
|
850
|
+
tty,
|
|
851
|
+
platform: process.platform
|
|
852
|
+
};
|
|
853
|
+
const found = locateExtension({
|
|
854
|
+
allowOpen: !args.includes("--no-open"),
|
|
855
|
+
connected: !!connected,
|
|
856
|
+
pairedOffline,
|
|
857
|
+
detections,
|
|
858
|
+
preferred: ssh ? undefined : defaultBrowser(detections.map((detection) => detection.browser)),
|
|
859
|
+
env
|
|
860
|
+
});
|
|
861
|
+
if (connected || found === "off" || pairedOffline)
|
|
862
|
+
return;
|
|
863
|
+
ensureRelay(entry);
|
|
864
|
+
let code;
|
|
865
|
+
const pairingCode = () => code && pendingPairingCodeKeys().includes(pairingCodeKey(code)) ? code : code = mintPairingCode();
|
|
866
|
+
const pairStore = (scanned) => pairStoreExtension({
|
|
867
|
+
detections: scanned,
|
|
868
|
+
preferred: defaultBrowser(scanned.map((d) => d.browser)),
|
|
869
|
+
allowOpen: !args.includes("--no-open"),
|
|
870
|
+
env,
|
|
871
|
+
code: pairingCode
|
|
872
|
+
});
|
|
873
|
+
let offer = ssh ? "none" : pairStore(detections);
|
|
874
|
+
const blocked = detections.filter((d) => d.blocked).map((d) => d.browser.name);
|
|
875
|
+
if (offer === "none" && blocked.length)
|
|
876
|
+
log(`Couldn't check ${blocked.join(", ")}. If browse is already installed there, pair it manually. ${manualPair(pairingCode())}`);
|
|
877
|
+
const next = `If browse isn't connected after you add it, run \`${cliCommand("install")}\` again to pair it.`;
|
|
878
|
+
const agentNext = () => {
|
|
879
|
+
return `Agent: ${offer === "opened" ? "ask the user to open browse's status page in their browser" : offer === "manual" || blocked.length ? "ask the user to finish pairing in browse's Options" : "ask the user to add browse from the Chrome Web Store"}. Then re-run \`${cliCommand("install")}\` to finish, or call the browse status tool to check the connection.`;
|
|
880
|
+
};
|
|
881
|
+
if (!env.tty)
|
|
882
|
+
log(agentNext());
|
|
883
|
+
if (args.includes("--no-wait") || ssh || !env.display) {
|
|
884
|
+
if (env.tty)
|
|
885
|
+
log(next);
|
|
886
|
+
return;
|
|
887
|
+
}
|
|
888
|
+
if (rail.active)
|
|
889
|
+
(rail.waiting = spinner({
|
|
890
|
+
cancelMessage: "Stopped waiting",
|
|
891
|
+
onCancel: () => {
|
|
892
|
+
rail.waiting = undefined;
|
|
893
|
+
}
|
|
894
|
+
})).start("Waiting for browse to connect in your browser (Ctrl+C to skip)");
|
|
895
|
+
else
|
|
896
|
+
log(`Waiting for browse to connect (up to ${timeoutMs / 1000}s; Ctrl+C to skip)…`);
|
|
897
|
+
let stopped = false;
|
|
898
|
+
const stop = () => {
|
|
899
|
+
stopped = true;
|
|
900
|
+
};
|
|
901
|
+
process.once("SIGINT", stop);
|
|
902
|
+
try {
|
|
903
|
+
const deadline = Date.now() + timeoutMs;
|
|
904
|
+
do {
|
|
905
|
+
const status = await extensionStatus(!args.includes("--no-open") && (offer === "opened" || offer === "none" && !blocked.length));
|
|
906
|
+
if (status?.protocolCompatible === false)
|
|
907
|
+
return reportMismatch(status);
|
|
908
|
+
if (status?.connected)
|
|
909
|
+
return log(connectedMessage);
|
|
910
|
+
if (status?.pairingState === "paired-offline")
|
|
911
|
+
return log(pairedOfflineMessage);
|
|
912
|
+
if (offer === "none") {
|
|
913
|
+
const scan = detectBrowsers();
|
|
914
|
+
if (!checkStore(scan))
|
|
915
|
+
return;
|
|
916
|
+
if (scan.some((d) => d.enabled.length))
|
|
917
|
+
offer = pairStore(scan);
|
|
918
|
+
}
|
|
919
|
+
await new Promise((resolve) => setTimeout(resolve, Math.max(0, Math.min(1000, deadline - Date.now()))));
|
|
920
|
+
} while (!stopped && Date.now() < deadline);
|
|
921
|
+
if (!env.tty)
|
|
922
|
+
return log(`! Not connected yet. ${agentNext()}`);
|
|
923
|
+
log(`! Not connected yet. ${code ? manualPair(pairingCode()) : next}`);
|
|
924
|
+
process.exitCode = 1;
|
|
925
|
+
} finally {
|
|
926
|
+
process.off("SIGINT", stop);
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
function printSetupStatus() {
|
|
930
|
+
const settings = readJson(files.settings);
|
|
931
|
+
const runtime = installedRuntime(settings, mcpServers()[MCP_NAME]);
|
|
932
|
+
log(runtime ? `Setup: installed${runtime.source ? " (from source)" : ""}` : `Setup: not installed. Run \`${installCommand()}\`.`);
|
|
933
|
+
log(`Version: ${runtime ? `${runtime.version ?? "unknown"} (${runtime.entry})` : "not installed"}`);
|
|
934
|
+
log(`opencode: ${settings?.opencode ?? findOpencode([]) ?? "not found"}`);
|
|
935
|
+
log(mcpServers()[MCP_NAME] ? `MCP: "${MCP_NAME}" configured` : "MCP: not configured");
|
|
936
|
+
log(describeAutoUpdate(autoUpdateStatus()));
|
|
937
|
+
log(`Files: ${paths.config}, ${paths.data}, ${paths.state}, ${paths.cache}`);
|
|
938
|
+
log(`Logs: ${path2.join(paths.state, "logs")}`);
|
|
939
|
+
log("");
|
|
940
|
+
}
|
|
941
|
+
async function runSetup(command, args) {
|
|
942
|
+
if (command === "install")
|
|
943
|
+
return install(args);
|
|
944
|
+
if (command === "extension")
|
|
945
|
+
return extension();
|
|
946
|
+
if (command === "uninstall")
|
|
947
|
+
return uninstall(args);
|
|
948
|
+
if (command === "pair")
|
|
949
|
+
return pair(args);
|
|
950
|
+
if (command === "set")
|
|
951
|
+
return set(args);
|
|
952
|
+
}
|
|
953
|
+
export {
|
|
954
|
+
printSetupStatus,
|
|
955
|
+
runSetup
|
|
956
|
+
};
|