@zookanalytics/agent-env 1.2.2 → 1.2.3
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/README.md +14 -0
- package/bin/agent-env.js +27 -1
- package/completions/_agent-env +148 -0
- package/completions/agent-env.bash +124 -0
- package/dist/InstanceList-GLFIEBZM.js +137 -0
- package/dist/MenuContainer-UYYYFIFW.js +225 -0
- package/dist/build-EHN2NQPH.js +43 -0
- package/dist/chunk-JSBRDJBE.js +30 -0
- package/dist/chunk-VDILAY23.js +3651 -0
- package/dist/chunk-Y37YO5ZL.js +682 -0
- package/dist/cli.js +239 -5321
- package/package.json +3 -2
|
@@ -0,0 +1,682 @@
|
|
|
1
|
+
// package.json
|
|
2
|
+
var package_default = {
|
|
3
|
+
name: "@zookanalytics/agent-env",
|
|
4
|
+
version: "1.2.3",
|
|
5
|
+
description: "CLI for creating isolated, AI-ready development environments",
|
|
6
|
+
type: "module",
|
|
7
|
+
bin: {
|
|
8
|
+
"agent-env": "bin/agent-env.js"
|
|
9
|
+
},
|
|
10
|
+
exports: {
|
|
11
|
+
".": {
|
|
12
|
+
types: "./dist/cli.d.ts",
|
|
13
|
+
import: "./dist/cli.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
repository: {
|
|
17
|
+
type: "git",
|
|
18
|
+
url: "https://github.com/zookanalytics/bmad-orchestrator",
|
|
19
|
+
directory: "packages/agent-env"
|
|
20
|
+
},
|
|
21
|
+
engines: {
|
|
22
|
+
node: ">=24"
|
|
23
|
+
},
|
|
24
|
+
files: [
|
|
25
|
+
"dist",
|
|
26
|
+
"bin",
|
|
27
|
+
"completions",
|
|
28
|
+
"config",
|
|
29
|
+
"README.md",
|
|
30
|
+
"LICENSE"
|
|
31
|
+
],
|
|
32
|
+
scripts: {
|
|
33
|
+
dev: "tsx src/cli.ts",
|
|
34
|
+
build: "tsup && node scripts/generate-completions.mjs",
|
|
35
|
+
test: "vitest",
|
|
36
|
+
"test:run": "vitest run",
|
|
37
|
+
"test:coverage": "vitest run --coverage",
|
|
38
|
+
lint: "eslint src/",
|
|
39
|
+
"type-check": "tsc --noEmit",
|
|
40
|
+
check: "pnpm type-check && pnpm lint && pnpm test:run"
|
|
41
|
+
},
|
|
42
|
+
dependencies: {
|
|
43
|
+
chalk: "^5.3.0",
|
|
44
|
+
commander: "^14.0.2",
|
|
45
|
+
execa: "^9.6.1",
|
|
46
|
+
ink: "^6.6.0",
|
|
47
|
+
"jsonc-parser": "^3.3.1",
|
|
48
|
+
react: "^19.2.3",
|
|
49
|
+
"timeago.js": "^4.0.2"
|
|
50
|
+
},
|
|
51
|
+
devDependencies: {
|
|
52
|
+
"@inkjs/ui": "^2.0.0",
|
|
53
|
+
"@types/node": "^20.14.10",
|
|
54
|
+
"@types/react": "^19.2.8",
|
|
55
|
+
"@zookanalytics/shared": "workspace:*",
|
|
56
|
+
"ink-testing-library": "^4.0.0",
|
|
57
|
+
tsup: "^8.5.1",
|
|
58
|
+
tsx: "^4.21.0"
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// src/lib/update-check.ts
|
|
63
|
+
import chalk from "chalk";
|
|
64
|
+
import * as fs from "fs/promises";
|
|
65
|
+
import { dirname } from "path";
|
|
66
|
+
function normaliseVersion(version) {
|
|
67
|
+
const withoutBuild = version.split("+")[0];
|
|
68
|
+
const withoutPre = withoutBuild.split("-")[0];
|
|
69
|
+
return withoutPre;
|
|
70
|
+
}
|
|
71
|
+
function isNewerVersion(current, registry) {
|
|
72
|
+
const normCurrent = normaliseVersion(current);
|
|
73
|
+
const normRegistry = normaliseVersion(registry);
|
|
74
|
+
const currentParts = normCurrent.split(".").map(Number);
|
|
75
|
+
const registryParts = normRegistry.split(".").map(Number);
|
|
76
|
+
const len = Math.max(currentParts.length, registryParts.length);
|
|
77
|
+
for (let i = 0; i < len; i++) {
|
|
78
|
+
const c = currentParts[i] ?? 0;
|
|
79
|
+
const r = registryParts[i] ?? 0;
|
|
80
|
+
if (r > c) return true;
|
|
81
|
+
if (r < c) return false;
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
async function readCache(cachePath, readFileFn) {
|
|
86
|
+
try {
|
|
87
|
+
const raw = await readFileFn(cachePath, "utf-8");
|
|
88
|
+
const parsed = JSON.parse(raw);
|
|
89
|
+
if (parsed !== null && typeof parsed === "object" && "lastCheck" in parsed && "latestVersion" in parsed && typeof parsed.lastCheck === "number" && typeof parsed.latestVersion === "string") {
|
|
90
|
+
return parsed;
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
async function writeCache(cachePath, data, mkdirFn, writeFileFn) {
|
|
98
|
+
try {
|
|
99
|
+
await mkdirFn(dirname(cachePath), { recursive: true });
|
|
100
|
+
await writeFileFn(cachePath, JSON.stringify(data), "utf-8");
|
|
101
|
+
} catch {
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async function fetchLatestVersion(packageName, fetchFn) {
|
|
105
|
+
try {
|
|
106
|
+
const url = `https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`;
|
|
107
|
+
const response = await fetchFn(url, {
|
|
108
|
+
headers: { Accept: "application/json" },
|
|
109
|
+
signal: AbortSignal.timeout(5e3)
|
|
110
|
+
});
|
|
111
|
+
const json = await response.json();
|
|
112
|
+
if (json !== null && typeof json === "object" && "version" in json && typeof json.version === "string") {
|
|
113
|
+
return json.version;
|
|
114
|
+
}
|
|
115
|
+
return null;
|
|
116
|
+
} catch {
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
function formatUpdateMessage(currentVersion, latestVersion, packageName) {
|
|
121
|
+
const normCurrent = normaliseVersion(currentVersion);
|
|
122
|
+
const line1 = chalk.yellow(`Update available: ${normCurrent} -> ${latestVersion}`);
|
|
123
|
+
const line2 = chalk.cyan(`Run: pnpm add -g ${packageName}`);
|
|
124
|
+
return `${line1}
|
|
125
|
+
${line2}`;
|
|
126
|
+
}
|
|
127
|
+
async function checkForUpdate(opts) {
|
|
128
|
+
const {
|
|
129
|
+
currentVersion,
|
|
130
|
+
packageName,
|
|
131
|
+
cachePath,
|
|
132
|
+
cacheTtlMs,
|
|
133
|
+
fetchFn = fetch,
|
|
134
|
+
readFile: readFile5 = (p, enc) => fs.readFile(p, enc),
|
|
135
|
+
writeFile: writeFile3 = (p, d, enc) => fs.writeFile(p, d, enc),
|
|
136
|
+
mkdir: mkdir4 = (p, o) => fs.mkdir(p, o),
|
|
137
|
+
now = () => Date.now()
|
|
138
|
+
} = opts;
|
|
139
|
+
const currentTime = now();
|
|
140
|
+
const cache = await readCache(cachePath, readFile5);
|
|
141
|
+
let latestVersion = null;
|
|
142
|
+
const isCacheFresh = cache !== null && currentTime - cache.lastCheck < cacheTtlMs;
|
|
143
|
+
if (isCacheFresh) {
|
|
144
|
+
latestVersion = cache.latestVersion;
|
|
145
|
+
} else {
|
|
146
|
+
latestVersion = await fetchLatestVersion(packageName, fetchFn);
|
|
147
|
+
if (latestVersion !== null) {
|
|
148
|
+
await writeCache(cachePath, { lastCheck: currentTime, latestVersion }, mkdir4, writeFile3);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (latestVersion !== null && isNewerVersion(currentVersion, latestVersion)) {
|
|
152
|
+
return formatUpdateMessage(currentVersion, latestVersion, packageName);
|
|
153
|
+
}
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// src/lib/version-drift.ts
|
|
158
|
+
import { parse as parseJsonc2 } from "jsonc-parser";
|
|
159
|
+
import { spawnSync } from "child_process";
|
|
160
|
+
import { access as access2, constants, readFile as readFile4 } from "fs/promises";
|
|
161
|
+
import { homedir as homedir2 } from "os";
|
|
162
|
+
import { join as join3 } from "path";
|
|
163
|
+
|
|
164
|
+
// src/lib/devcontainer.ts
|
|
165
|
+
import { parse as parseJsonc } from "jsonc-parser";
|
|
166
|
+
import { accessSync } from "fs";
|
|
167
|
+
import { access, cp, mkdir as mkdir2, readdir, readFile as readFile2, stat, writeFile as writeFile2 } from "fs/promises";
|
|
168
|
+
import { dirname as dirname2, join } from "path";
|
|
169
|
+
import { fileURLToPath } from "url";
|
|
170
|
+
|
|
171
|
+
// src/lib/types.ts
|
|
172
|
+
var AGENT_ENV_DIR = ".agent-env";
|
|
173
|
+
var WORKSPACES_DIR = "workspaces";
|
|
174
|
+
var REPOS_DIR = "repos";
|
|
175
|
+
var STATE_FILE = "state.json";
|
|
176
|
+
var STATE_FILE_TMP = "state.json.tmp";
|
|
177
|
+
var CONTAINER_PREFIX = "ae-";
|
|
178
|
+
var MAX_INSTANCE_NAME_LENGTH = 20;
|
|
179
|
+
var MAX_REPO_SLUG_LENGTH = 39;
|
|
180
|
+
var MAX_CONTAINER_NAME_LENGTH = 63;
|
|
181
|
+
if (CONTAINER_PREFIX.length + MAX_REPO_SLUG_LENGTH + 1 + MAX_INSTANCE_NAME_LENGTH !== MAX_CONTAINER_NAME_LENGTH) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
"BUG: MAX_CONTAINER_NAME_LENGTH does not equal CONTAINER_PREFIX + MAX_REPO_SLUG_LENGTH + 1 + MAX_INSTANCE_NAME_LENGTH"
|
|
184
|
+
);
|
|
185
|
+
}
|
|
186
|
+
function createFallbackState(workspaceName) {
|
|
187
|
+
return {
|
|
188
|
+
instance: workspaceName,
|
|
189
|
+
repoSlug: "unknown",
|
|
190
|
+
repoUrl: "unknown",
|
|
191
|
+
createdAt: "unknown",
|
|
192
|
+
lastAttached: "unknown",
|
|
193
|
+
purpose: null,
|
|
194
|
+
containerName: `${CONTAINER_PREFIX}${workspaceName}`,
|
|
195
|
+
repoConfigDetected: false
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// src/lib/devcontainer.ts
|
|
200
|
+
var defaultFsDeps = { access, cp, mkdir: mkdir2, readdir, readFile: readFile2, stat, writeFile: writeFile2 };
|
|
201
|
+
var DEVCONTAINER_DIR = ".devcontainer";
|
|
202
|
+
var DEVCONTAINER_JSON = "devcontainer.json";
|
|
203
|
+
var DOT_DEVCONTAINER_JSON = ".devcontainer.json";
|
|
204
|
+
var MANAGED_IMAGE_REPO = "ghcr.io/zookanalytics/bmad-orchestrator/devcontainer";
|
|
205
|
+
function getManagedImage() {
|
|
206
|
+
return `${MANAGED_IMAGE_REPO}:${package_default.version}`;
|
|
207
|
+
}
|
|
208
|
+
var cachedPackageRoot;
|
|
209
|
+
function getPackageRoot(checkAccess = accessSync) {
|
|
210
|
+
if (cachedPackageRoot) return cachedPackageRoot;
|
|
211
|
+
let dir = dirname2(fileURLToPath(import.meta.url));
|
|
212
|
+
const startDir = dir;
|
|
213
|
+
for (; ; ) {
|
|
214
|
+
try {
|
|
215
|
+
checkAccess(join(dir, "package.json"));
|
|
216
|
+
cachedPackageRoot = dir;
|
|
217
|
+
return dir;
|
|
218
|
+
} catch (err) {
|
|
219
|
+
const code = err?.code;
|
|
220
|
+
if (code === "EACCES" || code === "EPERM") {
|
|
221
|
+
throw new Error(`Permission denied accessing ${join(dir, "package.json")}`);
|
|
222
|
+
}
|
|
223
|
+
const parent = dirname2(dir);
|
|
224
|
+
if (parent === dir) {
|
|
225
|
+
throw new Error(`Could not find package.json in ${startDir} or any parent directory`);
|
|
226
|
+
}
|
|
227
|
+
dir = parent;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
function getBaselineConfigPath() {
|
|
232
|
+
return join(getPackageRoot(), "config", "baseline");
|
|
233
|
+
}
|
|
234
|
+
function getTemplatesPath() {
|
|
235
|
+
return join(getPackageRoot(), "config", "templates");
|
|
236
|
+
}
|
|
237
|
+
async function copyStatusBarTemplate(workspacePath, deps = defaultFsDeps) {
|
|
238
|
+
const templatesPath = getTemplatesPath();
|
|
239
|
+
const srcFile = join(templatesPath, "statusBar.template.json");
|
|
240
|
+
try {
|
|
241
|
+
await deps.stat(srcFile);
|
|
242
|
+
} catch (err) {
|
|
243
|
+
if (err.code === "ENOENT") return;
|
|
244
|
+
throw err;
|
|
245
|
+
}
|
|
246
|
+
const targetDir = join(workspacePath, AGENT_ENV_DIR);
|
|
247
|
+
await deps.mkdir(targetDir, { recursive: true });
|
|
248
|
+
await deps.cp(srcFile, join(targetDir, "statusBar.template.json"));
|
|
249
|
+
}
|
|
250
|
+
async function copyManagedAssets(workspacePath, deps = defaultFsDeps) {
|
|
251
|
+
const baselinePath = getBaselineConfigPath();
|
|
252
|
+
const targetDir = join(workspacePath, AGENT_ENV_DIR);
|
|
253
|
+
await deps.mkdir(targetDir, { recursive: true });
|
|
254
|
+
await deps.cp(baselinePath, targetDir, {
|
|
255
|
+
recursive: true,
|
|
256
|
+
filter: (source) => !source.endsWith("devcontainer.json")
|
|
257
|
+
});
|
|
258
|
+
await copyStatusBarTemplate(workspacePath, deps);
|
|
259
|
+
}
|
|
260
|
+
async function resolveDockerfilePath(workspacePath, deps) {
|
|
261
|
+
const candidates = [
|
|
262
|
+
join(workspacePath, DEVCONTAINER_DIR, DEVCONTAINER_JSON),
|
|
263
|
+
join(workspacePath, DEVCONTAINER_JSON),
|
|
264
|
+
join(workspacePath, DOT_DEVCONTAINER_JSON)
|
|
265
|
+
];
|
|
266
|
+
let configPath = null;
|
|
267
|
+
for (const candidate of candidates) {
|
|
268
|
+
try {
|
|
269
|
+
await deps.stat(candidate);
|
|
270
|
+
configPath = candidate;
|
|
271
|
+
break;
|
|
272
|
+
} catch {
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (!configPath) {
|
|
276
|
+
return null;
|
|
277
|
+
}
|
|
278
|
+
const content = await deps.readFile(configPath, "utf-8");
|
|
279
|
+
const errors = [];
|
|
280
|
+
const config = parseJsonc(content, errors, { allowTrailingComma: true });
|
|
281
|
+
if (errors.length > 0) {
|
|
282
|
+
throw new Error(`Failed to parse devcontainer config at ${configPath}: Invalid JSONC`);
|
|
283
|
+
}
|
|
284
|
+
const configDir = dirname2(configPath);
|
|
285
|
+
if (config?.build?.dockerfile) {
|
|
286
|
+
return join(configDir, config.build.dockerfile);
|
|
287
|
+
}
|
|
288
|
+
if (config?.dockerfile) {
|
|
289
|
+
return join(configDir, config.dockerfile);
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
await deps.stat(join(configDir, "Dockerfile"));
|
|
293
|
+
return join(configDir, "Dockerfile");
|
|
294
|
+
} catch {
|
|
295
|
+
return null;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
function parseDockerfileImages(content, logger) {
|
|
299
|
+
const fromRegex = /^\s*FROM\s+(?:--\S+\s+)*(\S+)(?:\s+[Aa][Ss]\s+(\S+))?/i;
|
|
300
|
+
const stageNames = /* @__PURE__ */ new Set();
|
|
301
|
+
const images = /* @__PURE__ */ new Set();
|
|
302
|
+
for (const line of content.split("\n")) {
|
|
303
|
+
if (line.trim().startsWith("#")) continue;
|
|
304
|
+
const match = fromRegex.exec(line);
|
|
305
|
+
if (match?.[2]) {
|
|
306
|
+
stageNames.add(match[2].toLowerCase());
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
for (const line of content.split("\n")) {
|
|
310
|
+
const trimmed = line.trim();
|
|
311
|
+
if (trimmed.startsWith("#")) continue;
|
|
312
|
+
const match = fromRegex.exec(line);
|
|
313
|
+
if (!match) continue;
|
|
314
|
+
const image = match[1];
|
|
315
|
+
if (image.includes("$")) {
|
|
316
|
+
logger?.warn(`Skipping parameterized FROM: ${image}`);
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
if (image.toLowerCase() === "scratch") {
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
if (stageNames.has(image.toLowerCase())) {
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
images.add(image);
|
|
326
|
+
}
|
|
327
|
+
return [...images];
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// src/lib/workspace.ts
|
|
331
|
+
import { createHash } from "crypto";
|
|
332
|
+
import { mkdir as mkdir3, readdir as readdir2, readFile as readFile3, rm, stat as stat2 } from "fs/promises";
|
|
333
|
+
import { homedir } from "os";
|
|
334
|
+
import { join as join2 } from "path";
|
|
335
|
+
var defaultFsDeps2 = { mkdir: mkdir3, readdir: readdir2, stat: stat2, homedir };
|
|
336
|
+
var VALID_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
|
|
337
|
+
function validateNameSegment(value, label) {
|
|
338
|
+
if (!value) {
|
|
339
|
+
throw new Error(`${label} must not be empty`);
|
|
340
|
+
}
|
|
341
|
+
if (!VALID_NAME_PATTERN.test(value)) {
|
|
342
|
+
throw new Error(
|
|
343
|
+
`${label} contains invalid characters: "${value}". Only alphanumeric, dash, dot, and underscore are allowed (must start with alphanumeric).`
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
function deriveRepoSlug(url) {
|
|
348
|
+
const cleaned = url.replace(/\/+$/, "").replace(/\.git$/, "");
|
|
349
|
+
const lastSlash = cleaned.lastIndexOf("/");
|
|
350
|
+
const lastColon = cleaned.lastIndexOf(":");
|
|
351
|
+
const lastSeparator = Math.max(lastSlash, lastColon);
|
|
352
|
+
if (lastSeparator === -1) {
|
|
353
|
+
if (!cleaned) {
|
|
354
|
+
throw new Error(`Cannot derive repo slug from URL: ${url}`);
|
|
355
|
+
}
|
|
356
|
+
return compressSlug(cleaned.toLowerCase());
|
|
357
|
+
}
|
|
358
|
+
const repoName = cleaned.slice(lastSeparator + 1);
|
|
359
|
+
if (!repoName) {
|
|
360
|
+
throw new Error(`Cannot derive repo slug from URL: ${url}`);
|
|
361
|
+
}
|
|
362
|
+
return compressSlug(repoName.toLowerCase());
|
|
363
|
+
}
|
|
364
|
+
function compressSlug(slug, maxLength = MAX_REPO_SLUG_LENGTH) {
|
|
365
|
+
if (slug.length <= maxLength) {
|
|
366
|
+
return slug;
|
|
367
|
+
}
|
|
368
|
+
const hash = createHash("sha256").update(slug).digest("hex").slice(0, 6);
|
|
369
|
+
const overhead = 8;
|
|
370
|
+
const available = Math.max(0, maxLength - overhead);
|
|
371
|
+
const prefixLen = Math.ceil(available / 2);
|
|
372
|
+
const suffixLen = available - prefixLen;
|
|
373
|
+
const prefix = slug.slice(0, prefixLen);
|
|
374
|
+
const suffix = slug.slice(slug.length - suffixLen);
|
|
375
|
+
return `${prefix}_${hash}_${suffix}`;
|
|
376
|
+
}
|
|
377
|
+
function getWorkspacesBaseDir(deps = defaultFsDeps2) {
|
|
378
|
+
return join2(deps.homedir(), AGENT_ENV_DIR, WORKSPACES_DIR);
|
|
379
|
+
}
|
|
380
|
+
function deriveWorkspaceName(repo, instance) {
|
|
381
|
+
validateNameSegment(repo, "repo");
|
|
382
|
+
validateNameSegment(instance, "instance");
|
|
383
|
+
return `${repo}-${instance}`;
|
|
384
|
+
}
|
|
385
|
+
function deriveContainerName(workspaceName) {
|
|
386
|
+
return `${CONTAINER_PREFIX}${workspaceName}`;
|
|
387
|
+
}
|
|
388
|
+
function getWorkspacePath(repo, instance, deps = defaultFsDeps2) {
|
|
389
|
+
const name = deriveWorkspaceName(repo, instance);
|
|
390
|
+
const root = join2(getWorkspacesBaseDir(deps), name);
|
|
391
|
+
const agentEnvDir = join2(root, AGENT_ENV_DIR);
|
|
392
|
+
const stateFile = join2(agentEnvDir, STATE_FILE);
|
|
393
|
+
return { root, name, agentEnvDir, stateFile };
|
|
394
|
+
}
|
|
395
|
+
function getWorkspacePathByName(workspaceName, deps = defaultFsDeps2) {
|
|
396
|
+
const root = join2(getWorkspacesBaseDir(deps), workspaceName);
|
|
397
|
+
const agentEnvDir = join2(root, AGENT_ENV_DIR);
|
|
398
|
+
const stateFile = join2(agentEnvDir, STATE_FILE);
|
|
399
|
+
return { root, name: workspaceName, agentEnvDir, stateFile };
|
|
400
|
+
}
|
|
401
|
+
async function workspaceExists(repo, instance, deps = defaultFsDeps2) {
|
|
402
|
+
const wsPath = getWorkspacePath(repo, instance, deps);
|
|
403
|
+
try {
|
|
404
|
+
const stats = await deps.stat(wsPath.root);
|
|
405
|
+
return stats.isDirectory();
|
|
406
|
+
} catch (err) {
|
|
407
|
+
if (err.code === "ENOENT") {
|
|
408
|
+
return false;
|
|
409
|
+
}
|
|
410
|
+
throw err;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
async function scanWorkspaces(deps = defaultFsDeps2) {
|
|
414
|
+
const baseDir = getWorkspacesBaseDir(deps);
|
|
415
|
+
try {
|
|
416
|
+
const entries = await deps.readdir(baseDir, { withFileTypes: true });
|
|
417
|
+
return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
|
|
418
|
+
} catch (err) {
|
|
419
|
+
if (err.code === "ENOENT") {
|
|
420
|
+
return [];
|
|
421
|
+
}
|
|
422
|
+
throw err;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
function looksLikeUrl(value) {
|
|
426
|
+
return value.includes("/") || value.includes(":");
|
|
427
|
+
}
|
|
428
|
+
async function resolveRepo(opts, executor) {
|
|
429
|
+
const repoFlag = opts.repo?.trim();
|
|
430
|
+
if (repoFlag !== void 0 && repoFlag !== "") {
|
|
431
|
+
if (looksLikeUrl(repoFlag)) {
|
|
432
|
+
try {
|
|
433
|
+
const slug2 = deriveRepoSlug(repoFlag);
|
|
434
|
+
return { resolved: true, repoSlug: slug2 };
|
|
435
|
+
} catch {
|
|
436
|
+
return {
|
|
437
|
+
resolved: false,
|
|
438
|
+
error: {
|
|
439
|
+
code: "INVALID_REPO",
|
|
440
|
+
message: `Cannot derive repo slug from: ${repoFlag}`,
|
|
441
|
+
suggestion: "Provide a valid git URL or repo slug."
|
|
442
|
+
}
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
const slug = repoFlag.toLowerCase();
|
|
447
|
+
if (!VALID_NAME_PATTERN.test(slug)) {
|
|
448
|
+
return {
|
|
449
|
+
resolved: false,
|
|
450
|
+
error: {
|
|
451
|
+
code: "INVALID_REPO",
|
|
452
|
+
message: `Invalid repo slug: "${repoFlag}". Only alphanumeric, dash, dot, and underscore allowed (must start with alphanumeric).`,
|
|
453
|
+
suggestion: "Provide a valid repo slug or git URL."
|
|
454
|
+
}
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
return { resolved: true, repoSlug: slug };
|
|
458
|
+
}
|
|
459
|
+
if (opts.cwd) {
|
|
460
|
+
const result = await executor("git", ["remote", "get-url", "origin"], {
|
|
461
|
+
cwd: opts.cwd
|
|
462
|
+
});
|
|
463
|
+
if (result.ok && result.stdout.trim()) {
|
|
464
|
+
try {
|
|
465
|
+
const slug = deriveRepoSlug(result.stdout.trim());
|
|
466
|
+
return { resolved: true, repoSlug: slug };
|
|
467
|
+
} catch {
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
return { resolved: false };
|
|
472
|
+
}
|
|
473
|
+
var defaultResolveInstanceDeps = {
|
|
474
|
+
fsDeps: defaultFsDeps2,
|
|
475
|
+
readFile: readFile3
|
|
476
|
+
};
|
|
477
|
+
async function resolveInstance(instanceName, repoSlug, deps = defaultResolveInstanceDeps) {
|
|
478
|
+
const workspaces = await scanWorkspaces(deps.fsDeps);
|
|
479
|
+
if (workspaces.includes(instanceName)) {
|
|
480
|
+
return { found: true, workspaceName: instanceName };
|
|
481
|
+
}
|
|
482
|
+
if (repoSlug) {
|
|
483
|
+
const expectedName = `${repoSlug}-${instanceName}`;
|
|
484
|
+
if (workspaces.includes(expectedName)) {
|
|
485
|
+
return { found: true, workspaceName: expectedName };
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
const matches = [];
|
|
489
|
+
for (const wsName of workspaces) {
|
|
490
|
+
const wsPath = getWorkspacePathByName(wsName, deps.fsDeps);
|
|
491
|
+
try {
|
|
492
|
+
const content = await deps.readFile(wsPath.stateFile, "utf-8");
|
|
493
|
+
const state = JSON.parse(content);
|
|
494
|
+
if (typeof state === "object" && state !== null && state.instance === instanceName) {
|
|
495
|
+
matches.push(wsName);
|
|
496
|
+
if (matches.length > 1) break;
|
|
497
|
+
}
|
|
498
|
+
} catch {
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
if (matches.length === 1) {
|
|
502
|
+
return { found: true, workspaceName: matches[0] };
|
|
503
|
+
}
|
|
504
|
+
if (matches.length > 1) {
|
|
505
|
+
const repoSlugs = matches.map((ws) => {
|
|
506
|
+
const idx = ws.lastIndexOf(`-${instanceName}`);
|
|
507
|
+
return idx > 0 ? ws.slice(0, idx) : ws;
|
|
508
|
+
});
|
|
509
|
+
return {
|
|
510
|
+
found: false,
|
|
511
|
+
error: {
|
|
512
|
+
code: "AMBIGUOUS_INSTANCE",
|
|
513
|
+
message: `Multiple instances named '${instanceName}' exist across repos: ${repoSlugs.join(", ")}`,
|
|
514
|
+
suggestion: "Use --repo <slug> to specify which repo."
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
}
|
|
518
|
+
return {
|
|
519
|
+
found: false,
|
|
520
|
+
error: {
|
|
521
|
+
code: "WORKSPACE_NOT_FOUND",
|
|
522
|
+
message: `Instance '${instanceName}' not found`,
|
|
523
|
+
suggestion: "Use `agent-env list` to see available instances."
|
|
524
|
+
}
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
var defaultDeleteFsDeps = { rm };
|
|
528
|
+
async function deleteWorkspace(wsPath, deps = defaultDeleteFsDeps) {
|
|
529
|
+
await deps.rm(wsPath.root, { recursive: true, force: true });
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// src/lib/version-drift.ts
|
|
533
|
+
function normaliseVersion2(version) {
|
|
534
|
+
return version.split("+")[0].split("-")[0];
|
|
535
|
+
}
|
|
536
|
+
function isNewerVersion2(running, installed) {
|
|
537
|
+
const r = normaliseVersion2(running).split(".").map(Number);
|
|
538
|
+
const i = normaliseVersion2(installed).split(".").map(Number);
|
|
539
|
+
const len = Math.max(r.length, i.length);
|
|
540
|
+
for (let j = 0; j < len; j++) {
|
|
541
|
+
const rv = r[j] ?? 0;
|
|
542
|
+
const iv = i[j] ?? 0;
|
|
543
|
+
if (iv > rv) return true;
|
|
544
|
+
if (iv < rv) return false;
|
|
545
|
+
}
|
|
546
|
+
return false;
|
|
547
|
+
}
|
|
548
|
+
function getInstalledVersion(deps = {}) {
|
|
549
|
+
const spawn = deps.spawn ?? spawnSync;
|
|
550
|
+
try {
|
|
551
|
+
const result = spawn("agent-env", ["--version"], {
|
|
552
|
+
encoding: "utf-8",
|
|
553
|
+
timeout: 5e3,
|
|
554
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
555
|
+
});
|
|
556
|
+
if (result.status !== 0 || typeof result.stdout !== "string") {
|
|
557
|
+
return null;
|
|
558
|
+
}
|
|
559
|
+
const version = result.stdout.trim();
|
|
560
|
+
return /^\d+\.\d+\.\d+/.test(version) ? version : null;
|
|
561
|
+
} catch {
|
|
562
|
+
return null;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
async function isPackagePathStale(deps = {}) {
|
|
566
|
+
const { access: accessFn = access2, getBaselinePath = getBaselineConfigPath } = deps;
|
|
567
|
+
try {
|
|
568
|
+
await accessFn(join3(getBaselinePath(), "devcontainer.json"), constants.F_OK);
|
|
569
|
+
return false;
|
|
570
|
+
} catch {
|
|
571
|
+
return true;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
async function detectImageDrift(managedConfigPath, deps = {}) {
|
|
575
|
+
const read = deps.readFile ?? readFile4;
|
|
576
|
+
const expected = (deps.getExpectedImage ?? getManagedImage)();
|
|
577
|
+
let content;
|
|
578
|
+
try {
|
|
579
|
+
content = await read(managedConfigPath, "utf-8");
|
|
580
|
+
} catch {
|
|
581
|
+
return null;
|
|
582
|
+
}
|
|
583
|
+
const errors = [];
|
|
584
|
+
const parsed = parseJsonc2(content, errors, { allowTrailingComma: true });
|
|
585
|
+
if (errors.length > 0 || parsed === null) {
|
|
586
|
+
deps.logger?.warn(
|
|
587
|
+
`Could not parse ${managedConfigPath} to check image drift \u2014 file may be corrupted. Rebuild to regenerate.`
|
|
588
|
+
);
|
|
589
|
+
return null;
|
|
590
|
+
}
|
|
591
|
+
if (typeof parsed.image !== "string") return null;
|
|
592
|
+
if (parsed.image === expected) return null;
|
|
593
|
+
return { configuredImage: parsed.image, expectedImage: expected };
|
|
594
|
+
}
|
|
595
|
+
function getManagedConfigPath(workspaceName, fsDeps) {
|
|
596
|
+
const wsPath = getWorkspacePathByName(workspaceName, fsDeps);
|
|
597
|
+
return join3(wsPath.agentEnvDir, "devcontainer.json");
|
|
598
|
+
}
|
|
599
|
+
var UPDATE_CHECK_CACHE_PATH = join3(homedir2(), ".agent-env", "update-check.json");
|
|
600
|
+
var UPDATE_CHECK_CACHE_TTL_MS = 36e5;
|
|
601
|
+
async function fetchUpdateMessageFromRegistry(force = false) {
|
|
602
|
+
try {
|
|
603
|
+
return await checkForUpdate({
|
|
604
|
+
currentVersion: package_default.version,
|
|
605
|
+
packageName: package_default.name,
|
|
606
|
+
cachePath: UPDATE_CHECK_CACHE_PATH,
|
|
607
|
+
cacheTtlMs: force ? 0 : UPDATE_CHECK_CACHE_TTL_MS
|
|
608
|
+
});
|
|
609
|
+
} catch {
|
|
610
|
+
return null;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
async function detectDriftState(workspaceName, deps = {}, options = {}) {
|
|
614
|
+
const {
|
|
615
|
+
isPackagePathStale: probe = isPackagePathStale,
|
|
616
|
+
fetchUpdateMessage = (force) => fetchUpdateMessageFromRegistry(force),
|
|
617
|
+
getInstalledVersion: resolveInstalled = getInstalledVersion,
|
|
618
|
+
detectImageDrift: imageProbe = (path) => detectImageDrift(path)
|
|
619
|
+
} = deps;
|
|
620
|
+
const installedVersion = resolveInstalled();
|
|
621
|
+
const [packageMoved, updateMessage, imageDrift] = await Promise.all([
|
|
622
|
+
probe(),
|
|
623
|
+
fetchUpdateMessage(options.forceRefresh ?? false),
|
|
624
|
+
// Resilience: a buggy override could reject. Built-in detectImageDrift
|
|
625
|
+
// already swallows its own errors, but treat the whole probe as best-effort
|
|
626
|
+
// so the entire drift state never rejects on the menu's poll loop.
|
|
627
|
+
workspaceName !== void 0 ? imageProbe(getManagedConfigPath(workspaceName)).catch(
|
|
628
|
+
() => null
|
|
629
|
+
) : Promise.resolve(null)
|
|
630
|
+
]);
|
|
631
|
+
return {
|
|
632
|
+
packageMoved,
|
|
633
|
+
updateMessage,
|
|
634
|
+
installedVersion,
|
|
635
|
+
currentVersion: package_default.version,
|
|
636
|
+
imageDrift
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
function getCurrentVersion() {
|
|
640
|
+
return package_default.version;
|
|
641
|
+
}
|
|
642
|
+
function restartMenu({ workspaceName, repoSlug }, deps = {}) {
|
|
643
|
+
const spawn = deps.spawn ?? spawnSync;
|
|
644
|
+
const exit = deps.exit ?? ((code) => process.exit(code));
|
|
645
|
+
const args = ["on", workspaceName];
|
|
646
|
+
if (repoSlug) {
|
|
647
|
+
args.push("--repo", repoSlug);
|
|
648
|
+
}
|
|
649
|
+
const result = spawn("agent-env", args, { stdio: "inherit" });
|
|
650
|
+
exit(result.status ?? 1);
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
export {
|
|
654
|
+
package_default,
|
|
655
|
+
AGENT_ENV_DIR,
|
|
656
|
+
REPOS_DIR,
|
|
657
|
+
STATE_FILE_TMP,
|
|
658
|
+
CONTAINER_PREFIX,
|
|
659
|
+
MAX_INSTANCE_NAME_LENGTH,
|
|
660
|
+
createFallbackState,
|
|
661
|
+
getManagedImage,
|
|
662
|
+
getBaselineConfigPath,
|
|
663
|
+
copyManagedAssets,
|
|
664
|
+
resolveDockerfilePath,
|
|
665
|
+
parseDockerfileImages,
|
|
666
|
+
deriveRepoSlug,
|
|
667
|
+
deriveContainerName,
|
|
668
|
+
getWorkspacePath,
|
|
669
|
+
getWorkspacePathByName,
|
|
670
|
+
workspaceExists,
|
|
671
|
+
scanWorkspaces,
|
|
672
|
+
resolveRepo,
|
|
673
|
+
resolveInstance,
|
|
674
|
+
deleteWorkspace,
|
|
675
|
+
checkForUpdate,
|
|
676
|
+
isNewerVersion2 as isNewerVersion,
|
|
677
|
+
isPackagePathStale,
|
|
678
|
+
detectImageDrift,
|
|
679
|
+
detectDriftState,
|
|
680
|
+
getCurrentVersion,
|
|
681
|
+
restartMenu
|
|
682
|
+
};
|