aicomputer 0.1.17 → 0.1.19

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.
@@ -0,0 +1,188 @@
1
+ // src/lib/mutagen-runtime.ts
2
+ import { spawnSync } from "child_process";
3
+ import {
4
+ chmodSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ renameSync,
8
+ rmSync
9
+ } from "fs";
10
+ import { writeFile } from "fs/promises";
11
+ import { homedir } from "os";
12
+ import { dirname, join } from "path";
13
+ var BUNDLED_MUTAGEN_VERSION = "0.18.1";
14
+ var BUNDLED_MUTAGEN_DOWNLOAD_BASE = `https://github.com/mutagen-io/mutagen/releases/download/v${BUNDLED_MUTAGEN_VERSION}`;
15
+ var AGENTCOMPUTER_MUTAGEN_PATH_ENV = "AGENTCOMPUTER_MUTAGEN_PATH";
16
+ function getBundledMutagenAsset(platform = process.platform, arch = process.arch, homeDirectory = homedir()) {
17
+ if (!isSupportedPlatform(platform)) {
18
+ return null;
19
+ }
20
+ const assetArch = resolveMutagenAssetArch(arch);
21
+ if (!assetArch) {
22
+ return null;
23
+ }
24
+ const assetName = `mutagen_${platform}_${assetArch}_v${BUNDLED_MUTAGEN_VERSION}.tar.gz`;
25
+ const installDir = join(
26
+ homeDirectory,
27
+ ".agentcomputer",
28
+ "tools",
29
+ "mutagen",
30
+ `v${BUNDLED_MUTAGEN_VERSION}`,
31
+ `${platform}-${assetArch}`
32
+ );
33
+ return {
34
+ platform,
35
+ arch: assetArch,
36
+ version: BUNDLED_MUTAGEN_VERSION,
37
+ assetName,
38
+ downloadUrl: `${BUNDLED_MUTAGEN_DOWNLOAD_BASE}/${assetName}`,
39
+ installDir,
40
+ executablePath: join(installDir, "mutagen")
41
+ };
42
+ }
43
+ function hasBundledMutagen() {
44
+ const asset = getBundledMutagenAsset();
45
+ return asset ? existsSync(asset.executablePath) : false;
46
+ }
47
+ function resolveSystemCommandPath(command) {
48
+ const result = spawnSync("which", [command], { encoding: "utf8" });
49
+ if (result.status !== 0) {
50
+ return null;
51
+ }
52
+ const resolved = result.stdout.trim();
53
+ return resolved.length > 0 ? resolved : null;
54
+ }
55
+ async function ensureMutagenCommandPath() {
56
+ const asset = getBundledMutagenAsset();
57
+ if (asset && existsSync(asset.executablePath)) {
58
+ return asset.executablePath;
59
+ }
60
+ const systemPath = resolveSystemCommandPath("mutagen");
61
+ if (!asset) {
62
+ if (systemPath) {
63
+ return systemPath;
64
+ }
65
+ throw new Error(
66
+ `Agent Computer does not ship bundled Mutagen for ${process.platform} ${process.arch}. Install Mutagen manually and rerun \`computer mount\`.`
67
+ );
68
+ }
69
+ try {
70
+ return await installBundledMutagen(asset);
71
+ } catch (error) {
72
+ if (systemPath) {
73
+ return systemPath;
74
+ }
75
+ const reason = error instanceof Error ? error.message : "unknown Mutagen install failure";
76
+ throw new Error(
77
+ `Failed to install Agent Computer's bundled Mutagen (${reason}). Check your network connection and rerun \`computer mount\`.`
78
+ );
79
+ }
80
+ }
81
+ async function ensureBundledMutagenInstalled() {
82
+ const asset = getBundledMutagenAsset();
83
+ if (!asset) {
84
+ throw new Error(
85
+ `Agent Computer does not ship bundled Mutagen for ${process.platform} ${process.arch}.`
86
+ );
87
+ }
88
+ return installBundledMutagen(asset);
89
+ }
90
+ function resolveMutagenCommandPath() {
91
+ const overridden = process.env[AGENTCOMPUTER_MUTAGEN_PATH_ENV]?.trim();
92
+ if (overridden) {
93
+ return overridden;
94
+ }
95
+ const asset = getBundledMutagenAsset();
96
+ if (asset && existsSync(asset.executablePath)) {
97
+ return asset.executablePath;
98
+ }
99
+ const systemPath = resolveSystemCommandPath("mutagen");
100
+ if (systemPath) {
101
+ return systemPath;
102
+ }
103
+ if (!asset) {
104
+ throw new Error(
105
+ `Agent Computer does not ship bundled Mutagen for ${process.platform} ${process.arch}. Install Mutagen manually and rerun \`computer mount\`.`
106
+ );
107
+ }
108
+ throw new Error(
109
+ "Mutagen is not installed yet. Re-run `computer mount` and Agent Computer will install its bundled copy."
110
+ );
111
+ }
112
+ async function installBundledMutagen(asset) {
113
+ if (existsSync(asset.executablePath)) {
114
+ return asset.executablePath;
115
+ }
116
+ mkdirSync(dirname(asset.installDir), { recursive: true });
117
+ const stagingDir = `${asset.installDir}.staging-${process.pid}-${Date.now()}`;
118
+ const archivePath = join(stagingDir, asset.assetName);
119
+ rmSync(stagingDir, { recursive: true, force: true });
120
+ if (existsSync(asset.installDir) && !existsSync(asset.executablePath)) {
121
+ rmSync(asset.installDir, { recursive: true, force: true });
122
+ }
123
+ mkdirSync(stagingDir, { recursive: true });
124
+ try {
125
+ const response = await fetch(asset.downloadUrl, {
126
+ headers: {
127
+ "User-Agent": "aicomputer-cli"
128
+ }
129
+ });
130
+ if (!response.ok || !response.body) {
131
+ throw new Error(`download failed with status ${response.status}`);
132
+ }
133
+ await writeFile(archivePath, Buffer.from(await response.arrayBuffer()), {
134
+ mode: 384
135
+ });
136
+ const extract = spawnSync("tar", ["-xzf", archivePath, "-C", stagingDir], {
137
+ encoding: "utf8"
138
+ });
139
+ if (extract.status !== 0) {
140
+ throw new Error(
141
+ extract.stderr.trim() || extract.stdout.trim() || `failed to extract ${asset.assetName}`
142
+ );
143
+ }
144
+ if (!existsSync(join(stagingDir, "mutagen"))) {
145
+ throw new Error("archive did not contain the Mutagen executable");
146
+ }
147
+ chmodSync(join(stagingDir, "mutagen"), 493);
148
+ rmSync(archivePath, { force: true });
149
+ try {
150
+ renameSync(stagingDir, asset.installDir);
151
+ } catch (error) {
152
+ if (!existsSync(asset.executablePath)) {
153
+ throw error;
154
+ }
155
+ rmSync(stagingDir, { recursive: true, force: true });
156
+ }
157
+ return asset.executablePath;
158
+ } catch (error) {
159
+ rmSync(stagingDir, { recursive: true, force: true });
160
+ throw error;
161
+ }
162
+ }
163
+ function isSupportedPlatform(platform) {
164
+ return platform === "darwin" || platform === "linux";
165
+ }
166
+ function resolveMutagenAssetArch(arch) {
167
+ if (!isSupportedNodeArch(arch)) {
168
+ return null;
169
+ }
170
+ if (arch === "x64") {
171
+ return "amd64";
172
+ }
173
+ return arch;
174
+ }
175
+ function isSupportedNodeArch(arch) {
176
+ return arch === "arm64" || arch === "x64";
177
+ }
178
+
179
+ export {
180
+ AGENTCOMPUTER_MUTAGEN_PATH_ENV,
181
+ getBundledMutagenAsset,
182
+ hasBundledMutagen,
183
+ resolveSystemCommandPath,
184
+ ensureMutagenCommandPath,
185
+ ensureBundledMutagenInstalled,
186
+ resolveMutagenCommandPath,
187
+ resolveMutagenAssetArch
188
+ };
@@ -0,0 +1,354 @@
1
+ import {
2
+ MOUNT_SERVICE_LABEL,
3
+ ensureHandleDirectories,
4
+ ensureMountDirectories
5
+ } from "./chunk-KXLTHWW3.js";
6
+ import {
7
+ resolveMutagenCommandPath
8
+ } from "./chunk-MDSPJ57B.js";
9
+
10
+ // src/lib/mount-mutagen.ts
11
+ import { chmodSync, readFileSync, symlinkSync, unlinkSync, writeFileSync } from "fs";
12
+ import { spawn, spawnSync } from "child_process";
13
+ import { basename, join, relative, resolve } from "path";
14
+ var SYNC_NAME_PREFIX = "agentcomputer-mount-";
15
+ var DEFAULT_IGNORE_PATHS = [
16
+ ".codex/tmp",
17
+ ".local",
18
+ ".ssh/sshd.log"
19
+ ];
20
+ function ensureMutagenSshEnvironment(config, paths) {
21
+ ensureMountDirectories(paths);
22
+ const sshPath = resolveCommandPath("ssh");
23
+ const scpPath = resolveCommandPath("scp");
24
+ writeExecutableLink(paths.sshToolsDir, "ssh", sshPath);
25
+ writeExecutableLink(paths.sshToolsDir, "scp", scpPath);
26
+ writeExecutableLink(paths.sshToolsDir, basename(sshPath), sshPath);
27
+ writeExecutableLink(paths.sshToolsDir, basename(scpPath), scpPath);
28
+ }
29
+ function getHandleSessionName(handle) {
30
+ return `${SYNC_NAME_PREFIX}${handle}`;
31
+ }
32
+ function getDefaultMountIgnorePaths() {
33
+ return [...DEFAULT_IGNORE_PATHS];
34
+ }
35
+ function createHandleSession(handle, config, paths, signal) {
36
+ ensureHandleDirectories(handle, config.rootPath);
37
+ const sessionName = getHandleSessionName(handle);
38
+ const args = [
39
+ "sync",
40
+ "create",
41
+ join(paths.rootPath, handle),
42
+ `${handle}@${config.alias}:/home/node`,
43
+ "--name",
44
+ sessionName,
45
+ "--label",
46
+ `${MOUNT_SERVICE_LABEL}=true`,
47
+ "--label",
48
+ `${MOUNT_SERVICE_LABEL}.handle=${handle}`,
49
+ "--symlink-mode",
50
+ "posix-raw"
51
+ ];
52
+ for (const ignorePath of DEFAULT_IGNORE_PATHS) {
53
+ args.push("--ignore", ignorePath);
54
+ }
55
+ return runMutagen(args, config, paths, handle, { signal }).then(async () => {
56
+ await runMutagen(
57
+ ["sync", "flush", sessionName, "--skip-wait"],
58
+ config,
59
+ paths,
60
+ handle,
61
+ { signal }
62
+ );
63
+ });
64
+ }
65
+ function terminateSession(session, config, paths, signal) {
66
+ return runMutagen(
67
+ ["sync", "terminate", session.identifier],
68
+ config,
69
+ paths,
70
+ session.handle,
71
+ { ignoreFailure: true, signal }
72
+ ).then(() => void 0);
73
+ }
74
+ function inspectHandleSession(handle, config, paths, signal) {
75
+ return listOwnedSessions(config, paths, signal).then((sessions) => {
76
+ const matching = sessions.filter((session) => session.handle === handle);
77
+ if (matching.length === 0) {
78
+ return null;
79
+ }
80
+ return selectPreferredSession(handle, matching);
81
+ });
82
+ }
83
+ async function listOwnedSessions(config, paths, signal) {
84
+ const result = await runMutagen(["sync", "list", "-l"], config, paths, "mount", {
85
+ ignoreFailure: true,
86
+ signal
87
+ });
88
+ const raw = [result.stdout, result.stderr].filter(Boolean).join("\n").trim();
89
+ if (!raw) {
90
+ return [];
91
+ }
92
+ if (!result.ok && raw.includes("No synchronization sessions found")) {
93
+ return [];
94
+ }
95
+ const rootPath = resolve(paths.rootPath);
96
+ const sessions = parseMutagenSyncList(raw).filter((session) => session.alphaPath).map((session) => {
97
+ const alphaPath = resolve(session.alphaPath);
98
+ const handle = basename(alphaPath);
99
+ const expectedName = getHandleSessionName(handle);
100
+ const expectedBeta = `${handle}@${config.alias}:/home/node`;
101
+ const owned = alphaPath === rootPath || relative(rootPath, alphaPath) === "" || !relative(rootPath, alphaPath).startsWith("..") && !relative(rootPath, alphaPath).startsWith("../");
102
+ if (!owned || !session.identifier) {
103
+ return null;
104
+ }
105
+ return {
106
+ identifier: session.identifier,
107
+ name: session.name,
108
+ handle,
109
+ alphaPath,
110
+ betaUrl: session.betaUrl,
111
+ alphaConnected: session.alphaConnected,
112
+ betaConnected: session.betaConnected,
113
+ status: session.status,
114
+ lastError: session.lastError,
115
+ scanProblemCount: session.scanProblemCount,
116
+ conflictCount: session.conflictCount,
117
+ legacy: session.name !== expectedName || session.betaUrl !== expectedBeta || alphaPath !== resolve(join(rootPath, handle))
118
+ };
119
+ }).filter((session) => session !== null);
120
+ return sessions.sort((left, right) => left.handle.localeCompare(right.handle));
121
+ }
122
+ function selectPreferredSession(handle, sessions) {
123
+ const expectedName = getHandleSessionName(handle);
124
+ const exact = sessions.find((session) => session.name === expectedName);
125
+ return exact ?? sessions[0];
126
+ }
127
+ function parseMutagenSyncList(output) {
128
+ const sessions = [];
129
+ let current = null;
130
+ let section = "";
131
+ const finishCurrent = () => {
132
+ if (current?.identifier) {
133
+ sessions.push(current);
134
+ }
135
+ current = null;
136
+ section = "";
137
+ };
138
+ for (const line of output.split(/\r?\n/)) {
139
+ if (/^-{20,}$/.test(line.trim())) {
140
+ finishCurrent();
141
+ continue;
142
+ }
143
+ const trimmed = line.trim();
144
+ if (!trimmed) {
145
+ continue;
146
+ }
147
+ if (!current) {
148
+ current = {
149
+ alphaConnected: false,
150
+ betaConnected: false,
151
+ scanProblemCount: 0,
152
+ conflictCount: 0
153
+ };
154
+ }
155
+ if (trimmed.endsWith(":")) {
156
+ switch (trimmed.slice(0, -1)) {
157
+ case "Alpha":
158
+ case "Beta":
159
+ case "Scan problems":
160
+ case "Conflicts":
161
+ section = trimmed.slice(0, -1);
162
+ continue;
163
+ default:
164
+ continue;
165
+ }
166
+ }
167
+ if (trimmed.startsWith("Name: ")) {
168
+ current.name = trimmed.slice("Name: ".length);
169
+ continue;
170
+ }
171
+ if (trimmed.startsWith("Identifier: ")) {
172
+ current.identifier = trimmed.slice("Identifier: ".length);
173
+ continue;
174
+ }
175
+ if (trimmed.startsWith("Status: ")) {
176
+ current.status = trimmed.slice("Status: ".length);
177
+ continue;
178
+ }
179
+ if (trimmed.startsWith("Last error: ")) {
180
+ current.lastError = trimmed.slice("Last error: ".length);
181
+ continue;
182
+ }
183
+ if (section === "Alpha") {
184
+ if (trimmed.startsWith("URL: ")) {
185
+ current.alphaPath = trimmed.slice("URL: ".length);
186
+ continue;
187
+ }
188
+ if (trimmed.startsWith("Connected: ")) {
189
+ current.alphaConnected = parseConnected(trimmed);
190
+ continue;
191
+ }
192
+ }
193
+ if (section === "Beta") {
194
+ if (trimmed.startsWith("URL: ")) {
195
+ current.betaUrl = trimmed.slice("URL: ".length);
196
+ continue;
197
+ }
198
+ if (trimmed.startsWith("Connected: ")) {
199
+ current.betaConnected = parseConnected(trimmed);
200
+ continue;
201
+ }
202
+ }
203
+ if (section === "Scan problems") {
204
+ current.scanProblemCount += 1;
205
+ continue;
206
+ }
207
+ if (section === "Conflicts") {
208
+ if (trimmed.startsWith("(alpha)")) {
209
+ current.conflictCount += 1;
210
+ }
211
+ continue;
212
+ }
213
+ }
214
+ finishCurrent();
215
+ return sessions;
216
+ }
217
+ function parseConnected(line) {
218
+ return line.slice("Connected: ".length).trim().toLowerCase() === "yes";
219
+ }
220
+ function isAbortError(error) {
221
+ return error instanceof Error && error.name === "AbortError";
222
+ }
223
+ async function runMutagen(args, config, paths, handle, options = {}) {
224
+ if (options.signal?.aborted) {
225
+ throw createAbortError(handle);
226
+ }
227
+ return new Promise((resolve2, reject) => {
228
+ const child = spawn(resolveMutagenCommandPath(), args, {
229
+ env: {
230
+ ...process.env,
231
+ MUTAGEN_SSH_PATH: paths.sshToolsDir,
232
+ MUTAGEN_SSH_CONNECT_TIMEOUT: String(config.connectTimeoutSeconds)
233
+ },
234
+ stdio: ["ignore", "pipe", "pipe"]
235
+ });
236
+ let stdout = "";
237
+ let stderr = "";
238
+ let settled = false;
239
+ let killTimer = null;
240
+ const finish = (callback) => {
241
+ if (settled) {
242
+ return;
243
+ }
244
+ settled = true;
245
+ if (killTimer) {
246
+ clearTimeout(killTimer);
247
+ }
248
+ options.signal?.removeEventListener("abort", onAbort);
249
+ callback();
250
+ };
251
+ const onAbort = () => {
252
+ if (child.exitCode !== null) {
253
+ return;
254
+ }
255
+ child.kill("SIGTERM");
256
+ killTimer = setTimeout(() => {
257
+ if (child.exitCode === null) {
258
+ child.kill("SIGKILL");
259
+ }
260
+ }, 1e3);
261
+ };
262
+ options.signal?.addEventListener("abort", onAbort, { once: true });
263
+ child.stdout?.setEncoding("utf8");
264
+ child.stdout?.on("data", (chunk) => {
265
+ stdout += chunk;
266
+ });
267
+ child.stderr?.setEncoding("utf8");
268
+ child.stderr?.on("data", (chunk) => {
269
+ stderr += chunk;
270
+ });
271
+ child.once("error", (error) => {
272
+ finish(() => {
273
+ reject(options.signal?.aborted ? createAbortError(handle) : error);
274
+ });
275
+ });
276
+ child.once("close", (code) => {
277
+ const result = {
278
+ ok: code === 0,
279
+ stdout: stdout.trim(),
280
+ stderr: stderr.trim(),
281
+ status: code
282
+ };
283
+ finish(() => {
284
+ if (options.signal?.aborted) {
285
+ reject(createAbortError(handle));
286
+ return;
287
+ }
288
+ if (code !== 0 && !options.ignoreFailure) {
289
+ reject(
290
+ new Error(result.stderr || result.stdout || `mutagen failed for ${handle}`)
291
+ );
292
+ return;
293
+ }
294
+ resolve2(result);
295
+ });
296
+ });
297
+ });
298
+ }
299
+ function createAbortError(handle) {
300
+ const error = new Error(`mutagen cancelled for ${handle}`);
301
+ error.name = "AbortError";
302
+ return error;
303
+ }
304
+ function resolveCommandPath(command) {
305
+ const result = spawnSync("which", [command], { encoding: "utf8" });
306
+ if (result.status !== 0) {
307
+ throw new Error(`failed to resolve ${command}`);
308
+ }
309
+ return result.stdout.trim();
310
+ }
311
+ function writeExecutableLink(directory, name, target) {
312
+ const linkPath = join(directory, name);
313
+ try {
314
+ unlinkSync(linkPath);
315
+ } catch {
316
+ }
317
+ try {
318
+ symlinkSync(target, linkPath);
319
+ } catch {
320
+ const script = `#!/bin/sh
321
+ exec "${escapeShell(target)}" "$@"
322
+ `;
323
+ writeFileSync(linkPath, script, { mode: 493 });
324
+ chmodSync(linkPath, 493);
325
+ return;
326
+ }
327
+ try {
328
+ const stat = readFileSync(linkPath);
329
+ if (!stat) {
330
+ throw new Error("empty");
331
+ }
332
+ } catch {
333
+ const script = `#!/bin/sh
334
+ exec "${escapeShell(target)}" "$@"
335
+ `;
336
+ writeFileSync(linkPath, script, { mode: 493 });
337
+ chmodSync(linkPath, 493);
338
+ }
339
+ }
340
+ function escapeShell(value) {
341
+ return value.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("$", "\\$").replaceAll('"', '\\"');
342
+ }
343
+
344
+ export {
345
+ ensureMutagenSshEnvironment,
346
+ getHandleSessionName,
347
+ getDefaultMountIgnorePaths,
348
+ createHandleSession,
349
+ terminateSession,
350
+ inspectHandleSession,
351
+ listOwnedSessions,
352
+ selectPreferredSession,
353
+ isAbortError
354
+ };