@opencode/browse 0.0.11-dev.75 → 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-5980z4hc.mjs → cli-mx6tbg2m.mjs} +63 -52
- package/dist/cli.mjs +30 -19
- package/dist/{helpers-h1mvscyw.mjs → helpers-hgm1z9h5.mjs} +2 -2
- package/dist/{index-0dcypq31.mjs → index-yzz55kxm.mjs} +1 -1
- package/dist/{main-d1hydckg.mjs → main-1fdejpga.mjs} +9 -9
- package/dist/{main-tcae6pr3.mjs → main-6chyyr6j.mjs} +44 -39
- package/dist/{main-rt6g5418.mjs → main-8z9d979q.mjs} +15 -15
- package/dist/{setup-q1sfzdr9.mjs → main-b7g6460c.mjs} +3608 -4406
- package/dist/{main-gevbt7h7.mjs → main-csnx585b.mjs} +151 -151
- package/dist/{main-j38051kb.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-5vffh0gd.mjs → main-zq79yb8r.mjs} +6 -6
- package/dist/main-zya5ttbr.mjs +4 -0
- package/dist/{mcp-x1vq2n6t.mjs → mcp-h0qcxhqc.mjs} +138 -137
- package/dist/migrate-pgckfkg5.mjs +233 -0
- package/dist/{relay-94r2w21z.mjs → relay-gafgjtav.mjs} +191 -129
- 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-e2w15458.mjs → supervisor-06t66v4t.mjs} +38 -17
- package/dist/{update-c8xwkt5v.mjs → update-7hagfdc0.mjs} +3 -3
- package/dist/{version-0jtmhnzb.mjs → version-hhcvk9wm.mjs} +1 -1
- package/package.json +1 -1
- package/skills/browse/SKILL.md +2 -2
- package/dist/main-jkq3ey3t.mjs +0 -805
- package/dist/main-nhr7bg32.mjs +0 -131
- package/dist/main-s5mqta5j.mjs +0 -303
- package/dist/main-wpbmhp3v.mjs +0 -4
- package/dist/runtime-update-g516gc7h.mjs +0 -200
package/dist/main-jkq3ey3t.mjs
DELETED
|
@@ -1,805 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
opencodeBrowserVersion2
|
|
3
|
-
} from "./main-wpbmhp3v.mjs";
|
|
4
|
-
|
|
5
|
-
// src/update/auto-update.ts
|
|
6
|
-
import { spawn } from "node:child_process";
|
|
7
|
-
import { createHash } from "node:crypto";
|
|
8
|
-
import { chmodSync, closeSync, copyFileSync, cpSync, existsSync, linkSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
9
|
-
import { createRequire } from "node:module";
|
|
10
|
-
import path2 from "node:path";
|
|
11
|
-
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
12
|
-
import { gunzipSync } from "node:zlib";
|
|
13
|
-
|
|
14
|
-
// src/paths.ts
|
|
15
|
-
import fs from "node:fs";
|
|
16
|
-
import os from "node:os";
|
|
17
|
-
import path from "node:path";
|
|
18
|
-
import { fileURLToPath } from "node:url";
|
|
19
|
-
function dataRoot(home = os.homedir()) {
|
|
20
|
-
const override = process.env.OPENCODE_BROWSER_HOME;
|
|
21
|
-
if (override)
|
|
22
|
-
return override;
|
|
23
|
-
if (process.platform === "win32")
|
|
24
|
-
return path.join(process.env.LOCALAPPDATA ?? path.join(home, "AppData", "Local"), "opencode-browser");
|
|
25
|
-
const xdg = home === os.homedir() ? process.env.XDG_DATA_HOME : undefined;
|
|
26
|
-
return path.join(xdg ?? path.join(home, ".local", "share"), "opencode-browser");
|
|
27
|
-
}
|
|
28
|
-
var packageRoot = () => path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
|
29
|
-
var oldStoreMarker = () => path.join(dataRoot(), "old-store-extension");
|
|
30
|
-
function fromCheckout() {
|
|
31
|
-
return !compiledBinary() && fs.existsSync(path.join(packageRoot(), "src", "main.ts"));
|
|
32
|
-
}
|
|
33
|
-
var compiledBinary = () => globalThis.__OPENCODE_BROWSER_COMPILED__ === true;
|
|
34
|
-
var binaryPackage = () => globalThis.__OPENCODE_BROWSER_TARGET__ ? `@opencode/browse-${globalThis.__OPENCODE_BROWSER_TARGET__}` : undefined;
|
|
35
|
-
var binaryName = (platform = process.platform) => platform === "win32" ? "browse.exe" : "browse";
|
|
36
|
-
var scriptEntry = (entry) => /\.[cm]?[jt]s$/.test(entry);
|
|
37
|
-
var entryCommand = (entry, node = process.execPath) => scriptEntry(entry) ? [node, entry] : [entry];
|
|
38
|
-
function installedBinary() {
|
|
39
|
-
try {
|
|
40
|
-
const binary = JSON.parse(fs.readFileSync(path.join(dataRoot(), "runtime", "current.json"), "utf8")).binary;
|
|
41
|
-
return typeof binary === "string" ? binary : undefined;
|
|
42
|
-
} catch {
|
|
43
|
-
return;
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
var runningEntry = () => compiledBinary() ? process.execPath : process.argv[1];
|
|
47
|
-
function checkoutRoot() {
|
|
48
|
-
return fromCheckout() ? path.dirname(packageRoot()) : undefined;
|
|
49
|
-
}
|
|
50
|
-
var quoted = (value) => /^[\w@%+=:,./-]+$/.test(value) ? value : JSON.stringify(value);
|
|
51
|
-
function cliInstall() {
|
|
52
|
-
if (compiledBinary())
|
|
53
|
-
return { kind: "binary", binary: installedBinary() ?? process.execPath, pathEnv: process.env.PATH };
|
|
54
|
-
if (fromCheckout())
|
|
55
|
-
return { kind: "checkout", bundle: path.join(packageRoot(), "dist", "cli.mjs") };
|
|
56
|
-
return { kind: "npm", version: "0.0.11-dev.75" };
|
|
57
|
-
}
|
|
58
|
-
function cliPrefix(install = cliInstall()) {
|
|
59
|
-
if (install.kind === "binary") {
|
|
60
|
-
const dir = path.dirname(install.binary);
|
|
61
|
-
const onPath = (install.pathEnv ?? "").split(path.delimiter).some((entry) => entry && path.resolve(entry) === dir);
|
|
62
|
-
return onPath ? "browse" : quoted(install.binary);
|
|
63
|
-
}
|
|
64
|
-
if (install.kind === "checkout")
|
|
65
|
-
return `node ${quoted(install.bundle)}`;
|
|
66
|
-
return install.version?.includes("-dev.") ? "npx @opencode/browse@dev" : "npx @opencode/browse";
|
|
67
|
-
}
|
|
68
|
-
var cliCommand = (args, install = cliInstall()) => `${cliPrefix(install)} ${args}`;
|
|
69
|
-
var STORE_ITEM_ID = /^[a-p]{32}$/;
|
|
70
|
-
var PUBLIC_STORE_ID = "mfnicocicmmlkpjnaffgihfjhdgjkdjg";
|
|
71
|
-
function storeConfig(env = process.env, baked = { id: "mfnicocicmmlkpjnaffgihfjhdgjkdjg" }) {
|
|
72
|
-
const id = [env.OPENCODE_BROWSER_STORE_ID, baked?.id].find((value) => value && STORE_ITEM_ID.test(value));
|
|
73
|
-
return id ? { id } : {};
|
|
74
|
-
}
|
|
75
|
-
var RELEASE_SERVICE = "https://anoma.ly/release";
|
|
76
|
-
function devExtension(baked = { file: "browse-extension-0.0.11-dev.75.zip", sha256: "231c4d7c28c6f5d35763f22c949604fbc25b92a2e6cd13a764d7df98b8b56b85", size: 182613 }) {
|
|
77
|
-
return baked && /^[0-9a-f]{64}$/.test(baked.sha256) && /^[\w.-]+\.zip$/.test(baked.file) ? baked : undefined;
|
|
78
|
-
}
|
|
79
|
-
var devExtensionUrl = (extension, env = process.env) => `${(env.OPENCODE_BROWSER_RELEASE_SERVICE || RELEASE_SERVICE).replace(/\/+$/, "")}/browse/files/${extension.sha256}/${extension.file}`;
|
|
80
|
-
var devExtensionFolder = (root = dataRoot()) => path.join(root, "extension");
|
|
81
|
-
var storeUrl = (id) => `https://chromewebstore.google.com/detail/${id}`;
|
|
82
|
-
function installCommand() {
|
|
83
|
-
return fromCheckout() ? `cd ${quoted(path.dirname(packageRoot()))} && bun run setup` : cliCommand("install");
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// src/update/auto-update.ts
|
|
87
|
-
var PACKAGE_NAME = "@opencode/browse";
|
|
88
|
-
var DAY_MS = 24 * 60 * 60 * 1000;
|
|
89
|
-
var DEFAULT_REGISTRY = "https://registry.npmjs.org";
|
|
90
|
-
var autoUpdateModes = ["on", "notify", "off"];
|
|
91
|
-
function runtimeLayout(root = dataRoot()) {
|
|
92
|
-
const runtime = path2.join(root, "runtime");
|
|
93
|
-
return {
|
|
94
|
-
root,
|
|
95
|
-
runtime,
|
|
96
|
-
versions: path2.join(runtime, "versions"),
|
|
97
|
-
current: path2.join(runtime, "current.json"),
|
|
98
|
-
shim: path2.join(root, "bin", "opencode-browser.mjs"),
|
|
99
|
-
state: path2.join(root, "auto-update.json")
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
var versionDirectory = (layout, version) => path2.join(layout.versions, version);
|
|
103
|
-
var versionEntry = (layout, version, binary = compiledBinary()) => binary ? path2.join(versionDirectory(layout, version), binaryName()) : path2.join(versionDirectory(layout, version), "node_modules", "@opencode", "browse", "dist", "cli.mjs");
|
|
104
|
-
var updatePackage = () => (compiledBinary() ? binaryPackage() : undefined) ?? PACKAGE_NAME;
|
|
105
|
-
var channelOf = (version) => version.includes("-dev.") ? "dev" : "latest";
|
|
106
|
-
var UPDATE_VERSION = /^(\d+)\.(\d+)\.(\d+)(?:-dev\.(\d+)(?:\.(\d+))?)?$/;
|
|
107
|
-
function compareVersions(left, right) {
|
|
108
|
-
const parse = (value) => {
|
|
109
|
-
const match = UPDATE_VERSION.exec(value);
|
|
110
|
-
if (!match)
|
|
111
|
-
return;
|
|
112
|
-
const release = match[4] === undefined ? 1 : 0;
|
|
113
|
-
return [Number(match[1]), Number(match[2]), Number(match[3]), release, Number(match[4] ?? 0), Number(match[5] ?? 0)];
|
|
114
|
-
};
|
|
115
|
-
const a = parse(left);
|
|
116
|
-
const b = parse(right);
|
|
117
|
-
if (!a || !b)
|
|
118
|
-
return 0;
|
|
119
|
-
for (let index = 0;index < a.length; index++)
|
|
120
|
-
if (a[index] !== b[index])
|
|
121
|
-
return a[index] < b[index] ? -1 : 1;
|
|
122
|
-
return 0;
|
|
123
|
-
}
|
|
124
|
-
function readJson(file) {
|
|
125
|
-
try {
|
|
126
|
-
return JSON.parse(readFileSync(file, "utf8"));
|
|
127
|
-
} catch {
|
|
128
|
-
return;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
function writeJsonAtomic(file, value) {
|
|
132
|
-
mkdirSync(path2.dirname(file), { recursive: true });
|
|
133
|
-
const temporary = `${file}.${process.pid}.tmp`;
|
|
134
|
-
writeFileSync(temporary, JSON.stringify(value, null, 2) + `
|
|
135
|
-
`, { mode: 384 });
|
|
136
|
-
renameSync(temporary, file);
|
|
137
|
-
}
|
|
138
|
-
function readCurrent(layout = runtimeLayout()) {
|
|
139
|
-
const current = readJson(layout.current);
|
|
140
|
-
return current && typeof current.version === "string" ? current : undefined;
|
|
141
|
-
}
|
|
142
|
-
function writeCurrent(layout, current) {
|
|
143
|
-
writeJsonAtomic(layout.current, { ...current, switchedAt: new Date().toISOString() });
|
|
144
|
-
}
|
|
145
|
-
function readState(layout = runtimeLayout()) {
|
|
146
|
-
return readJson(layout.state) ?? {};
|
|
147
|
-
}
|
|
148
|
-
function updateState(layout, change) {
|
|
149
|
-
const next = change(readState(layout));
|
|
150
|
-
writeJsonAtomic(layout.state, next);
|
|
151
|
-
return next;
|
|
152
|
-
}
|
|
153
|
-
var realpath = (file) => {
|
|
154
|
-
try {
|
|
155
|
-
return realpathSync(file);
|
|
156
|
-
} catch {
|
|
157
|
-
return path2.resolve(file);
|
|
158
|
-
}
|
|
159
|
-
};
|
|
160
|
-
function npmRuntime(options = {}) {
|
|
161
|
-
if (options.checkout ?? fromCheckout())
|
|
162
|
-
return;
|
|
163
|
-
const layout = options.layout ?? runtimeLayout();
|
|
164
|
-
if (compiledBinary())
|
|
165
|
-
return binaryRuntime(layout);
|
|
166
|
-
const defaultEntry = () => fileURLToPath2(import.meta.url.endsWith(".ts") ? import.meta.url : new URL("./cli.mjs", import.meta.url));
|
|
167
|
-
const entry = realpath(options.entry ?? defaultEntry());
|
|
168
|
-
const relative = path2.relative(realpath(layout.versions), entry).split(path2.sep);
|
|
169
|
-
if (relative.length !== 6 || relative[0] === ".." || relative.slice(1).join("/") !== "node_modules/@opencode/browse/dist/cli.mjs")
|
|
170
|
-
return;
|
|
171
|
-
const current = readCurrent(layout);
|
|
172
|
-
if (!current)
|
|
173
|
-
return;
|
|
174
|
-
return { layout, version: relative[0], current };
|
|
175
|
-
}
|
|
176
|
-
function binaryRuntime(layout) {
|
|
177
|
-
const current = readCurrent(layout);
|
|
178
|
-
if (!current?.binary)
|
|
179
|
-
return;
|
|
180
|
-
const self = realpath(process.execPath);
|
|
181
|
-
const inVersions = !path2.relative(realpath(layout.versions), self).startsWith("..");
|
|
182
|
-
if (self !== realpath(current.binary) && !inVersions)
|
|
183
|
-
return;
|
|
184
|
-
return { layout, version: opencodeBrowserVersion2, current };
|
|
185
|
-
}
|
|
186
|
-
function autoUpdateOverride(env = process.env) {
|
|
187
|
-
const value = env.OPENCODE_BROWSER_AUTO_UPDATE?.trim().toLowerCase();
|
|
188
|
-
if (value === "on" || value === "1" || value === "true")
|
|
189
|
-
return "on";
|
|
190
|
-
if (value === "notify")
|
|
191
|
-
return "notify";
|
|
192
|
-
if (value === "off" || value === "0" || value === "false")
|
|
193
|
-
return "off";
|
|
194
|
-
if (env.OPENCODE_BROWSER_UPDATE_CHECK === "0")
|
|
195
|
-
return "off";
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
function storedMode(layout = runtimeLayout()) {
|
|
199
|
-
const mode = readState(layout).mode;
|
|
200
|
-
return mode && autoUpdateModes.includes(mode) ? mode : "on";
|
|
201
|
-
}
|
|
202
|
-
function effectiveMode(layout = runtimeLayout(), env = process.env) {
|
|
203
|
-
return autoUpdateOverride(env) ?? storedMode(layout);
|
|
204
|
-
}
|
|
205
|
-
function setStoredMode(mode, layout = runtimeLayout()) {
|
|
206
|
-
updateState(layout, (state) => ({ ...state, mode }));
|
|
207
|
-
}
|
|
208
|
-
function autoUpdateStatus(options = {}) {
|
|
209
|
-
const layout = options.layout ?? runtimeLayout();
|
|
210
|
-
const env = options.env ?? process.env;
|
|
211
|
-
const runtime = options.runtime === undefined ? npmRuntime({ layout }) : options.runtime;
|
|
212
|
-
const state = readState(layout);
|
|
213
|
-
const override = autoUpdateOverride(env);
|
|
214
|
-
const current = runtime?.current ?? readCurrent(layout);
|
|
215
|
-
const install = runtime ? "npm" : fromCheckout() ? "checkout" : current ? "npm" : "other";
|
|
216
|
-
return {
|
|
217
|
-
install,
|
|
218
|
-
cli: cliPrefix(),
|
|
219
|
-
mode: storedMode(layout),
|
|
220
|
-
effective: install === "npm" ? override ?? storedMode(layout) : "off",
|
|
221
|
-
...override ? { overriddenBy: env.OPENCODE_BROWSER_AUTO_UPDATE !== undefined ? "OPENCODE_BROWSER_AUTO_UPDATE" : "OPENCODE_BROWSER_UPDATE_CHECK" } : {},
|
|
222
|
-
...current ? { version: current.version, channel: current.channel } : {},
|
|
223
|
-
...current?.previous && existsSync(versionEntry(layout, current.previous)) ? { previous: current.previous } : {},
|
|
224
|
-
...state.latest ? { latest: state.latest } : {},
|
|
225
|
-
...state.pending ? { pending: state.pending } : {},
|
|
226
|
-
...state.skipped ? { skipped: state.skipped } : {},
|
|
227
|
-
...state.checkedAt ? { checkedAt: new Date(state.checkedAt).toISOString() } : {},
|
|
228
|
-
...state.lastUpdate ? { lastUpdate: state.lastUpdate } : {},
|
|
229
|
-
...state.lastError ? { lastError: state.lastError } : {}
|
|
230
|
-
};
|
|
231
|
-
}
|
|
232
|
-
function describeAutoUpdate(status) {
|
|
233
|
-
if (status.install === "checkout")
|
|
234
|
-
return "Updates: checkout install; `update` pulls new commits";
|
|
235
|
-
if (status.install !== "npm")
|
|
236
|
-
return "Updates: not an installed runtime";
|
|
237
|
-
const mode = { on: "automatic", notify: "notify only", off: "off" }[status.effective];
|
|
238
|
-
const parts = [`${mode}${status.overriddenBy ? ` (set by ${status.overriddenBy})` : ""}`, `channel ${status.channel ?? "latest"}`];
|
|
239
|
-
if (status.pending)
|
|
240
|
-
parts.push(`${status.pending} installed, switches in when no agent is using the browser`);
|
|
241
|
-
else if (status.latest && status.latest === status.skipped)
|
|
242
|
-
parts.push(`skipping ${status.latest} (rolled back from it; \`update\` installs it again)`);
|
|
243
|
-
else if (status.latest && status.version && compareVersions(status.latest, status.version) > 0)
|
|
244
|
-
parts.push(`${status.latest} available`);
|
|
245
|
-
if (status.previous && status.version && compareVersions(status.previous, status.version) < 0)
|
|
246
|
-
parts.push(`\`rollback\` returns to ${status.previous}`);
|
|
247
|
-
if (status.lastError)
|
|
248
|
-
parts.push(`last attempt failed: ${status.lastError.message}`);
|
|
249
|
-
return `Updates: ${parts.join("; ")}`;
|
|
250
|
-
}
|
|
251
|
-
var runCommand = (command, args, options = {}) => new Promise((resolve) => {
|
|
252
|
-
const npmCli = process.platform === "win32" && command === "npm" ? path2.join(path2.dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js") : undefined;
|
|
253
|
-
const [file, argv] = npmCli && existsSync(npmCli) ? [process.execPath, [npmCli, ...args]] : [command, args];
|
|
254
|
-
const child = spawn(file, argv, { env: options.env ?? process.env, stdio: ["ignore", "pipe", "pipe"] });
|
|
255
|
-
let stdout = "";
|
|
256
|
-
let stderr = "";
|
|
257
|
-
child.stdout.setEncoding("utf8").on("data", (chunk) => void (stdout += chunk));
|
|
258
|
-
child.stderr.setEncoding("utf8").on("data", (chunk) => void (stderr += chunk));
|
|
259
|
-
const timer = setTimeout(() => child.kill(), options.timeoutMs ?? 120000);
|
|
260
|
-
child.on("error", (error) => {
|
|
261
|
-
clearTimeout(timer);
|
|
262
|
-
resolve({ status: null, stdout, stderr: stderr + error.message });
|
|
263
|
-
});
|
|
264
|
-
child.on("close", (status) => {
|
|
265
|
-
clearTimeout(timer);
|
|
266
|
-
resolve({ status, stdout, stderr });
|
|
267
|
-
});
|
|
268
|
-
});
|
|
269
|
-
async function registryUrl(run = runCommand, env = process.env) {
|
|
270
|
-
const override = env.OPENCODE_BROWSER_NPM_REGISTRY?.trim();
|
|
271
|
-
const configured = override || (compiledBinary() ? "" : (await run("npm", ["config", "get", "registry"], { timeoutMs: 15000 })).stdout.trim());
|
|
272
|
-
return /^https?:\/\//.test(configured) ? configured.replace(/\/+$/, "") : DEFAULT_REGISTRY;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
class InstallVerificationError extends Error {
|
|
276
|
-
}
|
|
277
|
-
async function fetchPublished(options) {
|
|
278
|
-
const request = options.fetch ?? fetch;
|
|
279
|
-
const name = options.packageName ?? updatePackage();
|
|
280
|
-
const response = await request(`${options.registry}/${name.replace("/", "%2f")}`, {
|
|
281
|
-
headers: { accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8" },
|
|
282
|
-
signal: AbortSignal.timeout(20000)
|
|
283
|
-
});
|
|
284
|
-
if (!response.ok)
|
|
285
|
-
throw new Error(`the registry answered ${response.status} for ${name}`);
|
|
286
|
-
const body = await response.json();
|
|
287
|
-
const version = body["dist-tags"]?.[options.channel];
|
|
288
|
-
if (!version)
|
|
289
|
-
throw new Error(`${name} has no ${options.channel} dist-tag`);
|
|
290
|
-
const integrity = body.versions?.[version]?.dist?.integrity;
|
|
291
|
-
if (!integrity || !/^sha512-/.test(integrity))
|
|
292
|
-
throw new Error(`${name}@${version} has no sha512 integrity in the registry`);
|
|
293
|
-
return { version, integrity };
|
|
294
|
-
}
|
|
295
|
-
function copyRunningPackage(source, prefix) {
|
|
296
|
-
const modules = path2.dirname(path2.dirname(source));
|
|
297
|
-
const seen = new Set;
|
|
298
|
-
const copy = (dir) => {
|
|
299
|
-
if (seen.has(dir))
|
|
300
|
-
return;
|
|
301
|
-
seen.add(dir);
|
|
302
|
-
const target = path2.join(prefix, "node_modules", path2.relative(modules, dir));
|
|
303
|
-
cpSync(dir, target, { recursive: true, dereference: true, filter: (file) => path2.basename(file) !== "node_modules" });
|
|
304
|
-
const manifest = path2.join(dir, "package.json");
|
|
305
|
-
const pkg = JSON.parse(readFileSync(manifest, "utf8"));
|
|
306
|
-
const require2 = createRequire(manifest);
|
|
307
|
-
for (const name of Object.keys({ ...pkg.dependencies, ...pkg.peerDependencies, ...pkg.optionalDependencies })) {
|
|
308
|
-
const dependency = require2.resolve.paths(name)?.map((parent) => path2.join(parent, name)).find((candidate) => candidate.startsWith(modules + path2.sep) && existsSync(path2.join(candidate, "package.json")));
|
|
309
|
-
if (dependency)
|
|
310
|
-
copy(dependency);
|
|
311
|
-
else if (!pkg.optionalDependencies?.[name] && !pkg.peerDependenciesMeta?.[name]?.optional)
|
|
312
|
-
throw new Error(`Missing installed dependency ${name} of ${pkg.name}`);
|
|
313
|
-
}
|
|
314
|
-
};
|
|
315
|
-
copy(source);
|
|
316
|
-
}
|
|
317
|
-
async function installVersion(options) {
|
|
318
|
-
if (compiledBinary() || options.runningBinary)
|
|
319
|
-
return installBinaryVersion(options);
|
|
320
|
-
const run = options.run ?? runCommand;
|
|
321
|
-
const { layout } = options;
|
|
322
|
-
const spec = options.spec ?? `${PACKAGE_NAME}@${options.version}`;
|
|
323
|
-
if (spec.startsWith("-") || /[\s"'`&|<>^%!;]/.test(spec))
|
|
324
|
-
throw new Error(`Invalid package spec ${JSON.stringify(spec)}`);
|
|
325
|
-
mkdirSync(layout.versions, { recursive: true });
|
|
326
|
-
const temporary = path2.join(layout.versions, `.install-${process.pid}-${Date.now()}`);
|
|
327
|
-
rmSync(temporary, { recursive: true, force: true });
|
|
328
|
-
mkdirSync(temporary, { recursive: true });
|
|
329
|
-
try {
|
|
330
|
-
writeFileSync(path2.join(temporary, "package.json"), `{"private":true}
|
|
331
|
-
`);
|
|
332
|
-
if (options.runningPackage)
|
|
333
|
-
copyRunningPackage(options.runningPackage, temporary);
|
|
334
|
-
else {
|
|
335
|
-
const args = ["install", "--prefix", temporary, "--no-audit", "--no-fund", "--ignore-scripts", "--loglevel=error", ...options.registry ? [`--registry=${options.registry}`] : [], spec];
|
|
336
|
-
const npm = await run("npm", args, { timeoutMs: 10 * 60000 });
|
|
337
|
-
if (npm.status !== 0) {
|
|
338
|
-
const output = npm.stderr || npm.stdout;
|
|
339
|
-
const message = `npm install ${spec} failed: ${output.trim().split(`
|
|
340
|
-
`).slice(-3).join(" ")}`;
|
|
341
|
-
throw /\bEINTEGRITY\b/.test(output) ? new InstallVerificationError(message) : new Error(message);
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
const installed = readJson(path2.join(temporary, "node_modules", "@opencode", "browse", "package.json"))?.version;
|
|
345
|
-
if (!installed)
|
|
346
|
-
throw new InstallVerificationError(`npm install ${spec} didn't install ${PACKAGE_NAME}`);
|
|
347
|
-
if (options.spec === undefined && installed !== options.version)
|
|
348
|
-
throw new InstallVerificationError(`npm installed ${installed}, not ${options.version}`);
|
|
349
|
-
if (options.integrity) {
|
|
350
|
-
const locked = readJson(path2.join(temporary, "package-lock.json"))?.packages?.["node_modules/@opencode/browse"];
|
|
351
|
-
if (locked?.integrity !== options.integrity)
|
|
352
|
-
throw new InstallVerificationError(`${PACKAGE_NAME}@${installed} installed with integrity ${locked?.integrity ?? "unknown"}, not the registry's ${options.integrity}`);
|
|
353
|
-
}
|
|
354
|
-
const entry = path2.join(temporary, "node_modules", "@opencode", "browse", "dist", "cli.mjs");
|
|
355
|
-
const reported = await run(options.node ?? process.execPath, [entry, "--version"], { timeoutMs: 30000, env: { ...process.env, OPENCODE_BROWSER_AUTOSTART: "0" } });
|
|
356
|
-
if (reported.status !== 0 || reported.stdout.trim() !== installed)
|
|
357
|
-
throw new InstallVerificationError(`${PACKAGE_NAME}@${installed} didn't run: \`--version\` printed ${JSON.stringify(reported.stdout.trim() || reported.stderr.trim()).slice(0, 200)}`);
|
|
358
|
-
const target = versionDirectory(layout, installed);
|
|
359
|
-
rmSync(target, { recursive: true, force: true });
|
|
360
|
-
renameSync(temporary, target);
|
|
361
|
-
return versionEntry(layout, installed);
|
|
362
|
-
} finally {
|
|
363
|
-
rmSync(temporary, { recursive: true, force: true });
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
async function installBinaryVersion(options) {
|
|
367
|
-
const run = options.run ?? runCommand;
|
|
368
|
-
const { layout } = options;
|
|
369
|
-
mkdirSync(layout.versions, { recursive: true });
|
|
370
|
-
const temporary = path2.join(layout.versions, `.install-${process.pid}-${Date.now()}`);
|
|
371
|
-
rmSync(temporary, { recursive: true, force: true });
|
|
372
|
-
mkdirSync(temporary, { recursive: true });
|
|
373
|
-
try {
|
|
374
|
-
const file = path2.join(temporary, binaryName());
|
|
375
|
-
const expected = options.runningBinary ? opencodeBrowserVersion2 : options.version;
|
|
376
|
-
if (options.runningBinary)
|
|
377
|
-
copyFileSync(options.runningBinary, file);
|
|
378
|
-
else {
|
|
379
|
-
const name = updatePackage();
|
|
380
|
-
if (name === PACKAGE_NAME)
|
|
381
|
-
throw new Error("this executable doesn't know its platform package");
|
|
382
|
-
const registry = options.registry ?? await registryUrl(run);
|
|
383
|
-
const integrity = options.integrity ?? await publishedIntegrity(registry, name, options.version);
|
|
384
|
-
const response = await fetch(`${registry}/${name}/-/${name.split("/")[1]}-${options.version}.tgz`, { signal: AbortSignal.timeout(10 * 60000) });
|
|
385
|
-
if (!response.ok)
|
|
386
|
-
throw new Error(`downloading ${name}@${options.version} failed: the registry answered ${response.status}`);
|
|
387
|
-
const tgz = new Uint8Array(await response.arrayBuffer());
|
|
388
|
-
const actual = `sha512-${createHash("sha512").update(tgz).digest("base64")}`;
|
|
389
|
-
if (actual !== integrity)
|
|
390
|
-
throw new InstallVerificationError(`${name}@${options.version} downloaded with integrity ${actual}, not the registry's ${integrity}`);
|
|
391
|
-
const executable = tarFile(tgz, `package/bin/${binaryName()}`);
|
|
392
|
-
if (!executable)
|
|
393
|
-
throw new InstallVerificationError(`${name}@${options.version} has no bin/${binaryName()}`);
|
|
394
|
-
writeFileSync(file, executable);
|
|
395
|
-
}
|
|
396
|
-
chmodSync(file, 493);
|
|
397
|
-
const reported = await run(file, ["--version"], { timeoutMs: 30000, env: { ...process.env, OPENCODE_BROWSER_AUTOSTART: "0" } });
|
|
398
|
-
if (reported.status !== 0 || reported.stdout.trim() !== expected)
|
|
399
|
-
throw new InstallVerificationError(`browse ${expected} didn't run: \`--version\` printed ${JSON.stringify(reported.stdout.trim() || reported.stderr.trim()).slice(0, 200)}`);
|
|
400
|
-
const target = versionDirectory(layout, expected);
|
|
401
|
-
rmSync(target, { recursive: true, force: true });
|
|
402
|
-
renameSync(temporary, target);
|
|
403
|
-
return versionEntry(layout, expected, true);
|
|
404
|
-
} finally {
|
|
405
|
-
rmSync(temporary, { recursive: true, force: true });
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
async function publishedIntegrity(registry, name, version) {
|
|
409
|
-
const response = await fetch(`${registry}/${name.replace("/", "%2f")}/${version}`, { signal: AbortSignal.timeout(20000) });
|
|
410
|
-
if (!response.ok)
|
|
411
|
-
throw new Error(`the registry answered ${response.status} for ${name}@${version}`);
|
|
412
|
-
const integrity = (await response.json()).dist?.integrity;
|
|
413
|
-
if (!integrity || !/^sha512-/.test(integrity))
|
|
414
|
-
throw new Error(`${name}@${version} has no sha512 integrity in the registry`);
|
|
415
|
-
return integrity;
|
|
416
|
-
}
|
|
417
|
-
function tarFile(tgz, wanted) {
|
|
418
|
-
const tar = gunzipSync(tgz);
|
|
419
|
-
let offset = 0;
|
|
420
|
-
let longName;
|
|
421
|
-
while (offset + 512 <= tar.length) {
|
|
422
|
-
const header = tar.subarray(offset, offset + 512);
|
|
423
|
-
if (header.every((byte) => byte === 0))
|
|
424
|
-
return;
|
|
425
|
-
const field = (start, length) => header.subarray(start, start + length).toString("utf8").replace(/\0[\s\S]*$/, "");
|
|
426
|
-
const size = parseInt(field(124, 12).trim() || "0", 8);
|
|
427
|
-
const type = field(156, 1) || "0";
|
|
428
|
-
const prefix = field(345, 155);
|
|
429
|
-
const name = longName ?? (prefix ? `${prefix}/${field(0, 100)}` : field(0, 100));
|
|
430
|
-
longName = undefined;
|
|
431
|
-
const body = tar.subarray(offset + 512, offset + 512 + size);
|
|
432
|
-
offset += 512 + Math.ceil(size / 512) * 512;
|
|
433
|
-
if (type === "x")
|
|
434
|
-
longName = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(body.toString("utf8"))?.[1];
|
|
435
|
-
else if (type === "L")
|
|
436
|
-
longName = body.toString("utf8").replace(/\0[\s\S]*$/, "");
|
|
437
|
-
else if (type === "0" && name === wanted)
|
|
438
|
-
return Buffer.from(body);
|
|
439
|
-
}
|
|
440
|
-
return;
|
|
441
|
-
}
|
|
442
|
-
function placeBinary(source, target) {
|
|
443
|
-
const staged = `${target}.${process.pid}.new`;
|
|
444
|
-
rmSync(staged, { force: true });
|
|
445
|
-
try {
|
|
446
|
-
linkSync(source, staged);
|
|
447
|
-
} catch {
|
|
448
|
-
copyFileSync(source, staged);
|
|
449
|
-
}
|
|
450
|
-
chmodSync(staged, 493);
|
|
451
|
-
if (process.platform === "win32") {
|
|
452
|
-
const dir = path2.dirname(target);
|
|
453
|
-
const stale = `${path2.basename(target)}.old-`;
|
|
454
|
-
for (const name of readdirSync(dir)) {
|
|
455
|
-
if (!name.startsWith(stale))
|
|
456
|
-
continue;
|
|
457
|
-
try {
|
|
458
|
-
rmSync(path2.join(dir, name), { force: true });
|
|
459
|
-
} catch {}
|
|
460
|
-
}
|
|
461
|
-
if (existsSync(target))
|
|
462
|
-
renameSync(target, `${target}.old-${Date.now()}`);
|
|
463
|
-
}
|
|
464
|
-
renameSync(staged, target);
|
|
465
|
-
}
|
|
466
|
-
function processAlive(pid) {
|
|
467
|
-
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
468
|
-
return false;
|
|
469
|
-
try {
|
|
470
|
-
process.kill(pid, 0);
|
|
471
|
-
return true;
|
|
472
|
-
} catch (error) {
|
|
473
|
-
return error.code === "EPERM";
|
|
474
|
-
}
|
|
475
|
-
}
|
|
476
|
-
function pruneVersions(layout, keep = []) {
|
|
477
|
-
let names = [];
|
|
478
|
-
try {
|
|
479
|
-
names = readdirSync(layout.versions);
|
|
480
|
-
} catch {
|
|
481
|
-
return;
|
|
482
|
-
}
|
|
483
|
-
const current = readCurrent(layout);
|
|
484
|
-
const kept = new Set([...keep, current?.version, current?.previous, readState(layout).pending].filter((name) => !!name));
|
|
485
|
-
for (const name of names) {
|
|
486
|
-
if (kept.has(name))
|
|
487
|
-
continue;
|
|
488
|
-
const temporary = /^\.install-(\d+)-\d+$/.exec(name);
|
|
489
|
-
if (temporary && processAlive(Number(temporary[1])))
|
|
490
|
-
continue;
|
|
491
|
-
rmSync(path2.join(layout.versions, name), { recursive: true, force: true });
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
function validatePending(layout) {
|
|
495
|
-
const state = readState(layout);
|
|
496
|
-
if (!state.pending || existsSync(versionEntry(layout, state.pending)))
|
|
497
|
-
return state;
|
|
498
|
-
return updateState(layout, ({ pending: _pending, ...rest }) => rest);
|
|
499
|
-
}
|
|
500
|
-
function switchVersion(layout, version, previous, binary = compiledBinary() ? readCurrent(layout)?.binary : undefined) {
|
|
501
|
-
const entry = versionEntry(layout, version, binary !== undefined);
|
|
502
|
-
if (!existsSync(entry))
|
|
503
|
-
throw new Error(`${version} isn't installed in ${layout.versions}`);
|
|
504
|
-
if (binary && !(version === opencodeBrowserVersion2 && realpath(binary) === realpath(process.execPath)))
|
|
505
|
-
placeBinary(entry, binary);
|
|
506
|
-
writeCurrent(layout, { version, ...previous && previous !== version ? { previous } : {}, channel: channelOf(version), ...binary ? { binary } : {} });
|
|
507
|
-
if (!binary || existsSync(layout.shim))
|
|
508
|
-
writeShim(layout);
|
|
509
|
-
}
|
|
510
|
-
function shimSource() {
|
|
511
|
-
return `#!/usr/bin/env node
|
|
512
|
-
// browse's stable entry, written by install (cli/src/auto-update.ts). opencode's browse MCP server runs this
|
|
513
|
-
// file, so its configuration never changes when the runtime updates. Don't edit; install rewrites it.
|
|
514
|
-
import { spawn } from "node:child_process"
|
|
515
|
-
import { readFileSync } from "node:fs"
|
|
516
|
-
import path from "node:path"
|
|
517
|
-
import { createInterface } from "node:readline"
|
|
518
|
-
import { fileURLToPath, pathToFileURL } from "node:url"
|
|
519
|
-
|
|
520
|
-
const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)))
|
|
521
|
-
const runtime = path.join(root, "runtime")
|
|
522
|
-
const installed = () => JSON.parse(readFileSync(path.join(runtime, "current.json"), "utf8"))
|
|
523
|
-
const current = () => installed().version
|
|
524
|
-
const entry = (version) => path.join(runtime, "versions", version, "node_modules", "@opencode", "browse", "dist", "cli.mjs")
|
|
525
|
-
process.env.OPENCODE_BROWSER_HOME ??= root
|
|
526
|
-
const relayPort = Number(process.env.OPENCODE_BROWSER_PORT) || 19988
|
|
527
|
-
|
|
528
|
-
const binary = installed().binary
|
|
529
|
-
if (binary) {
|
|
530
|
-
// An agent still runs the npm entry after a binary install. The executable supplies its own MCP supervisor.
|
|
531
|
-
const child = spawn(binary, process.argv.slice(2), { stdio: "inherit" })
|
|
532
|
-
for (const signal of ["SIGTERM", "SIGINT"]) process.on(signal, () => child.kill(signal))
|
|
533
|
-
child.on("exit", (code, signal) => { process.exitCode = code ?? (signal ? 1 : 0) })
|
|
534
|
-
} else if (process.argv[2] !== "mcp") {
|
|
535
|
-
process.argv[1] = entry(current())
|
|
536
|
-
await import(pathToFileURL(entry(current())).href)
|
|
537
|
-
} else {
|
|
538
|
-
const REPLAY = "opencode-browser-shim-initialize"
|
|
539
|
-
// Every server this supervisor starts keeps one implicit session, and the relay watches this process (not the
|
|
540
|
-
// server it replaces), so an update doesn't end the agent's session or close its tabs.
|
|
541
|
-
process.env.OPENCODE_BROWSER_MCP_SESSION ??= "mcp-" + Math.random().toString(16).slice(2, 10).padEnd(8, "0")
|
|
542
|
-
process.env.OPENCODE_BROWSER_CLIENT_PID = String(process.pid)
|
|
543
|
-
let version = current()
|
|
544
|
-
let child
|
|
545
|
-
let initialize
|
|
546
|
-
let initialized
|
|
547
|
-
let swapping = false
|
|
548
|
-
let listChanged = false
|
|
549
|
-
const inflight = new Set()
|
|
550
|
-
const queue = []
|
|
551
|
-
const toClient = (line) => process.stdout.write(line + "\\n")
|
|
552
|
-
const toChild = (line) => child.stdin.write(line + "\\n")
|
|
553
|
-
const parse = (line) => { try { return JSON.parse(line) } catch { return undefined } }
|
|
554
|
-
// A request is in flight until its response; a cancelled request never gets one, so its client tells us to forget it.
|
|
555
|
-
const trackRequest = (message) => {
|
|
556
|
-
if (!message) return
|
|
557
|
-
if (message.id !== undefined && message.method !== undefined) inflight.add(message.id)
|
|
558
|
-
if (message.method !== "notifications/cancelled" || !message.params || typeof message.params !== "object") return
|
|
559
|
-
const cancelled = message.params.requestId
|
|
560
|
-
if (cancelled !== undefined) inflight.delete(cancelled)
|
|
561
|
-
}
|
|
562
|
-
const forward = (line) => { trackRequest(parse(line)); toChild(line) }
|
|
563
|
-
|
|
564
|
-
const start = (replay) => {
|
|
565
|
-
const next = spawn(process.execPath, [entry(version), "mcp"], { stdio: ["pipe", "pipe", "inherit"], env: process.env })
|
|
566
|
-
// A server that exits mid-write (an old one being replaced) must not take the supervisor down with EPIPE.
|
|
567
|
-
next.stdin.on("error", () => {})
|
|
568
|
-
child = next
|
|
569
|
-
next.on("exit", (code, signal) => {
|
|
570
|
-
if (next !== child) return
|
|
571
|
-
process.exit(code ?? (signal ? 1 : 0))
|
|
572
|
-
})
|
|
573
|
-
createInterface({ input: next.stdout }).on("line", (line) => {
|
|
574
|
-
if (next !== child) return
|
|
575
|
-
const message = parse(line)
|
|
576
|
-
if (message && message.id === REPLAY) {
|
|
577
|
-
if (initialized) toChild(initialized)
|
|
578
|
-
swapping = false
|
|
579
|
-
if (listChanged) toClient(JSON.stringify({ jsonrpc: "2.0", method: "notifications/tools/list_changed" }))
|
|
580
|
-
for (const queued of queue.splice(0)) fromClient(queued)
|
|
581
|
-
return
|
|
582
|
-
}
|
|
583
|
-
if (message && message.id !== undefined && message.method === undefined) {
|
|
584
|
-
inflight.delete(message.id)
|
|
585
|
-
if (message.result && message.result.capabilities && message.result.capabilities.tools) listChanged = message.result.capabilities.tools.listChanged === true
|
|
586
|
-
}
|
|
587
|
-
toClient(line)
|
|
588
|
-
void maybeSwap()
|
|
589
|
-
})
|
|
590
|
-
if (replay && initialize) {
|
|
591
|
-
swapping = true
|
|
592
|
-
toChild(JSON.stringify({ ...initialize, id: REPLAY }))
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
|
|
596
|
-
// Once current.json names another version, new requests wait for the swap instead of reaching a server whose relay is
|
|
597
|
-
// going away (or already runs the other version); a switch that doesn't happen releases them.
|
|
598
|
-
let heldSince
|
|
599
|
-
const moved = () => { try { return current() !== version } catch { return false } }
|
|
600
|
-
const fromClient = (line) => {
|
|
601
|
-
const message = parse(line)
|
|
602
|
-
// A cancellation drops the request at once, even while client messages wait: it may be the one blocking the swap.
|
|
603
|
-
if (message && message.method === "notifications/cancelled") trackRequest(message)
|
|
604
|
-
if (swapping) return void queue.push(line)
|
|
605
|
-
if (moved()) {
|
|
606
|
-
heldSince ??= Date.now()
|
|
607
|
-
queue.push(line)
|
|
608
|
-
return void maybeSwap()
|
|
609
|
-
}
|
|
610
|
-
if (message && message.method === "initialize") initialize = message
|
|
611
|
-
if (message && message.method === "notifications/initialized") initialized = line
|
|
612
|
-
forward(line)
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
// A new version in current.json swaps the server only once the relay runs it too (GET /version), so a server never
|
|
616
|
-
// talks to a relay of another version. With no relay at all for a few checks, nothing can mix, and it swaps.
|
|
617
|
-
let checking = false
|
|
618
|
-
let unreachable = 0
|
|
619
|
-
const relayVersion = () => fetch("http://127.0.0.1:" + relayPort + "/version", { signal: AbortSignal.timeout(2000) })
|
|
620
|
-
.then((response) => (response.ok ? response.json() : undefined))
|
|
621
|
-
.then((body) => (body && typeof body.version === "string" ? body.version : undefined), () => undefined)
|
|
622
|
-
const maybeSwap = async () => {
|
|
623
|
-
if (swapping || checking) return
|
|
624
|
-
// Held requests go to the current server at the deadline even when a request still looks in flight: a cancelled
|
|
625
|
-
// request may never answer, and waiting for it would wedge the swap forever.
|
|
626
|
-
if (heldSince !== undefined && Date.now() - heldSince > 15000) {
|
|
627
|
-
heldSince = undefined
|
|
628
|
-
const released = queue.splice(0)
|
|
629
|
-
for (const line of released) forward(line)
|
|
630
|
-
}
|
|
631
|
-
if (inflight.size > 0) return
|
|
632
|
-
let next
|
|
633
|
-
try { next = current() } catch { return }
|
|
634
|
-
if (next === version) {
|
|
635
|
-
unreachable = 0
|
|
636
|
-
heldSince = undefined
|
|
637
|
-
for (const queued of queue.splice(0)) fromClient(queued)
|
|
638
|
-
return
|
|
639
|
-
}
|
|
640
|
-
checking = true
|
|
641
|
-
const running = await relayVersion()
|
|
642
|
-
checking = false
|
|
643
|
-
unreachable = running === undefined ? unreachable + 1 : 0
|
|
644
|
-
// Held requests don't wait forever for a relay that never reports the new version: they go to the current server.
|
|
645
|
-
if (running !== next && unreachable < 3) return
|
|
646
|
-
if (swapping || inflight.size > 0 || current() !== next) return
|
|
647
|
-
const old = child
|
|
648
|
-
version = next
|
|
649
|
-
heldSince = undefined
|
|
650
|
-
start(true)
|
|
651
|
-
old.stdin.end()
|
|
652
|
-
setTimeout(() => old.kill(), 5000).unref()
|
|
653
|
-
}
|
|
654
|
-
|
|
655
|
-
start(false)
|
|
656
|
-
createInterface({ input: process.stdin }).on("line", fromClient).on("close", () => {
|
|
657
|
-
child.stdin.end()
|
|
658
|
-
setTimeout(() => process.exit(0), 5000).unref()
|
|
659
|
-
})
|
|
660
|
-
setInterval(() => void maybeSwap(), 1000).unref()
|
|
661
|
-
}
|
|
662
|
-
`;
|
|
663
|
-
}
|
|
664
|
-
function writeShim(layout) {
|
|
665
|
-
mkdirSync(path2.dirname(layout.shim), { recursive: true });
|
|
666
|
-
const source = shimSource();
|
|
667
|
-
try {
|
|
668
|
-
if (readFileSync(layout.shim, "utf8") === source)
|
|
669
|
-
return;
|
|
670
|
-
} catch {}
|
|
671
|
-
const temporary = `${layout.shim}.${process.pid}.tmp`;
|
|
672
|
-
writeFileSync(temporary, source);
|
|
673
|
-
chmodSync(temporary, 493);
|
|
674
|
-
renameSync(temporary, layout.shim);
|
|
675
|
-
}
|
|
676
|
-
var INSTALL_TIMEOUT_MS = 15 * 60000;
|
|
677
|
-
var SWITCH_TIMEOUT_MS = 5 * 60000;
|
|
678
|
-
function createAutoUpdater(deps) {
|
|
679
|
-
const env = deps.env ?? process.env;
|
|
680
|
-
const now = deps.now ?? Date.now;
|
|
681
|
-
const { layout, version: running } = deps.runtime;
|
|
682
|
-
const checkIntervalMs = Number(env.OPENCODE_BROWSER_AUTO_UPDATE_INTERVAL_MS) || DAY_MS;
|
|
683
|
-
const spawnChild = deps.spawnChild ?? ((args, onExit) => spawnRuntimeChild(layout, versionEntry(layout, running), args, onExit, env));
|
|
684
|
-
let busy = false;
|
|
685
|
-
let switching;
|
|
686
|
-
let timer;
|
|
687
|
-
const settled = readState(layout);
|
|
688
|
-
if (settled.pending === running) {
|
|
689
|
-
updateState(layout, ({ pending: _pending, lastError: _error, ...state }) => ({ ...state, lastUpdate: { from: deps.runtime.current.previous ?? "unknown", to: running, at: new Date(now()).toISOString() } }));
|
|
690
|
-
deps.log("autoupdate.switched", { version: running, previous: deps.runtime.current.previous });
|
|
691
|
-
pruneVersions(layout, [running]);
|
|
692
|
-
}
|
|
693
|
-
async function tick() {
|
|
694
|
-
if (switching && (now() - switching.startedAt > SWITCH_TIMEOUT_MS || switching.pid !== undefined && !processAlive(switching.pid))) {
|
|
695
|
-
deps.log("autoupdate.switch_abandoned", { pid: switching.pid });
|
|
696
|
-
switching = undefined;
|
|
697
|
-
}
|
|
698
|
-
if (busy || switching)
|
|
699
|
-
return;
|
|
700
|
-
busy = true;
|
|
701
|
-
try {
|
|
702
|
-
const mode = effectiveMode(layout, env);
|
|
703
|
-
if (mode === "off")
|
|
704
|
-
return;
|
|
705
|
-
let state = validatePending(layout);
|
|
706
|
-
if (!state.checkedAt || now() - state.checkedAt >= checkIntervalMs || now() < state.checkedAt) {
|
|
707
|
-
const channel = channelOf(running);
|
|
708
|
-
try {
|
|
709
|
-
const published = await fetchPublished({ registry: await registryUrl(deps.run, env), channel, ...deps.fetch ? { fetch: deps.fetch } : {} });
|
|
710
|
-
state = updateState(layout, ({ failed: _failed, ...rest }) => ({ ...rest, checkedAt: now(), latest: published.version, integrity: published.integrity }));
|
|
711
|
-
deps.log("autoupdate.checked", { channel, latest: published.version, running });
|
|
712
|
-
} catch (error) {
|
|
713
|
-
state = updateState(layout, (rest) => ({ ...rest, checkedAt: now(), failed: error.message }));
|
|
714
|
-
deps.log("autoupdate.check_failed", { error: error.message });
|
|
715
|
-
}
|
|
716
|
-
deps.onChange?.();
|
|
717
|
-
}
|
|
718
|
-
const latest = state.latest;
|
|
719
|
-
const wanted = latest && compareVersions(latest, running) > 0 && latest !== state.skipped ? latest : undefined;
|
|
720
|
-
if (!wanted || mode !== "on")
|
|
721
|
-
return;
|
|
722
|
-
const installing = state.installing;
|
|
723
|
-
if (installing) {
|
|
724
|
-
if (processAlive(installing.pid) && now() - installing.startedAt < INSTALL_TIMEOUT_MS)
|
|
725
|
-
return;
|
|
726
|
-
const done = existsSync(versionEntry(layout, installing.version));
|
|
727
|
-
state = updateState(layout, ({ installing: _installing, ...rest }) => ({
|
|
728
|
-
...rest,
|
|
729
|
-
...done ? { pending: installing.version } : rest.pending === installing.version ? {} : { lastError: { message: "the installer stopped without finishing", at: new Date(now()).toISOString(), version: installing.version } }
|
|
730
|
-
}));
|
|
731
|
-
deps.log("autoupdate.installer_gone", { version: installing.version });
|
|
732
|
-
}
|
|
733
|
-
if (state.pending !== wanted) {
|
|
734
|
-
if (state.lastError?.version === wanted) {
|
|
735
|
-
const failure = state.lastError;
|
|
736
|
-
const attempts = failure.attempts ?? 1;
|
|
737
|
-
const backoff = (attempts <= 1 ? 15 : attempts === 2 ? 60 : 240) * 60000;
|
|
738
|
-
const delay = failure.verification ? checkIntervalMs : Math.min(backoff, checkIntervalMs);
|
|
739
|
-
const age = now() - Date.parse(failure.at);
|
|
740
|
-
if (age >= 0 && age < delay)
|
|
741
|
-
return;
|
|
742
|
-
}
|
|
743
|
-
deps.log("autoupdate.installing", { version: wanted });
|
|
744
|
-
const pid = spawnChild(["runtime-install", wanted, ...state.integrity ? ["--integrity", state.integrity] : []], (code) => {
|
|
745
|
-
deps.log(code === 0 ? "autoupdate.installed" : "autoupdate.install_failed", { version: wanted, code });
|
|
746
|
-
deps.onChange?.();
|
|
747
|
-
if (code === 0)
|
|
748
|
-
tick();
|
|
749
|
-
});
|
|
750
|
-
if (pid)
|
|
751
|
-
updateState(layout, (rest) => ({ ...rest, installing: { version: wanted, pid, startedAt: now() } }));
|
|
752
|
-
return;
|
|
753
|
-
}
|
|
754
|
-
if (!deps.isIdle())
|
|
755
|
-
return;
|
|
756
|
-
const current = readCurrent(layout);
|
|
757
|
-
if (!current || current.version !== running)
|
|
758
|
-
return;
|
|
759
|
-
const attempt = { pid: undefined, startedAt: now() };
|
|
760
|
-
switching = attempt;
|
|
761
|
-
deps.log("autoupdate.switching", { from: running, to: wanted });
|
|
762
|
-
attempt.pid = spawnChild(["runtime-switch", wanted], (code) => {
|
|
763
|
-
if (switching === attempt)
|
|
764
|
-
switching = undefined;
|
|
765
|
-
if (code !== 0)
|
|
766
|
-
deps.log("autoupdate.restart_refused", { version: wanted, code });
|
|
767
|
-
});
|
|
768
|
-
} catch (error) {
|
|
769
|
-
deps.log("autoupdate.error", { error: error.message });
|
|
770
|
-
} finally {
|
|
771
|
-
busy = false;
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
return {
|
|
775
|
-
tick,
|
|
776
|
-
start(intervalMs = Number(env.OPENCODE_BROWSER_AUTO_UPDATE_TICK_MS) || 10 * 60000) {
|
|
777
|
-
timer = setInterval(() => void tick(), intervalMs);
|
|
778
|
-
timer.unref();
|
|
779
|
-
setTimeout(() => void tick(), Math.min(intervalMs, 60000)).unref();
|
|
780
|
-
},
|
|
781
|
-
stop() {
|
|
782
|
-
clearInterval(timer);
|
|
783
|
-
}
|
|
784
|
-
};
|
|
785
|
-
}
|
|
786
|
-
function spawnRuntimeChild(layout, entry, args, onExit, env = process.env) {
|
|
787
|
-
const { OPENCODE_BROWSER_MANAGED_RELAY: _managed, OPENCODE_BROWSER_RESTART_REQUEST_ID: _request, ...rest } = env;
|
|
788
|
-
mkdirSync(path2.join(layout.root, "logs"), { recursive: true });
|
|
789
|
-
const log = openSync(path2.join(layout.root, "logs", "auto-update.log"), "a", 384);
|
|
790
|
-
try {
|
|
791
|
-
const [file, ...prefix] = entryCommand(entry);
|
|
792
|
-
const child = spawn(file, [...prefix, ...args], { detached: true, stdio: ["ignore", log, log], env: { ...rest, OPENCODE_BROWSER_HOME: layout.root } });
|
|
793
|
-
child.on("error", () => onExit(null));
|
|
794
|
-
child.on("exit", (code) => onExit(code));
|
|
795
|
-
child.unref();
|
|
796
|
-
return child.pid;
|
|
797
|
-
} catch {
|
|
798
|
-
onExit(null);
|
|
799
|
-
return;
|
|
800
|
-
} finally {
|
|
801
|
-
closeSync(log);
|
|
802
|
-
}
|
|
803
|
-
}
|
|
804
|
-
|
|
805
|
-
export { dataRoot, oldStoreMarker, fromCheckout, compiledBinary, binaryPackage, scriptEntry, entryCommand, runningEntry, checkoutRoot, cliCommand, PUBLIC_STORE_ID, storeConfig, devExtension, devExtensionUrl, devExtensionFolder, storeUrl, installCommand, autoUpdateModes, runtimeLayout, versionEntry, channelOf, UPDATE_VERSION, compareVersions, readCurrent, writeCurrent, updateState, npmRuntime, autoUpdateOverride, storedMode, effectiveMode, setStoredMode, autoUpdateStatus, describeAutoUpdate, registryUrl, InstallVerificationError, fetchPublished, installVersion, pruneVersions, switchVersion, createAutoUpdater };
|