@opencode/browse 0.0.11-dev.76 → 0.0.11-dev.78

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-e9x2hzbm.mjs} +63 -52
  2. package/dist/cli.mjs +30 -19
  3. package/dist/{helpers-kp0j46jt.mjs → helpers-681ybn8r.mjs} +2 -2
  4. package/dist/{index-0dcypq31.mjs → index-yzz55kxm.mjs} +1 -1
  5. package/dist/{main-eej5z0y5.mjs → main-0yxzwqt8.mjs} +6 -6
  6. package/dist/main-1ja7rnnp.mjs +4 -0
  7. package/dist/main-3d4mj1xj.mjs +157 -0
  8. package/dist/main-4qeb707s.mjs +161 -0
  9. package/dist/{main-rt6g5418.mjs → main-8z9d979q.mjs} +15 -15
  10. package/dist/{main-nqmm7pdz.mjs → main-93xmqcr3.mjs} +47 -47
  11. package/dist/{main-gevbt7h7.mjs → main-csnx585b.mjs} +151 -151
  12. package/dist/{setup-j76yv51b.mjs → main-fkskfb8a.mjs} +3608 -4406
  13. package/dist/main-ftsbt0hk.mjs +73 -0
  14. package/dist/{main-brv9dhy5.mjs → main-gdvgbgce.mjs} +9 -9
  15. package/dist/{main-ajza8egc.mjs → main-mysz5yma.mjs} +44 -39
  16. package/dist/main-qzvstggv.mjs +465 -0
  17. package/dist/main-vgzr4689.mjs +61 -0
  18. package/dist/{mcp-sy8qgkyr.mjs → mcp-3v0wxzr5.mjs} +139 -138
  19. package/dist/migrate-5phz1hha.mjs +233 -0
  20. package/dist/{relay-ateyg5ax.mjs → relay-4chyv51v.mjs} +128 -123
  21. package/dist/runtime-update-pzazb7sh.mjs +156 -0
  22. package/dist/setup-5g5kza58.mjs +956 -0
  23. package/dist/{skill-text-x7sccp6h.mjs → skill-text-mrxy6zpc.mjs} +5 -4
  24. package/dist/{supervisor-0rvjpf4e.mjs → supervisor-bfrn5cxb.mjs} +38 -17
  25. package/dist/{update-rbd2025v.mjs → update-42j1j7w1.mjs} +3 -3
  26. package/dist/{version-4cjr3wpp.mjs → version-w0dwcyve.mjs} +1 -1
  27. package/package.json +1 -1
  28. package/skills/browse/SKILL.md +5 -4
  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-1ja7rnnp.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.78", 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.78.zip", sha256: "3e8dbaa111534c43858d59017c52b96e1f4e693cd58f5d02db5fccd8b94fc561", size: 182561 }) {
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,61 @@
1
+ import {
2
+ isString
3
+ } from "./main-yf9xhpn4.mjs";
4
+ // src/fs-durability.ts
5
+ import crypto from "node:crypto";
6
+ import fsSync from "node:fs";
7
+ import fs from "node:fs/promises";
8
+ import path from "node:path";
9
+ var unsupportedDirectorySyncCodes = new Set(["EPERM", "EINVAL", "ENOTSUP"]);
10
+ function isNodeError(error) {
11
+ return error instanceof Error && "code" in error;
12
+ }
13
+ function isUnsupportedDirectorySyncError(error) {
14
+ return isNodeError(error) && isString(error.code) && unsupportedDirectorySyncCodes.has(error.code);
15
+ }
16
+ async function writeJsonFileAtomically(filePath, value, options = {}) {
17
+ const directory = path.dirname(filePath);
18
+ await fs.mkdir(directory, {
19
+ recursive: true,
20
+ ...options.dirMode === undefined ? {} : { mode: options.dirMode }
21
+ });
22
+ if (options.dirMode !== undefined) {
23
+ await fs.chmod(directory, options.dirMode);
24
+ }
25
+ const temporaryPath = `${filePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
26
+ let renamed = false;
27
+ try {
28
+ await fs.writeFile(temporaryPath, `${JSON.stringify(value, null, 2)}
29
+ `, { mode: 384 });
30
+ await fs.rename(temporaryPath, filePath);
31
+ renamed = true;
32
+ await fs.chmod(filePath, 384);
33
+ } finally {
34
+ if (!renamed)
35
+ await fs.rm(temporaryPath, { force: true }).catch(() => {});
36
+ }
37
+ }
38
+ function ensurePrivateDirectorySync(directory) {
39
+ fsSync.mkdirSync(directory, { recursive: true, mode: 448 });
40
+ if (process.platform !== "win32")
41
+ fsSync.chmodSync(directory, 448);
42
+ }
43
+ function writePrivateJsonFileSync(filePath, value, options = {}) {
44
+ if (options.ensureParent)
45
+ ensurePrivateDirectorySync(path.dirname(filePath));
46
+ const temporaryPath = `${filePath}.${process.pid}.${crypto.randomUUID()}.tmp`;
47
+ let renamed = false;
48
+ try {
49
+ fsSync.writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}
50
+ `, { mode: 384 });
51
+ fsSync.renameSync(temporaryPath, filePath);
52
+ renamed = true;
53
+ if (process.platform !== "win32")
54
+ fsSync.chmodSync(filePath, 384);
55
+ } finally {
56
+ if (!renamed)
57
+ fsSync.rmSync(temporaryPath, { force: true });
58
+ }
59
+ }
60
+
61
+ export { isNodeError, isUnsupportedDirectorySyncError, writeJsonFileAtomically, ensurePrivateDirectorySync, writePrivateJsonFileSync };