@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.
Files changed (33) hide show
  1. package/dist/{cli-qpkh40gh.mjs → cli-mx6tbg2m.mjs} +63 -52
  2. package/dist/cli.mjs +30 -19
  3. package/dist/{helpers-kp0j46jt.mjs → helpers-hgm1z9h5.mjs} +2 -2
  4. package/dist/{index-0dcypq31.mjs → index-yzz55kxm.mjs} +1 -1
  5. package/dist/{main-brv9dhy5.mjs → main-1fdejpga.mjs} +9 -9
  6. package/dist/{main-ajza8egc.mjs → main-6chyyr6j.mjs} +44 -39
  7. package/dist/{main-rt6g5418.mjs → main-8z9d979q.mjs} +15 -15
  8. package/dist/{setup-j76yv51b.mjs → main-b7g6460c.mjs} +3608 -4406
  9. package/dist/{main-gevbt7h7.mjs → main-csnx585b.mjs} +151 -151
  10. package/dist/{main-nqmm7pdz.mjs → main-cymarjp4.mjs} +47 -47
  11. package/dist/main-j2ehvkhk.mjs +465 -0
  12. package/dist/main-r3a6053j.mjs +157 -0
  13. package/dist/main-s7017yah.mjs +161 -0
  14. package/dist/main-sjrzyg3x.mjs +73 -0
  15. package/dist/main-vgzr4689.mjs +61 -0
  16. package/dist/{main-eej5z0y5.mjs → main-zq79yb8r.mjs} +6 -6
  17. package/dist/main-zya5ttbr.mjs +4 -0
  18. package/dist/{mcp-sy8qgkyr.mjs → mcp-h0qcxhqc.mjs} +138 -137
  19. package/dist/migrate-pgckfkg5.mjs +233 -0
  20. package/dist/{relay-ateyg5ax.mjs → relay-gafgjtav.mjs} +128 -123
  21. package/dist/runtime-update-p2pnfdy1.mjs +156 -0
  22. package/dist/setup-fhhjnx9r.mjs +956 -0
  23. package/dist/{skill-text-x7sccp6h.mjs → skill-text-6p6scqwe.mjs} +2 -2
  24. package/dist/{supervisor-0rvjpf4e.mjs → supervisor-06t66v4t.mjs} +38 -17
  25. package/dist/{update-rbd2025v.mjs → update-7hagfdc0.mjs} +3 -3
  26. package/dist/{version-4cjr3wpp.mjs → version-hhcvk9wm.mjs} +1 -1
  27. package/package.json +1 -1
  28. package/skills/browse/SKILL.md +2 -2
  29. package/dist/main-7wgmq04v.mjs +0 -303
  30. package/dist/main-exnm62gg.mjs +0 -4
  31. package/dist/main-hm4fcpfz.mjs +0 -131
  32. package/dist/main-rn7hdcq2.mjs +0 -805
  33. package/dist/runtime-update-70gqzynp.mjs +0 -200
@@ -0,0 +1,465 @@
1
+ import {
2
+ opencodeBrowserVersion2
3
+ } from "./main-zya5ttbr.mjs";
4
+
5
+ // src/paths.ts
6
+ import fs from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { fileURLToPath } from "node:url";
10
+ var override = (home) => home === os.homedir() && process.env.OPENCODE_BROWSER_HOME ? process.env.OPENCODE_BROWSER_HOME : undefined;
11
+ var xdgRoot = (variable, fallback, home) => {
12
+ const configured = home === os.homedir() ? process.env[variable] : undefined;
13
+ return path.join(configured && path.isAbsolute(configured) ? configured : path.join(home, fallback), "browse");
14
+ };
15
+ function configRoot2(home = os.homedir()) {
16
+ return override(home) ?? xdgRoot("XDG_CONFIG_HOME", ".config", home);
17
+ }
18
+ function dataRoot(home = os.homedir()) {
19
+ return override(home) ?? xdgRoot("XDG_DATA_HOME", ".local/share", home);
20
+ }
21
+ function stateRoot(home = os.homedir()) {
22
+ return override(home) ?? xdgRoot("XDG_STATE_HOME", ".local/state", home);
23
+ }
24
+ function cacheRoot(home = os.homedir()) {
25
+ return override(home) ?? xdgRoot("XDG_CACHE_HOME", ".cache", home);
26
+ }
27
+ function binRoot(home = os.homedir()) {
28
+ if (override(home))
29
+ return path.join(override(home), "bin");
30
+ const configured = home === os.homedir() ? process.env.XDG_BIN_HOME : undefined;
31
+ return configured && path.isAbsolute(configured) ? configured : path.join(home, ".local", "bin");
32
+ }
33
+ var installedBinaryPath = (home = os.homedir()) => path.join(binRoot(home), binaryName());
34
+ var packageRoot = () => path.dirname(path.dirname(fileURLToPath(import.meta.url)));
35
+ var oldStoreMarker = () => path.join(stateRoot(), "old-store-extension");
36
+ function fromCheckout() {
37
+ return !compiledBinary() && fs.existsSync(path.join(packageRoot(), "src", "main.ts"));
38
+ }
39
+ var compiledBinary = () => globalThis.__OPENCODE_BROWSER_COMPILED__ === true;
40
+ var binaryPackage = () => globalThis.__OPENCODE_BROWSER_TARGET__ ? `@opencode/browse-${globalThis.__OPENCODE_BROWSER_TARGET__}` : undefined;
41
+ var binaryName = (platform = process.platform) => platform === "win32" ? "browse.exe" : "browse";
42
+ var scriptEntry = (entry) => /\.[cm]?[jt]s$/.test(entry);
43
+ var entryCommand = (entry, node = process.execPath) => scriptEntry(entry) ? [node, entry] : [entry];
44
+ function installedBinary() {
45
+ const binary = installedBinaryPath();
46
+ return fs.existsSync(binary) ? binary : undefined;
47
+ }
48
+ var runningEntry = () => compiledBinary() ? process.execPath : process.argv[1];
49
+ function checkoutRoot() {
50
+ return fromCheckout() ? path.dirname(packageRoot()) : undefined;
51
+ }
52
+ var quoted = (value) => /^[\w@%+=:,./-]+$/.test(value) ? value : JSON.stringify(value);
53
+ function cliInstall() {
54
+ if (compiledBinary())
55
+ return { kind: "binary", binary: installedBinary() ?? process.execPath, pathEnv: process.env.PATH };
56
+ if (fromCheckout())
57
+ return { kind: "checkout", bundle: path.join(packageRoot(), "dist", "cli.mjs") };
58
+ return { kind: "npm", version: "0.0.11-dev.77", npx: /[/\\]_npx[/\\]/.test(process.argv[1] ?? "") };
59
+ }
60
+ function cliPrefix(install = cliInstall()) {
61
+ if (install.kind === "binary") {
62
+ const dir = path.dirname(install.binary);
63
+ const onPath = (install.pathEnv ?? "").split(path.delimiter).some((entry) => entry && path.resolve(entry) === dir);
64
+ return onPath ? "browse" : quoted(install.binary);
65
+ }
66
+ if (install.kind === "checkout")
67
+ return `node ${quoted(install.bundle)}`;
68
+ if (install.npx)
69
+ return install.version?.includes("-dev.") ? "npx @opencode/browse@dev" : "npx @opencode/browse";
70
+ return "browse";
71
+ }
72
+ var cliCommand = (args, install = cliInstall()) => `${cliPrefix(install)} ${args}`;
73
+ var STORE_ITEM_ID = /^[a-p]{32}$/;
74
+ var PUBLIC_STORE_ID = "mfnicocicmmlkpjnaffgihfjhdgjkdjg";
75
+ function storeConfig(env = process.env, baked = { id: "mfnicocicmmlkpjnaffgihfjhdgjkdjg" }) {
76
+ const id = [env.OPENCODE_BROWSER_STORE_ID, baked?.id].find((value) => value && STORE_ITEM_ID.test(value));
77
+ return id ? { id } : {};
78
+ }
79
+ var RELEASE_SERVICE = "https://anoma.ly/release";
80
+ function devExtension(baked = { file: "browse-extension-0.0.11-dev.77.zip", sha256: "f698845a8d162fecede6fd66488018bf2f2f0eb819048e65e791bc7f567c1324", size: 182559 }) {
81
+ return baked && /^[0-9a-f]{64}$/.test(baked.sha256) && /^[\w.-]+\.zip$/.test(baked.file) ? baked : undefined;
82
+ }
83
+ var devExtensionUrl = (extension, env = process.env) => `${(env.OPENCODE_BROWSER_RELEASE_SERVICE || RELEASE_SERVICE).replace(/\/+$/, "")}/browse/files/${extension.sha256}/${extension.file}`;
84
+ var devExtensionFolder = (root = cacheRoot()) => path.join(root, "extension");
85
+ var storeUrl = (id) => `https://chromewebstore.google.com/detail/${id}`;
86
+ function installCommand() {
87
+ return fromCheckout() ? `cd ${quoted(path.dirname(packageRoot()))} && bun run setup` : cliCommand("install");
88
+ }
89
+
90
+ // src/update/auto-update.ts
91
+ import { spawn, spawnSync } from "node:child_process";
92
+ import { chmodSync, closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, realpathSync, writeFileSync } from "node:fs";
93
+ import os2 from "node:os";
94
+ import path2 from "node:path";
95
+ var PACKAGE_NAME = "@opencode/browse";
96
+ var DAY_MS = 24 * 60 * 60 * 1000;
97
+ var DEFAULT_REGISTRY = "https://registry.npmjs.org";
98
+ var INSTALL_SCRIPT = "https://opencode.ai/browse/install";
99
+ var INSTALL_SCRIPT_WINDOWS = "https://opencode.ai/browse/install.ps1";
100
+ var autoUpdateModes = ["on", "notify", "off"];
101
+ var UPDATE_VERSION = /^(\d+)\.(\d+)\.(\d+)(?:-dev\.(\d+)(?:\.(\d+))?)?$/;
102
+ var channelOf = (version) => version.includes("-dev.") ? "dev" : "latest";
103
+ function compareVersions(left, right) {
104
+ const parse = (value) => {
105
+ const match = UPDATE_VERSION.exec(value);
106
+ if (!match)
107
+ return;
108
+ const release = match[4] === undefined ? 1 : 0;
109
+ return [Number(match[1]), Number(match[2]), Number(match[3]), release, Number(match[4] ?? 0), Number(match[5] ?? 0)];
110
+ };
111
+ const a = parse(left);
112
+ const b = parse(right);
113
+ if (!a || !b)
114
+ return 0;
115
+ for (let index = 0;index < a.length; index++)
116
+ if (a[index] !== b[index])
117
+ return a[index] < b[index] ? -1 : 1;
118
+ return 0;
119
+ }
120
+ function installKind(entry = process.argv[1] ?? "", checkout = fromCheckout()) {
121
+ if (checkout)
122
+ return "checkout";
123
+ if (compiledBinary())
124
+ return "binary";
125
+ const normalized = entry.replaceAll("\\", "/");
126
+ if (/\/_npx\/|\/npm-cache\/_npx\//.test(normalized))
127
+ return "npx";
128
+ return entry ? "npm" : "other";
129
+ }
130
+ var packageVersion = (entry) => {
131
+ try {
132
+ const manifest = path2.join(path2.dirname(path2.dirname(entry)), "package.json");
133
+ const version = JSON.parse(readFileSync(manifest, "utf8")).version;
134
+ return typeof version === "string" ? version : undefined;
135
+ } catch {
136
+ return;
137
+ }
138
+ };
139
+ var realEntry = (entry) => {
140
+ try {
141
+ return realpathSync(entry);
142
+ } catch {
143
+ return entry;
144
+ }
145
+ };
146
+ function installedRuntime2(entry = process.argv[1] ?? process.execPath) {
147
+ const kind = installKind(entry);
148
+ if (kind === "binary") {
149
+ const binary = installedBinary();
150
+ if (binary)
151
+ return { kind, entry: binary, version: opencodeBrowserVersion2 };
152
+ return;
153
+ }
154
+ if (kind !== "npm" && kind !== "npx")
155
+ return;
156
+ const resolved = realEntry(entry);
157
+ return { kind, entry: resolved, version: packageVersion(resolved) ?? opencodeBrowserVersion2 };
158
+ }
159
+ function installedVersion(runtime) {
160
+ if (runtime.kind === "binary") {
161
+ const result = spawnSync(runtime.entry, ["--version"], { encoding: "utf8", timeout: 15000, env: { ...process.env, OPENCODE_BROWSER_AUTOSTART: "0" } });
162
+ return result.status === 0 ? result.stdout.trim() || undefined : undefined;
163
+ }
164
+ return packageVersion(runtime.entry);
165
+ }
166
+ var autoUpdateStatePath = () => path2.join(stateRoot(), "auto-update.json");
167
+ function readJson(file) {
168
+ try {
169
+ return JSON.parse(readFileSync(file, "utf8"));
170
+ } catch {
171
+ return;
172
+ }
173
+ }
174
+ function writeJsonAtomic(file, value) {
175
+ mkdirSync(path2.dirname(file), { recursive: true, mode: 448 });
176
+ const temporary = `${file}.${process.pid}.tmp`;
177
+ writeFileSync(temporary, JSON.stringify(value, null, 2) + `
178
+ `, { mode: 384 });
179
+ chmodSync(temporary, 384);
180
+ renameSync(temporary, file);
181
+ }
182
+ function readState() {
183
+ return readJson(autoUpdateStatePath()) ?? {};
184
+ }
185
+ function updateState(change) {
186
+ const next = change(readState());
187
+ writeJsonAtomic(autoUpdateStatePath(), next);
188
+ return next;
189
+ }
190
+ function autoUpdateOverride(env = process.env) {
191
+ const value = env.OPENCODE_BROWSER_AUTO_UPDATE?.trim().toLowerCase();
192
+ if (value === "on" || value === "1" || value === "true")
193
+ return "on";
194
+ if (value === "notify")
195
+ return "notify";
196
+ if (value === "off" || value === "0" || value === "false")
197
+ return "off";
198
+ if (env.OPENCODE_BROWSER_UPDATE_CHECK === "0")
199
+ return "off";
200
+ return;
201
+ }
202
+ function storedMode() {
203
+ const mode = readState().mode;
204
+ return mode && autoUpdateModes.includes(mode) ? mode : "on";
205
+ }
206
+ function effectiveMode(env = process.env) {
207
+ return autoUpdateOverride(env) ?? storedMode();
208
+ }
209
+ function setStoredMode(mode) {
210
+ updateState((state) => ({ ...state, mode }));
211
+ }
212
+ function autoUpdateStatus(options = {}) {
213
+ const env = options.env ?? process.env;
214
+ const runtime = options.runtime === undefined ? installedRuntime2() : options.runtime;
215
+ const state = readState();
216
+ const override = autoUpdateOverride(env);
217
+ const install = runtime?.kind ?? installKind();
218
+ return {
219
+ install,
220
+ cli: cliPrefix(),
221
+ mode: storedMode(),
222
+ effective: install === "binary" || install === "npm" ? override ?? storedMode() : "off",
223
+ ...override ? { overriddenBy: env.OPENCODE_BROWSER_AUTO_UPDATE !== undefined ? "OPENCODE_BROWSER_AUTO_UPDATE" : "OPENCODE_BROWSER_UPDATE_CHECK" } : {},
224
+ ...runtime ? { version: runtime.version, channel: channelOf(runtime.version) } : {},
225
+ ...state.latest ? { latest: state.latest } : {},
226
+ ...state.checkedAt ? { checkedAt: new Date(state.checkedAt).toISOString() } : {},
227
+ ...state.lastUpdate ? { lastUpdate: state.lastUpdate } : {},
228
+ ...state.lastError ? { lastError: state.lastError } : {}
229
+ };
230
+ }
231
+ function describeAutoUpdate(status) {
232
+ if (status.install === "checkout")
233
+ return "Updates: checkout install; `update` pulls new commits";
234
+ if (status.install === "npx")
235
+ return "Updates: npx resolves the package itself; `update` is a no-op";
236
+ if (status.install !== "binary" && status.install !== "npm")
237
+ return "Updates: not an installed runtime";
238
+ const mode = { on: "automatic", notify: "notify only", off: "off" }[status.effective];
239
+ const parts = [`${mode}${status.overriddenBy ? ` (set by ${status.overriddenBy})` : ""}`, `channel ${status.channel ?? "latest"}`];
240
+ if (status.latest && status.version && compareVersions(status.latest, status.version) > 0)
241
+ parts.push(`${status.latest} available; the installer runs when no agent is using the browser`);
242
+ if (status.lastError)
243
+ parts.push(`last attempt failed: ${status.lastError.message}`);
244
+ return `Updates: ${parts.join("; ")}`;
245
+ }
246
+ var runCommand = (command, args, options = {}) => new Promise((resolve) => {
247
+ const npmCli = process.platform === "win32" && command === "npm" ? path2.join(path2.dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : undefined;
248
+ const [file, argv] = npmCli && existsSync(npmCli) ? [process.execPath, [npmCli, ...args]] : [command, args];
249
+ const child = spawn(file, argv, { env: options.env ?? process.env, stdio: ["ignore", "pipe", "pipe"] });
250
+ let stdout = "";
251
+ let stderr = "";
252
+ child.stdout.setEncoding("utf8").on("data", (chunk) => void (stdout += chunk));
253
+ child.stderr.setEncoding("utf8").on("data", (chunk) => void (stderr += chunk));
254
+ const timer = setTimeout(() => child.kill(), options.timeoutMs ?? 120000);
255
+ child.on("error", (error) => {
256
+ clearTimeout(timer);
257
+ resolve({ status: null, stdout, stderr: stderr + error.message });
258
+ });
259
+ child.on("close", (status) => {
260
+ clearTimeout(timer);
261
+ resolve({ status, stdout, stderr });
262
+ });
263
+ });
264
+ async function registryUrl(run = runCommand, env = process.env) {
265
+ const override = env.OPENCODE_BROWSER_NPM_REGISTRY?.trim();
266
+ const configured = override || (compiledBinary() ? "" : (await run("npm", ["config", "get", "registry"], { timeoutMs: 15000 })).stdout.trim());
267
+ return /^https?:\/\//.test(configured) ? configured.replace(/\/+$/, "") : DEFAULT_REGISTRY;
268
+ }
269
+ async function fetchPublished(options) {
270
+ const request = options.fetch ?? fetch;
271
+ const name = options.packageName ?? PACKAGE_NAME;
272
+ const response = await request(`${options.registry}/${name.replace("/", "%2f")}`, {
273
+ headers: { accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8" },
274
+ signal: AbortSignal.timeout(20000)
275
+ });
276
+ if (!response.ok)
277
+ throw new Error(`the registry answered ${response.status} for ${name}`);
278
+ const body = await response.json();
279
+ const version = body["dist-tags"]?.[options.channel];
280
+ if (!version)
281
+ throw new Error(`${name} has no ${options.channel} dist-tag`);
282
+ return { version };
283
+ }
284
+ async function runInstaller(options) {
285
+ const run = options.run ?? runCommand;
286
+ const env = options.env ?? process.env;
287
+ const platform = options.platform ?? process.platform;
288
+ if (options.runtime.kind === "npx")
289
+ return options.runtime.version;
290
+ if (options.runtime.kind === "npm") {
291
+ const spec = `${PACKAGE_NAME}@${options.version ?? options.channel ?? "latest"}`;
292
+ const npm = await run("npm", ["install", "-g", spec], { timeoutMs: 10 * 60000, env });
293
+ if (npm.status !== 0)
294
+ throw new Error(`npm install -g ${spec} failed: ${(npm.stderr || npm.stdout).trim().split(`
295
+ `).slice(-3).join(" ")}`);
296
+ const version = installedVersion(options.runtime) ?? options.version ?? options.channel ?? "latest";
297
+ if (options.version && compareVersions(version, options.version) < 0)
298
+ throw new Error(`npm install -g ${spec} left ${version}, not the requested ${options.version}`);
299
+ return version;
300
+ }
301
+ const scriptUrl = env.OPENCODE_BROWSER_INSTALL_SCRIPT || (platform === "win32" ? INSTALL_SCRIPT_WINDOWS : INSTALL_SCRIPT);
302
+ const script = existsSync(scriptUrl) ? readFileSync(scriptUrl, "utf8") : await (options.fetch ?? fetch)(scriptUrl, { signal: AbortSignal.timeout(60000) }).then(async (response) => {
303
+ if (!response.ok)
304
+ throw new Error(`couldn't download the installer (${response.status})`);
305
+ return response.text();
306
+ });
307
+ const directory = mkdtempSync(path2.join(os2.tmpdir(), "browse-install-"));
308
+ const file = path2.join(directory, platform === "win32" ? "install.ps1" : "install");
309
+ const args = [...options.version ? ["--version", options.version] : options.channel ? ["--channel", options.channel] : [], "--no-setup"];
310
+ try {
311
+ writeFileSync(file, script, { mode: platform === "win32" ? 384 : 448 });
312
+ const command = platform === "win32" ? "powershell.exe" : "sh";
313
+ const argv = platform === "win32" ? ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", file, ...args] : [file, ...args];
314
+ const installed = await run(command, argv, { timeoutMs: 10 * 60000, env });
315
+ if (installed.status !== 0)
316
+ throw new Error(`the installer failed: ${(installed.stderr || installed.stdout).trim().split(`
317
+ `).slice(-3).join(" ")}`);
318
+ } finally {
319
+ rmSync(directory, { recursive: true, force: true });
320
+ }
321
+ const version = installedVersion(options.runtime);
322
+ if (!version)
323
+ throw new Error(`the installer ran, but ${options.runtime.entry} doesn't report a version`);
324
+ if (options.version && compareVersions(version, options.version) < 0)
325
+ throw new Error(`the installer left ${version}, not the requested ${options.version}`);
326
+ return version;
327
+ }
328
+ function processAlive(pid) {
329
+ if (!Number.isSafeInteger(pid) || pid <= 0)
330
+ return false;
331
+ try {
332
+ process.kill(pid, 0);
333
+ return true;
334
+ } catch (error) {
335
+ return error.code === "EPERM";
336
+ }
337
+ }
338
+ var INSTALL_TIMEOUT_MS = 15 * 60000;
339
+ var SWITCH_TIMEOUT_MS = 5 * 60000;
340
+ function createAutoUpdater(deps) {
341
+ const env = deps.env ?? process.env;
342
+ const now = deps.now ?? Date.now;
343
+ const { runtime } = deps;
344
+ const running = runtime.version;
345
+ const checkIntervalMs = Number(env.OPENCODE_BROWSER_AUTO_UPDATE_INTERVAL_MS) || DAY_MS;
346
+ const spawnChild = deps.spawnChild ?? ((args, onExit) => spawnRuntimeChild(runtime, args, onExit, env));
347
+ let busy = false;
348
+ let switching;
349
+ let timer;
350
+ async function tick() {
351
+ if (switching && (now() - switching.startedAt > SWITCH_TIMEOUT_MS || switching.pid !== undefined && !processAlive(switching.pid))) {
352
+ deps.log("autoupdate.switch_abandoned", { pid: switching.pid });
353
+ switching = undefined;
354
+ }
355
+ if (busy || switching)
356
+ return;
357
+ busy = true;
358
+ try {
359
+ const mode = effectiveMode(env);
360
+ if (mode === "off")
361
+ return;
362
+ let state = readState();
363
+ if (!state.checkedAt || now() - state.checkedAt >= checkIntervalMs || now() < state.checkedAt) {
364
+ const channel = channelOf(running);
365
+ try {
366
+ const published = await fetchPublished({ registry: await registryUrl(deps.run, env), channel, ...deps.fetch ? { fetch: deps.fetch } : {} });
367
+ state = updateState(({ failed: _failed, ...rest }) => ({ ...rest, checkedAt: now(), latest: published.version }));
368
+ deps.log("autoupdate.checked", { channel, latest: published.version, running });
369
+ } catch (error) {
370
+ state = updateState((rest) => ({ ...rest, checkedAt: now(), failed: error.message }));
371
+ deps.log("autoupdate.check_failed", { error: error.message });
372
+ }
373
+ deps.onChange?.();
374
+ }
375
+ const latest = state.latest;
376
+ const wanted = latest && compareVersions(latest, running) > 0 ? latest : undefined;
377
+ if (!wanted || mode !== "on")
378
+ return;
379
+ const installing = state.installing;
380
+ if (installing) {
381
+ const alive = processAlive(installing.pid) && now() - installing.startedAt < INSTALL_TIMEOUT_MS;
382
+ if (alive)
383
+ return;
384
+ const installed = installedVersion(runtime);
385
+ state = updateState(({ installing: _installing, ...rest }) => ({
386
+ ...rest,
387
+ ...installed && compareVersions(installed, installing.version) >= 0 ? {} : { lastError: { message: "the installer stopped without finishing", at: new Date(now()).toISOString(), version: installing.version } }
388
+ }));
389
+ deps.log("autoupdate.installer_gone", { version: installing.version });
390
+ }
391
+ const installed = installedVersion(runtime);
392
+ if (installed && compareVersions(installed, wanted) >= 0) {
393
+ if (!deps.isIdle())
394
+ return;
395
+ switching = { pid: undefined, startedAt: now() };
396
+ deps.log("autoupdate.switching", { from: running, to: installed });
397
+ switching.pid = spawnChild(["runtime-switch", installed], (code) => {
398
+ if (switching)
399
+ switching = undefined;
400
+ if (code !== 0)
401
+ deps.log("autoupdate.restart_refused", { version: installed, code });
402
+ deps.onChange?.();
403
+ });
404
+ return;
405
+ }
406
+ if (state.lastError?.version === wanted) {
407
+ const failure = state.lastError;
408
+ const attempts = failure.attempts ?? 1;
409
+ const backoff = (attempts <= 1 ? 15 : attempts === 2 ? 60 : 240) * 60000;
410
+ const age = now() - Date.parse(failure.at);
411
+ if (age >= 0 && age < Math.min(backoff, checkIntervalMs))
412
+ return;
413
+ }
414
+ deps.log("autoupdate.installing", { version: wanted });
415
+ const pid = spawnChild(["self-update", wanted, "--channel", channelOf(running)], (code) => {
416
+ deps.log(code === 0 ? "autoupdate.installed" : "autoupdate.install_failed", { version: wanted, code });
417
+ updateState(({ installing: _installing, ...rest }) => ({
418
+ ...rest,
419
+ ...code === 0 ? {} : { lastError: { message: "the installer failed", at: new Date(now()).toISOString(), version: wanted, attempts: 1 + (rest.lastError?.version === wanted ? rest.lastError.attempts ?? 1 : 0) } }
420
+ }));
421
+ deps.onChange?.();
422
+ if (code === 0)
423
+ tick();
424
+ });
425
+ if (pid)
426
+ updateState((rest) => ({ ...rest, installing: { version: wanted, pid, startedAt: now() } }));
427
+ } catch (error) {
428
+ deps.log("autoupdate.error", { error: error.message });
429
+ } finally {
430
+ busy = false;
431
+ }
432
+ }
433
+ return {
434
+ tick,
435
+ start(intervalMs = Number(env.OPENCODE_BROWSER_AUTO_UPDATE_TICK_MS) || 10 * 60000) {
436
+ timer = setInterval(() => void tick(), intervalMs);
437
+ timer.unref();
438
+ setTimeout(() => void tick(), Math.min(intervalMs, 60000)).unref();
439
+ },
440
+ stop() {
441
+ clearInterval(timer);
442
+ }
443
+ };
444
+ }
445
+ function spawnRuntimeChild(runtime, args, onExit, env = process.env) {
446
+ const { OPENCODE_BROWSER_MANAGED_RELAY: _managed, OPENCODE_BROWSER_RESTART_REQUEST_ID: _request, ...rest } = env;
447
+ const directory = path2.join(stateRoot(), "logs");
448
+ mkdirSync(directory, { recursive: true, mode: 448 });
449
+ const log = openSync(path2.join(directory, "auto-update.log"), "a", 384);
450
+ try {
451
+ const [file, ...prefix] = entryCommand(runtime.entry);
452
+ const child = spawn(file, [...prefix, ...args], { detached: true, stdio: ["ignore", log, log], env: rest });
453
+ child.on("error", () => onExit(null));
454
+ child.on("exit", (code) => onExit(code));
455
+ child.unref();
456
+ return child.pid;
457
+ } catch {
458
+ onExit(null);
459
+ return;
460
+ } finally {
461
+ closeSync(log);
462
+ }
463
+ }
464
+
465
+ export { configRoot2, dataRoot, stateRoot, cacheRoot, binRoot, installedBinaryPath, oldStoreMarker, fromCheckout, compiledBinary, binaryPackage, binaryName, scriptEntry, entryCommand, runningEntry, checkoutRoot, cliCommand, PUBLIC_STORE_ID, storeConfig, devExtension, devExtensionUrl, devExtensionFolder, storeUrl, installCommand, autoUpdateModes, UPDATE_VERSION, channelOf, compareVersions, installedRuntime2, installedVersion, updateState, autoUpdateOverride, storedMode, effectiveMode, setStoredMode, autoUpdateStatus, describeAutoUpdate, runCommand, registryUrl, fetchPublished, runInstaller, createAutoUpdater };
@@ -0,0 +1,157 @@
1
+ import {
2
+ writePrivateJsonFileSync
3
+ } from "./main-vgzr4689.mjs";
4
+ import {
5
+ dataRoot,
6
+ stateRoot
7
+ } from "./main-j2ehvkhk.mjs";
8
+
9
+ // src/relay/browser-pairing.ts
10
+ import crypto from "node:crypto";
11
+ import fs from "node:fs";
12
+ import path from "node:path";
13
+ var legacyContext = "opencode-browser-pairing-v2";
14
+ var context = "opencode-browser-pairing-v3";
15
+ var crockford = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
16
+ var pairingCodeLength = 8;
17
+ var codeKeyIterations = 1e5;
18
+ var codeKeySalt = `${context}|code`;
19
+ var pairingCodeTtlMs = 10 * 60000;
20
+ var bundledPairingCodeTtlMs = 60 * 60000;
21
+ var maxPairingFailures = 5;
22
+ var maxPendingCodes = 5;
23
+ var extensionPairingFileName = "relay-pairing.json";
24
+ var pairingCodesPath = (root = stateRoot()) => path.join(root, "pairing-codes.json");
25
+ var browserTokensPath = (root = dataRoot()) => path.join(root, "browser-tokens.json");
26
+ var legacyPairingCodePath = (root = dataRoot()) => path.join(root, "extension-pairing");
27
+ function formatPairingCode(code) {
28
+ return code.match(/.{1,4}/g)?.join("-") ?? code;
29
+ }
30
+ function pairingCodeKey(code) {
31
+ return crypto.pbkdf2Sync(code, codeKeySalt, codeKeyIterations, 32, "sha256").toString("hex");
32
+ }
33
+ function readPendingCodes(root, now) {
34
+ try {
35
+ const value = JSON.parse(fs.readFileSync(pairingCodesPath(root), "utf8"));
36
+ const codes = Array.isArray(value.codes) ? value.codes.filter((entry) => typeof entry?.key === "string" && /^[0-9a-f]{64}$/.test(entry.key) && typeof entry.expiresAt === "number" && entry.expiresAt >= now) : [];
37
+ return { codes, failures: typeof value.failures === "number" ? value.failures : 0 };
38
+ } catch {
39
+ return { codes: [], failures: 0 };
40
+ }
41
+ }
42
+ function writePendingCodes(root, pending) {
43
+ if (pending.codes.length === 0 && pending.failures === 0) {
44
+ fs.rmSync(pairingCodesPath(root), { force: true });
45
+ return;
46
+ }
47
+ writePrivateJsonFileSync(pairingCodesPath(root), pending, { ensureParent: true });
48
+ }
49
+ function mintPairingCode(root = stateRoot(), options = {}) {
50
+ const now = options.now ?? Date.now();
51
+ const code = Array.from(crypto.randomBytes(pairingCodeLength), (byte) => crockford[byte & 31]).join("");
52
+ const pending = readPendingCodes(root, now);
53
+ pending.codes.push({ key: pairingCodeKey(code), expiresAt: now + (options.ttlMs ?? pairingCodeTtlMs), ...options.receipt ? { receipt: options.receipt } : {} });
54
+ writePendingCodes(root, { codes: pending.codes.slice(-maxPendingCodes), failures: 0 });
55
+ return code;
56
+ }
57
+ function pendingPairingCodeKeys(root = stateRoot(), now = Date.now()) {
58
+ return readPendingCodes(root, now).codes.map((entry) => entry.key);
59
+ }
60
+ function consumePairingCode(key, root = stateRoot(), now = Date.now()) {
61
+ const pending = readPendingCodes(root, now);
62
+ writePendingCodes(root, { codes: pending.codes.filter((entry) => entry.key !== key), failures: 0 });
63
+ return pending.codes.find((entry) => entry.key === key)?.receipt;
64
+ }
65
+ function recordPairingFailure(root = stateRoot(), now = Date.now()) {
66
+ const pending = readPendingCodes(root, now);
67
+ const failures = pending.failures + 1;
68
+ const exhausted = failures >= maxPairingFailures;
69
+ writePendingCodes(root, exhausted ? { codes: [], failures: 0 } : { codes: pending.codes, failures });
70
+ return exhausted && pending.codes.length > 0;
71
+ }
72
+ function writeExtensionPairing(extensionDirectory, code) {
73
+ writePrivateJsonFileSync(path.join(extensionDirectory, extensionPairingFileName), { code });
74
+ }
75
+ function readBrowserPairings(root = dataRoot()) {
76
+ try {
77
+ const value = JSON.parse(fs.readFileSync(browserTokensPath(root), "utf8"));
78
+ if (value === null || typeof value !== "object" || Array.isArray(value))
79
+ return {};
80
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => typeof entry?.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(entry.token)));
81
+ } catch {
82
+ return {};
83
+ }
84
+ }
85
+ function writeBrowserPairings(root, pairings) {
86
+ writePrivateJsonFileSync(browserTokensPath(root), pairings, { ensureParent: true });
87
+ }
88
+ function browserToken(key, root = dataRoot()) {
89
+ return readBrowserPairings(root)[key]?.token;
90
+ }
91
+ var newBrowserToken = () => crypto.randomBytes(32).toString("base64url");
92
+ function issueBrowserToken(key, root = dataRoot(), now = Date.now(), token = newBrowserToken(), receipt) {
93
+ const pairings = readBrowserPairings(root);
94
+ writeBrowserPairings(root, { ...pairings, [key]: { token, pairedAt: now, ...receipt ? { receipt } : {} } });
95
+ return token;
96
+ }
97
+ function touchBrowserPairing(key, seen, root = dataRoot(), now = Date.now()) {
98
+ const pairings = readBrowserPairings(root);
99
+ const entry = pairings[key];
100
+ if (!entry)
101
+ return;
102
+ writeBrowserPairings(root, { ...pairings, [key]: { ...entry, lastSeen: now, id: seen.id, name: seen.name } });
103
+ }
104
+ function revokeBrowserToken(key, root = dataRoot()) {
105
+ const pairings = readBrowserPairings(root);
106
+ if (!(key in pairings))
107
+ return false;
108
+ delete pairings[key];
109
+ writeBrowserPairings(root, pairings);
110
+ return true;
111
+ }
112
+ function legacyPairingCode(root = dataRoot()) {
113
+ try {
114
+ const code = fs.readFileSync(legacyPairingCodePath(root), "utf8").trim();
115
+ return new RegExp(`^[${crockford}]{32}$`).test(code) ? code : undefined;
116
+ } catch {
117
+ return;
118
+ }
119
+ }
120
+ function removeLegacyPairingCode(root = dataRoot()) {
121
+ const existed = legacyPairingCode(root) !== undefined;
122
+ fs.rmSync(legacyPairingCodePath(root), { force: true });
123
+ return existed;
124
+ }
125
+ function legacyPairingProof(code, role, port, ownNonce, peerNonce) {
126
+ return crypto.createHmac("sha256", code).update(`${legacyContext}|${role}|${pairingEndpoint(port)}|${peerNonce}|${ownNonce}`).digest("base64url");
127
+ }
128
+ function pairingEndpoint(port) {
129
+ return `127.0.0.1:${port}/extension`;
130
+ }
131
+ function pairingProof(token, role, port, ownNonce, peerNonce) {
132
+ return crypto.createHmac("sha256", token).update(`${context}|${role}|${pairingEndpoint(port)}|${peerNonce}|${ownNonce}`).digest("base64url");
133
+ }
134
+ function ecdhExchange(peerPublicKey) {
135
+ const peer = Buffer.from(peerPublicKey, "base64url");
136
+ if (peer.length !== 65 || peer[0] !== 4)
137
+ return;
138
+ const ecdh = crypto.createECDH("prime256v1");
139
+ const publicKey = ecdh.generateKeys().toString("base64url");
140
+ try {
141
+ return { publicKey, secret: ecdh.computeSecret(peer) };
142
+ } catch {
143
+ return;
144
+ }
145
+ }
146
+ function pairingSessionKey(material, secret, transcript) {
147
+ return crypto.createHmac("sha256", material).update(`${context}|session|${pairingEndpoint(transcript.port)}|${transcript.extensionNonce}|${transcript.relayNonce}|${transcript.extensionKey}|${transcript.relayKey}|`).update(secret).digest();
148
+ }
149
+ function sessionProof(sessionKey, role) {
150
+ return crypto.createHmac("sha256", sessionKey).update(`${context}|proof|${role}`).digest("base64url");
151
+ }
152
+ function wrapToken(sessionKey, token) {
153
+ const mask = crypto.createHmac("sha256", sessionKey).update(`${context}|wrap`).digest();
154
+ return Buffer.from(Buffer.from(token, "base64url").map((byte, index) => byte ^ mask[index])).toString("base64url");
155
+ }
156
+
157
+ export { context, pairingCodeTtlMs, bundledPairingCodeTtlMs, formatPairingCode, pairingCodeKey, mintPairingCode, pendingPairingCodeKeys, consumePairingCode, recordPairingFailure, writeExtensionPairing, readBrowserPairings, browserToken, newBrowserToken, issueBrowserToken, touchBrowserPairing, revokeBrowserToken, legacyPairingCode, removeLegacyPairingCode, legacyPairingProof, pairingProof, ecdhExchange, pairingSessionKey, sessionProof, wrapToken };