@zookanalytics/agent-env 0.1.2 → 0.2.0
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.
|
@@ -7,8 +7,13 @@
|
|
|
7
7
|
"containerUser": "node",
|
|
8
8
|
"initializeCommand": "bash .devcontainer/init-host.sh",
|
|
9
9
|
"mounts": [
|
|
10
|
-
"source=${localEnv:HOME}/.claude,target=/home/node/.claude,type=bind,readonly"
|
|
10
|
+
"source=${localEnv:HOME}/.claude,target=/home/node/.claude,type=bind,readonly",
|
|
11
|
+
"source=${localEnv:HOME}/.gitconfig,target=/home/node/.gitconfig,type=bind,readonly",
|
|
12
|
+
"source=/run/host-services/ssh-auth.sock,target=/run/host-services/ssh-auth.sock,type=bind"
|
|
11
13
|
],
|
|
14
|
+
"containerEnv": {
|
|
15
|
+
"SSH_AUTH_SOCK": "/run/host-services/ssh-auth.sock"
|
|
16
|
+
},
|
|
12
17
|
"features": {
|
|
13
18
|
"ghcr.io/devcontainers/features/git:1": {},
|
|
14
19
|
"ghcr.io/devcontainers/features/git-lfs:1": {}
|
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
set -euo pipefail
|
|
6
6
|
|
|
7
7
|
CLAUDE_DIR="$HOME/.claude"
|
|
8
|
+
GITCONFIG="$HOME/.gitconfig"
|
|
9
|
+
SSH_SOCKET="/run/host-services/ssh-auth.sock"
|
|
8
10
|
|
|
9
11
|
# Ensure ~/.claude directory exists (mounted read-only into container)
|
|
10
12
|
if [ ! -d "$CLAUDE_DIR" ]; then
|
|
@@ -12,4 +14,17 @@ if [ ! -d "$CLAUDE_DIR" ]; then
|
|
|
12
14
|
mkdir -p "$CLAUDE_DIR"
|
|
13
15
|
fi
|
|
14
16
|
|
|
17
|
+
# Ensure ~/.gitconfig exists (mounted read-only into container)
|
|
18
|
+
if [ ! -f "$GITCONFIG" ]; then
|
|
19
|
+
echo "agent-env: Creating $GITCONFIG (mount source)"
|
|
20
|
+
touch "$GITCONFIG"
|
|
21
|
+
fi
|
|
22
|
+
|
|
23
|
+
# Verify SSH agent socket exists (provided by Docker Desktop / OrbStack on macOS)
|
|
24
|
+
if [ ! -S "$SSH_SOCKET" ]; then
|
|
25
|
+
echo "agent-env: Warning: SSH agent socket not found at $SSH_SOCKET"
|
|
26
|
+
echo "agent-env: SSH operations (git clone/push) may not work inside the container."
|
|
27
|
+
echo "agent-env: Ensure Docker Desktop or OrbStack is running on macOS."
|
|
28
|
+
fi
|
|
29
|
+
|
|
15
30
|
echo "agent-env: Host initialization complete"
|
|
@@ -6,10 +6,6 @@ set -euo pipefail
|
|
|
6
6
|
|
|
7
7
|
echo "=== agent-env: post-create initialization ==="
|
|
8
8
|
|
|
9
|
-
# Include agent-env git config for SSH-based signing
|
|
10
|
-
cp .devcontainer/git-config /home/node/.devcontainer-git-config 2>/dev/null || true
|
|
11
|
-
git config --global include.path /home/node/.devcontainer-git-config
|
|
12
|
-
|
|
13
9
|
# Verify tool installation
|
|
14
10
|
echo "--- Tool verification ---"
|
|
15
11
|
echo "Node.js: $(node --version)"
|
package/dist/cli.js
CHANGED
|
@@ -34,12 +34,15 @@ var execute = createExecutor();
|
|
|
34
34
|
// src/cli.ts
|
|
35
35
|
import { program } from "commander";
|
|
36
36
|
import { render as render2 } from "ink";
|
|
37
|
-
import
|
|
37
|
+
import { existsSync } from "fs";
|
|
38
|
+
import { dirname as dirname3, resolve } from "path";
|
|
39
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
40
|
+
import React3 from "react";
|
|
38
41
|
|
|
39
42
|
// package.json
|
|
40
43
|
var package_default = {
|
|
41
44
|
name: "@zookanalytics/agent-env",
|
|
42
|
-
version: "0.
|
|
45
|
+
version: "0.2.0",
|
|
43
46
|
description: "CLI for creating isolated, AI-ready development environments",
|
|
44
47
|
type: "module",
|
|
45
48
|
bin: {
|
|
@@ -82,6 +85,7 @@ var package_default = {
|
|
|
82
85
|
commander: "^14.0.2",
|
|
83
86
|
execa: "^9.6.1",
|
|
84
87
|
ink: "^6.6.0",
|
|
88
|
+
"jsonc-parser": "^3.3.1",
|
|
85
89
|
react: "^19.2.3",
|
|
86
90
|
"timeago.js": "^4.0.2"
|
|
87
91
|
},
|
|
@@ -104,10 +108,26 @@ import { homedir as homedir3 } from "os";
|
|
|
104
108
|
|
|
105
109
|
// src/lib/container.ts
|
|
106
110
|
var DEVCONTAINER_UP_TIMEOUT = 12e4;
|
|
111
|
+
var DEVCONTAINER_UP_NO_CACHE_TIMEOUT = 3e5;
|
|
112
|
+
var DOCKER_PULL_TIMEOUT = 3e5;
|
|
107
113
|
var DOCKER_INSPECT_TIMEOUT = 1e4;
|
|
108
114
|
var DOCKER_INFO_TIMEOUT = 5e3;
|
|
109
115
|
var DOCKER_STOP_TIMEOUT = 3e4;
|
|
110
116
|
var DOCKER_RM_TIMEOUT = 1e4;
|
|
117
|
+
function parseDevcontainerOutput(stdout) {
|
|
118
|
+
try {
|
|
119
|
+
return JSON.parse(stdout);
|
|
120
|
+
} catch {
|
|
121
|
+
const lines = stdout.trim().split("\n");
|
|
122
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
123
|
+
try {
|
|
124
|
+
return JSON.parse(lines[i]);
|
|
125
|
+
} catch {
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
111
131
|
function createContainerLifecycle(executor = createExecutor()) {
|
|
112
132
|
async function isDockerAvailable() {
|
|
113
133
|
const result = await executor("docker", ["info"], { timeout: DOCKER_INFO_TIMEOUT });
|
|
@@ -176,7 +196,27 @@ function createContainerLifecycle(executor = createExecutor()) {
|
|
|
176
196
|
const name = result.stdout.trim().replace(/^\//, "");
|
|
177
197
|
return name || null;
|
|
178
198
|
}
|
|
179
|
-
async function
|
|
199
|
+
async function findContainerByWorkspaceLabel(workspacePath) {
|
|
200
|
+
const result = await executor(
|
|
201
|
+
"docker",
|
|
202
|
+
[
|
|
203
|
+
"ps",
|
|
204
|
+
"-a",
|
|
205
|
+
"--filter",
|
|
206
|
+
// Quote the label value to prevent parsing issues with special characters like commas
|
|
207
|
+
`label=devcontainer.local_folder="${workspacePath}"`,
|
|
208
|
+
"--format",
|
|
209
|
+
"{{.Names}}"
|
|
210
|
+
],
|
|
211
|
+
{ timeout: DOCKER_INSPECT_TIMEOUT }
|
|
212
|
+
);
|
|
213
|
+
if (!result.ok) {
|
|
214
|
+
return null;
|
|
215
|
+
}
|
|
216
|
+
const name = result.stdout.trim().split("\n")[0]?.trim();
|
|
217
|
+
return name || null;
|
|
218
|
+
}
|
|
219
|
+
async function devcontainerUp(workspacePath, containerName, options) {
|
|
180
220
|
const dockerOk = await isDockerAvailable();
|
|
181
221
|
if (!dockerOk) {
|
|
182
222
|
return {
|
|
@@ -190,24 +230,26 @@ function createContainerLifecycle(executor = createExecutor()) {
|
|
|
190
230
|
}
|
|
191
231
|
};
|
|
192
232
|
}
|
|
193
|
-
const
|
|
194
|
-
|
|
233
|
+
const buildNoCache = options?.buildNoCache === true;
|
|
234
|
+
const args = [
|
|
235
|
+
"up",
|
|
236
|
+
"--workspace-folder",
|
|
237
|
+
workspacePath,
|
|
238
|
+
...buildNoCache ? ["--build-no-cache"] : []
|
|
239
|
+
];
|
|
240
|
+
const result = await executor("devcontainer", args, {
|
|
241
|
+
timeout: buildNoCache ? DEVCONTAINER_UP_NO_CACHE_TIMEOUT : DEVCONTAINER_UP_TIMEOUT
|
|
195
242
|
});
|
|
196
|
-
|
|
197
|
-
try {
|
|
198
|
-
parsedOutput = JSON.parse(result.stdout);
|
|
199
|
-
} catch {
|
|
200
|
-
const lines = result.stdout.trim().split("\n");
|
|
201
|
-
for (let i = lines.length - 1; i >= 0; i--) {
|
|
202
|
-
try {
|
|
203
|
-
parsedOutput = JSON.parse(lines[i]);
|
|
204
|
-
break;
|
|
205
|
-
} catch {
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
}
|
|
243
|
+
const parsedOutput = parseDevcontainerOutput(result.stdout);
|
|
209
244
|
if (!result.ok) {
|
|
210
|
-
const
|
|
245
|
+
const parts = [];
|
|
246
|
+
if (parsedOutput?.message) parts.push(parsedOutput.message);
|
|
247
|
+
if (parsedOutput?.description) parts.push(parsedOutput.description);
|
|
248
|
+
if (result.stderr) parts.push(result.stderr);
|
|
249
|
+
if (parts.length === 0 && result.stdout) parts.push(result.stdout.slice(0, 1e3));
|
|
250
|
+
const details = parts.join("\n ") || "No error details available";
|
|
251
|
+
const combined = `${result.stderr} ${result.stdout}`;
|
|
252
|
+
const isNameConflict = combined.includes("is already in use") || combined.includes("name is already in use") || combined.includes("Conflict.") || combined.includes("conflict");
|
|
211
253
|
return {
|
|
212
254
|
ok: false,
|
|
213
255
|
status: "not-found",
|
|
@@ -216,7 +258,7 @@ function createContainerLifecycle(executor = createExecutor()) {
|
|
|
216
258
|
code: "CONTAINER_ERROR",
|
|
217
259
|
message: `devcontainer up failed for '${containerName}':
|
|
218
260
|
${details}`,
|
|
219
|
-
suggestion: "Check the devcontainer.json configuration and Docker logs."
|
|
261
|
+
suggestion: isNameConflict ? "A container with this name already exists. Use `docker ps -a` to find it, then `docker rm -f <name>` to remove it and retry." : "Check the devcontainer.json configuration and Docker logs."
|
|
220
262
|
}
|
|
221
263
|
};
|
|
222
264
|
}
|
|
@@ -264,11 +306,29 @@ function createContainerLifecycle(executor = createExecutor()) {
|
|
|
264
306
|
}
|
|
265
307
|
};
|
|
266
308
|
}
|
|
309
|
+
async function dockerPull(image) {
|
|
310
|
+
const result = await executor("docker", ["pull", image], {
|
|
311
|
+
timeout: DOCKER_PULL_TIMEOUT
|
|
312
|
+
});
|
|
313
|
+
if (result.ok) {
|
|
314
|
+
return { ok: true };
|
|
315
|
+
}
|
|
316
|
+
return {
|
|
317
|
+
ok: false,
|
|
318
|
+
error: {
|
|
319
|
+
code: "IMAGE_PULL_FAILED",
|
|
320
|
+
message: `Failed to pull '${image}': ${result.stderr}`,
|
|
321
|
+
suggestion: "Check network connectivity and image name. Use --no-pull to skip pulling and use cached images."
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
}
|
|
267
325
|
return {
|
|
268
326
|
isDockerAvailable,
|
|
269
327
|
containerStatus,
|
|
270
328
|
getContainerNameById,
|
|
329
|
+
findContainerByWorkspaceLabel,
|
|
271
330
|
devcontainerUp,
|
|
331
|
+
dockerPull,
|
|
272
332
|
containerStop,
|
|
273
333
|
containerRemove
|
|
274
334
|
};
|
|
@@ -290,6 +350,7 @@ import { homedir as homedir2 } from "os";
|
|
|
290
350
|
import { dirname as dirname2 } from "path";
|
|
291
351
|
|
|
292
352
|
// src/lib/devcontainer.ts
|
|
353
|
+
import { parse as parseJsonc } from "jsonc-parser";
|
|
293
354
|
import { access, cp, mkdir, readdir, readFile, stat, writeFile } from "fs/promises";
|
|
294
355
|
import { dirname, join } from "path";
|
|
295
356
|
import { fileURLToPath } from "url";
|
|
@@ -337,8 +398,8 @@ async function copyBaselineConfig(workspacePath, deps = defaultFsDeps) {
|
|
|
337
398
|
await deps.mkdir(targetDir, { recursive: true });
|
|
338
399
|
await deps.cp(baselinePath, targetDir, { recursive: true });
|
|
339
400
|
}
|
|
340
|
-
async function patchContainerName(workspacePath, containerName, deps = defaultFsDeps) {
|
|
341
|
-
const configPath = join(workspacePath,
|
|
401
|
+
async function patchContainerName(workspacePath, containerName, deps = defaultFsDeps, configDir = DEVCONTAINER_DIR) {
|
|
402
|
+
const configPath = join(workspacePath, configDir, DEVCONTAINER_JSON);
|
|
342
403
|
const content = await deps.readFile(configPath, "utf-8");
|
|
343
404
|
const config = JSON.parse(content);
|
|
344
405
|
const existing = Array.isArray(config.runArgs) ? config.runArgs : [];
|
|
@@ -346,6 +407,80 @@ async function patchContainerName(workspacePath, containerName, deps = defaultFs
|
|
|
346
407
|
config.runArgs = [...filtered, `--name=${containerName}`];
|
|
347
408
|
await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
|
|
348
409
|
}
|
|
410
|
+
async function listBaselineFiles(deps = defaultFsDeps) {
|
|
411
|
+
const baselinePath = getBaselineConfigPath();
|
|
412
|
+
const entries = await deps.readdir(baselinePath);
|
|
413
|
+
return entries.sort();
|
|
414
|
+
}
|
|
415
|
+
async function resolveDockerfilePath(workspacePath, deps) {
|
|
416
|
+
const candidates = [
|
|
417
|
+
join(workspacePath, DEVCONTAINER_DIR, DEVCONTAINER_JSON),
|
|
418
|
+
join(workspacePath, DEVCONTAINER_JSON),
|
|
419
|
+
join(workspacePath, DOT_DEVCONTAINER_JSON)
|
|
420
|
+
];
|
|
421
|
+
let configPath = null;
|
|
422
|
+
for (const candidate of candidates) {
|
|
423
|
+
try {
|
|
424
|
+
await deps.stat(candidate);
|
|
425
|
+
configPath = candidate;
|
|
426
|
+
break;
|
|
427
|
+
} catch {
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
if (!configPath) {
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
const content = await deps.readFile(configPath, "utf-8");
|
|
434
|
+
const errors = [];
|
|
435
|
+
const config = parseJsonc(content, errors, { allowTrailingComma: true });
|
|
436
|
+
if (errors.length > 0) {
|
|
437
|
+
throw new Error(`Failed to parse devcontainer config at ${configPath}: Invalid JSONC`);
|
|
438
|
+
}
|
|
439
|
+
const configDir = dirname(configPath);
|
|
440
|
+
if (config?.build?.dockerfile) {
|
|
441
|
+
return join(configDir, config.build.dockerfile);
|
|
442
|
+
}
|
|
443
|
+
if (config?.dockerfile) {
|
|
444
|
+
return join(configDir, config.dockerfile);
|
|
445
|
+
}
|
|
446
|
+
try {
|
|
447
|
+
await deps.stat(join(configDir, "Dockerfile"));
|
|
448
|
+
return join(configDir, "Dockerfile");
|
|
449
|
+
} catch {
|
|
450
|
+
return null;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
function parseDockerfileImages(content, logger) {
|
|
454
|
+
const fromRegex = /^\s*FROM\s+(?:--\S+\s+)*(\S+)(?:\s+[Aa][Ss]\s+(\S+))?/i;
|
|
455
|
+
const stageNames = /* @__PURE__ */ new Set();
|
|
456
|
+
const images = /* @__PURE__ */ new Set();
|
|
457
|
+
for (const line of content.split("\n")) {
|
|
458
|
+
if (line.trim().startsWith("#")) continue;
|
|
459
|
+
const match = fromRegex.exec(line);
|
|
460
|
+
if (match?.[2]) {
|
|
461
|
+
stageNames.add(match[2].toLowerCase());
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
for (const line of content.split("\n")) {
|
|
465
|
+
const trimmed = line.trim();
|
|
466
|
+
if (trimmed.startsWith("#")) continue;
|
|
467
|
+
const match = fromRegex.exec(line);
|
|
468
|
+
if (!match) continue;
|
|
469
|
+
const image = match[1];
|
|
470
|
+
if (image.includes("$")) {
|
|
471
|
+
logger?.warn(`Skipping parameterized FROM: ${image}`);
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
if (image.toLowerCase() === "scratch") {
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
if (stageNames.has(image.toLowerCase())) {
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
images.add(image);
|
|
481
|
+
}
|
|
482
|
+
return [...images];
|
|
483
|
+
}
|
|
349
484
|
|
|
350
485
|
// src/lib/state.ts
|
|
351
486
|
import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
|
|
@@ -392,7 +527,8 @@ async function writeStateAtomic(wsPath, state, deps = defaultStateFsDeps) {
|
|
|
392
527
|
await deps.writeFile(tmpPath, content, "utf-8");
|
|
393
528
|
await deps.rename(tmpPath, wsPath.stateFile);
|
|
394
529
|
}
|
|
395
|
-
function createInitialState(name, repo,
|
|
530
|
+
function createInitialState(name, repo, options) {
|
|
531
|
+
const { containerName, configSource } = options ?? {};
|
|
396
532
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
397
533
|
return {
|
|
398
534
|
name,
|
|
@@ -400,7 +536,8 @@ function createInitialState(name, repo, containerName) {
|
|
|
400
536
|
createdAt: now,
|
|
401
537
|
lastAttached: now,
|
|
402
538
|
purpose: null,
|
|
403
|
-
containerName: containerName ?? `${CONTAINER_PREFIX}${name}
|
|
539
|
+
containerName: containerName ?? `${CONTAINER_PREFIX}${name}`,
|
|
540
|
+
configSource: configSource ?? "baseline"
|
|
404
541
|
};
|
|
405
542
|
}
|
|
406
543
|
function isValidState(value) {
|
|
@@ -569,7 +706,11 @@ function createDefaultDeps() {
|
|
|
569
706
|
workspaceFsDeps: { mkdir: mkdir4, readdir: readdir3, stat: stat3, homedir: homedir2 },
|
|
570
707
|
stateFsDeps: { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
|
|
571
708
|
devcontainerFsDeps: { cp: cp2, mkdir: mkdir4, readFile: readFile3, stat: stat3, writeFile: writeFile3 },
|
|
572
|
-
rm: rm2
|
|
709
|
+
rm: rm2,
|
|
710
|
+
logger: {
|
|
711
|
+
warn: (msg) => console.warn(msg),
|
|
712
|
+
info: (msg) => console.info(msg)
|
|
713
|
+
}
|
|
573
714
|
};
|
|
574
715
|
}
|
|
575
716
|
async function createInstance(instanceName, repoUrl, deps) {
|
|
@@ -615,7 +756,7 @@ async function createInstance(instanceName, repoUrl, deps) {
|
|
|
615
756
|
timeout: GIT_CLONE_TIMEOUT
|
|
616
757
|
});
|
|
617
758
|
if (!cloneResult.ok) {
|
|
618
|
-
await safeRollback(wsPath.root, deps.rm);
|
|
759
|
+
await safeRollback(wsPath.root, deps.rm, deps.logger);
|
|
619
760
|
return {
|
|
620
761
|
ok: false,
|
|
621
762
|
error: {
|
|
@@ -628,7 +769,7 @@ async function createInstance(instanceName, repoUrl, deps) {
|
|
|
628
769
|
try {
|
|
629
770
|
await deps.workspaceFsDeps.mkdir(wsPath.agentEnvDir, { recursive: true });
|
|
630
771
|
} catch (err) {
|
|
631
|
-
await safeRollback(wsPath.root, deps.rm);
|
|
772
|
+
await safeRollback(wsPath.root, deps.rm, deps.logger);
|
|
632
773
|
return {
|
|
633
774
|
ok: false,
|
|
634
775
|
error: {
|
|
@@ -639,11 +780,12 @@ async function createInstance(instanceName, repoUrl, deps) {
|
|
|
639
780
|
};
|
|
640
781
|
}
|
|
641
782
|
const hasConfig = await hasDevcontainerConfig(wsPath.root, deps.devcontainerFsDeps);
|
|
783
|
+
let configSource = "baseline";
|
|
642
784
|
if (!hasConfig) {
|
|
643
785
|
try {
|
|
644
786
|
await copyBaselineConfig(wsPath.root, deps.devcontainerFsDeps);
|
|
645
787
|
} catch (err) {
|
|
646
|
-
await safeRollback(wsPath.root, deps.rm);
|
|
788
|
+
await safeRollback(wsPath.root, deps.rm, deps.logger);
|
|
647
789
|
return {
|
|
648
790
|
ok: false,
|
|
649
791
|
error: {
|
|
@@ -655,7 +797,7 @@ async function createInstance(instanceName, repoUrl, deps) {
|
|
|
655
797
|
try {
|
|
656
798
|
await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps);
|
|
657
799
|
} catch (err) {
|
|
658
|
-
await safeRollback(wsPath.root, deps.rm);
|
|
800
|
+
await safeRollback(wsPath.root, deps.rm, deps.logger);
|
|
659
801
|
return {
|
|
660
802
|
ok: false,
|
|
661
803
|
error: {
|
|
@@ -664,10 +806,25 @@ async function createInstance(instanceName, repoUrl, deps) {
|
|
|
664
806
|
}
|
|
665
807
|
};
|
|
666
808
|
}
|
|
809
|
+
} else {
|
|
810
|
+
configSource = "repo";
|
|
811
|
+
}
|
|
812
|
+
const existingContainer = await deps.container.findContainerByWorkspaceLabel(wsPath.root);
|
|
813
|
+
if (existingContainer) {
|
|
814
|
+
await safeRollback(wsPath.root, deps.rm, deps.logger);
|
|
815
|
+
return {
|
|
816
|
+
ok: false,
|
|
817
|
+
error: {
|
|
818
|
+
code: "CONTAINER_EXISTS",
|
|
819
|
+
message: `A container '${existingContainer}' already exists for this workspace path.`,
|
|
820
|
+
suggestion: `Remove it first with: docker rm -f ${existingContainer}`
|
|
821
|
+
}
|
|
822
|
+
};
|
|
667
823
|
}
|
|
668
824
|
const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName);
|
|
669
825
|
if (!containerResult.ok) {
|
|
670
|
-
|
|
826
|
+
deps.logger?.warn(`Rolling back workspace at ${wsPath.root} due to container startup failure.`);
|
|
827
|
+
await safeRollback(wsPath.root, deps.rm, deps.logger);
|
|
671
828
|
return {
|
|
672
829
|
ok: false,
|
|
673
830
|
error: containerResult.error ?? {
|
|
@@ -683,11 +840,14 @@ async function createInstance(instanceName, repoUrl, deps) {
|
|
|
683
840
|
actualContainerName = discovered;
|
|
684
841
|
}
|
|
685
842
|
} else {
|
|
686
|
-
|
|
843
|
+
deps.logger?.warn(
|
|
687
844
|
`Warning: devcontainer started successfully but no containerId returned. Using derived name '${containerName}'.`
|
|
688
845
|
);
|
|
689
846
|
}
|
|
690
|
-
const state = createInitialState(wsPath.name, repoUrl,
|
|
847
|
+
const state = createInitialState(wsPath.name, repoUrl, {
|
|
848
|
+
containerName: actualContainerName,
|
|
849
|
+
configSource
|
|
850
|
+
});
|
|
691
851
|
await writeStateAtomic(wsPath, state, deps.stateFsDeps);
|
|
692
852
|
await ensureGitExclude(wsPath.root, deps.stateFsDeps);
|
|
693
853
|
return {
|
|
@@ -696,11 +856,11 @@ async function createInstance(instanceName, repoUrl, deps) {
|
|
|
696
856
|
containerName: actualContainerName
|
|
697
857
|
};
|
|
698
858
|
}
|
|
699
|
-
async function safeRollback(workspacePath, rmFn) {
|
|
859
|
+
async function safeRollback(workspacePath, rmFn, logger) {
|
|
700
860
|
try {
|
|
701
861
|
await rmFn(workspacePath, { recursive: true, force: true });
|
|
702
862
|
} catch {
|
|
703
|
-
|
|
863
|
+
logger?.warn(`Warning: Failed to clean up workspace at ${workspacePath}`);
|
|
704
864
|
}
|
|
705
865
|
}
|
|
706
866
|
|
|
@@ -1488,24 +1648,375 @@ var purposeCommand = new Command5("purpose").description("Get or set the purpose
|
|
|
1488
1648
|
}
|
|
1489
1649
|
});
|
|
1490
1650
|
|
|
1491
|
-
// src/commands/
|
|
1492
|
-
import
|
|
1651
|
+
// src/commands/rebuild.ts
|
|
1652
|
+
import chalk from "chalk";
|
|
1493
1653
|
import { Command as Command6 } from "commander";
|
|
1494
1654
|
import { createInterface } from "readline";
|
|
1495
1655
|
|
|
1496
|
-
// src/lib/
|
|
1497
|
-
import {
|
|
1656
|
+
// src/lib/rebuild-instance.ts
|
|
1657
|
+
import {
|
|
1658
|
+
cp as cp3,
|
|
1659
|
+
mkdir as mkdir7,
|
|
1660
|
+
readdir as readdir6,
|
|
1661
|
+
readFile as readFile6,
|
|
1662
|
+
rename as rename5,
|
|
1663
|
+
rm as rm3,
|
|
1664
|
+
stat as stat6,
|
|
1665
|
+
writeFile as writeFile6,
|
|
1666
|
+
appendFile as appendFile5
|
|
1667
|
+
} from "fs/promises";
|
|
1498
1668
|
import { homedir as homedir5 } from "os";
|
|
1499
1669
|
import { join as join4 } from "path";
|
|
1670
|
+
function createRebuildDefaultDeps() {
|
|
1671
|
+
const executor = createExecutor();
|
|
1672
|
+
return {
|
|
1673
|
+
executor,
|
|
1674
|
+
container: createContainerLifecycle(executor),
|
|
1675
|
+
workspaceFsDeps: { mkdir: mkdir7, readdir: readdir6, stat: stat6, homedir: homedir5 },
|
|
1676
|
+
stateFsDeps: { readFile: readFile6, writeFile: writeFile6, rename: rename5, mkdir: mkdir7, appendFile: appendFile5 },
|
|
1677
|
+
devcontainerFsDeps: { cp: cp3, mkdir: mkdir7, readdir: readdir6, readFile: readFile6, stat: stat6, writeFile: writeFile6 },
|
|
1678
|
+
rm: rm3,
|
|
1679
|
+
rename: rename5,
|
|
1680
|
+
logger: { warn: (msg) => console.warn(msg), info: (msg) => console.info(msg) }
|
|
1681
|
+
};
|
|
1682
|
+
}
|
|
1683
|
+
async function refreshConfig(wsRoot, containerName, configSource, deps) {
|
|
1684
|
+
const devcontainerDir = join4(wsRoot, ".devcontainer");
|
|
1685
|
+
const tempDevcontainerDir = join4(wsRoot, ".devcontainer.new");
|
|
1686
|
+
if (configSource === "baseline") {
|
|
1687
|
+
try {
|
|
1688
|
+
try {
|
|
1689
|
+
const currentFiles = await deps.devcontainerFsDeps.readdir(devcontainerDir);
|
|
1690
|
+
const baselineFiles = await listBaselineFiles(deps.devcontainerFsDeps);
|
|
1691
|
+
const baselineSet = new Set(baselineFiles);
|
|
1692
|
+
const extras = currentFiles.filter((f) => !baselineSet.has(f));
|
|
1693
|
+
if (extras.length > 0) {
|
|
1694
|
+
deps.logger?.warn(`Extra files in .devcontainer/ will be deleted: ${extras.join(", ")}`);
|
|
1695
|
+
}
|
|
1696
|
+
} catch {
|
|
1697
|
+
}
|
|
1698
|
+
await deps.rm(tempDevcontainerDir, { recursive: true, force: true });
|
|
1699
|
+
await deps.devcontainerFsDeps.mkdir(tempDevcontainerDir, { recursive: true });
|
|
1700
|
+
await deps.devcontainerFsDeps.cp(getBaselineConfigPath(), tempDevcontainerDir, {
|
|
1701
|
+
recursive: true
|
|
1702
|
+
});
|
|
1703
|
+
await patchContainerName(wsRoot, containerName, deps.devcontainerFsDeps, ".devcontainer.new");
|
|
1704
|
+
await deps.rm(devcontainerDir, { recursive: true, force: true });
|
|
1705
|
+
await deps.rename(tempDevcontainerDir, devcontainerDir);
|
|
1706
|
+
} catch (err) {
|
|
1707
|
+
await deps.rm(tempDevcontainerDir, { recursive: true, force: true });
|
|
1708
|
+
return {
|
|
1709
|
+
ok: false,
|
|
1710
|
+
error: {
|
|
1711
|
+
code: "CONFIG_REFRESH_FAILED",
|
|
1712
|
+
message: `Failed to refresh baseline config: ${err instanceof Error ? err.message : String(err)}`,
|
|
1713
|
+
suggestion: "The existing container is still intact. Check that the baseline config files exist in the package."
|
|
1714
|
+
}
|
|
1715
|
+
};
|
|
1716
|
+
}
|
|
1717
|
+
} else {
|
|
1718
|
+
const configExists = await hasDevcontainerConfig(wsRoot, deps.devcontainerFsDeps);
|
|
1719
|
+
if (!configExists) {
|
|
1720
|
+
return {
|
|
1721
|
+
ok: false,
|
|
1722
|
+
error: {
|
|
1723
|
+
code: "CONFIG_MISSING",
|
|
1724
|
+
message: "Repo-provided devcontainer config is missing.",
|
|
1725
|
+
suggestion: "Re-clone the repository or provide a devcontainer config manually."
|
|
1726
|
+
}
|
|
1727
|
+
};
|
|
1728
|
+
}
|
|
1729
|
+
const dirExists = await deps.devcontainerFsDeps.stat(devcontainerDir).catch(() => null);
|
|
1730
|
+
if (dirExists) {
|
|
1731
|
+
const jsonExists = await deps.devcontainerFsDeps.stat(join4(devcontainerDir, "devcontainer.json")).catch(() => null);
|
|
1732
|
+
if (!jsonExists) {
|
|
1733
|
+
return {
|
|
1734
|
+
ok: false,
|
|
1735
|
+
error: {
|
|
1736
|
+
code: "CONFIG_CORRUPT",
|
|
1737
|
+
message: "Repo-provided devcontainer config is incomplete (missing devcontainer.json).",
|
|
1738
|
+
suggestion: "Ensure .devcontainer/devcontainer.json exists."
|
|
1739
|
+
}
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
return { ok: true };
|
|
1745
|
+
}
|
|
1746
|
+
async function lookupWorkspace(instanceName, deps) {
|
|
1747
|
+
const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
|
|
1748
|
+
if (!lookup.found) {
|
|
1749
|
+
if (lookup.reason === "ambiguous") {
|
|
1750
|
+
return {
|
|
1751
|
+
ok: false,
|
|
1752
|
+
error: {
|
|
1753
|
+
code: "AMBIGUOUS_MATCH",
|
|
1754
|
+
message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
|
|
1755
|
+
suggestion: "Use the full workspace name to specify which instance."
|
|
1756
|
+
}
|
|
1757
|
+
};
|
|
1758
|
+
}
|
|
1759
|
+
return {
|
|
1760
|
+
ok: false,
|
|
1761
|
+
error: {
|
|
1762
|
+
code: "WORKSPACE_NOT_FOUND",
|
|
1763
|
+
message: `Instance '${instanceName}' not found`,
|
|
1764
|
+
suggestion: "Use `agent-env list` to see available instances."
|
|
1765
|
+
}
|
|
1766
|
+
};
|
|
1767
|
+
}
|
|
1768
|
+
const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
|
|
1769
|
+
const state = await readState(wsPath, deps.stateFsDeps);
|
|
1770
|
+
return { ok: true, wsPath, state };
|
|
1771
|
+
}
|
|
1772
|
+
async function executePullStep(wsRoot, pull, deps) {
|
|
1773
|
+
let dockerfilePath;
|
|
1774
|
+
try {
|
|
1775
|
+
dockerfilePath = await resolveDockerfilePath(wsRoot, deps.devcontainerFsDeps);
|
|
1776
|
+
} catch (err) {
|
|
1777
|
+
return {
|
|
1778
|
+
ok: false,
|
|
1779
|
+
error: {
|
|
1780
|
+
code: "CONFIG_PARSE_FAILED",
|
|
1781
|
+
message: err instanceof Error ? err.message : String(err),
|
|
1782
|
+
suggestion: "Check that your devcontainer.json is valid JSON or JSONC."
|
|
1783
|
+
}
|
|
1784
|
+
};
|
|
1785
|
+
}
|
|
1786
|
+
const hasDockerfile = dockerfilePath !== null;
|
|
1787
|
+
if (!pull) {
|
|
1788
|
+
return { ok: true, hasDockerfile };
|
|
1789
|
+
}
|
|
1790
|
+
if (dockerfilePath === null) {
|
|
1791
|
+
deps.logger?.info("No Dockerfile found \u2014 skipping image pull.");
|
|
1792
|
+
return { ok: true, hasDockerfile: false };
|
|
1793
|
+
}
|
|
1794
|
+
let dockerfileContent;
|
|
1795
|
+
try {
|
|
1796
|
+
dockerfileContent = await deps.devcontainerFsDeps.readFile(dockerfilePath, "utf-8");
|
|
1797
|
+
} catch {
|
|
1798
|
+
return {
|
|
1799
|
+
ok: false,
|
|
1800
|
+
error: {
|
|
1801
|
+
code: "DOCKERFILE_MISSING",
|
|
1802
|
+
message: `Dockerfile not found at ${dockerfilePath}`,
|
|
1803
|
+
suggestion: "Ensure the Dockerfile exists at the configured path, or use --no-pull to skip."
|
|
1804
|
+
}
|
|
1805
|
+
};
|
|
1806
|
+
}
|
|
1807
|
+
const images = parseDockerfileImages(dockerfileContent, deps.logger);
|
|
1808
|
+
if (images.length === 0) {
|
|
1809
|
+
deps.logger?.info("No pullable FROM images found.");
|
|
1810
|
+
return { ok: true, hasDockerfile };
|
|
1811
|
+
}
|
|
1812
|
+
const results = await Promise.allSettled(
|
|
1813
|
+
images.map(async (image) => {
|
|
1814
|
+
deps.logger?.info(`Pulling ${image}...`);
|
|
1815
|
+
const pullResult = await deps.container.dockerPull(image);
|
|
1816
|
+
if (!pullResult.ok) {
|
|
1817
|
+
throw pullResult.error;
|
|
1818
|
+
}
|
|
1819
|
+
deps.logger?.info(`Pulled ${image}`);
|
|
1820
|
+
})
|
|
1821
|
+
);
|
|
1822
|
+
const firstFailure = results.find((r) => r.status === "rejected");
|
|
1823
|
+
if (firstFailure) {
|
|
1824
|
+
return {
|
|
1825
|
+
ok: false,
|
|
1826
|
+
error: firstFailure.reason
|
|
1827
|
+
};
|
|
1828
|
+
}
|
|
1829
|
+
return { ok: true, hasDockerfile };
|
|
1830
|
+
}
|
|
1831
|
+
async function teardownContainer(containerName, container, statusResult) {
|
|
1832
|
+
if (!statusResult.ok || statusResult.status === "not-found") {
|
|
1833
|
+
return { ok: true };
|
|
1834
|
+
}
|
|
1835
|
+
const stopResult = await container.containerStop(containerName);
|
|
1836
|
+
if (!stopResult.ok) {
|
|
1837
|
+
return { ok: false, error: stopResult.error };
|
|
1838
|
+
}
|
|
1839
|
+
const removeResult = await container.containerRemove(containerName);
|
|
1840
|
+
if (!removeResult.ok) {
|
|
1841
|
+
return { ok: false, error: removeResult.error };
|
|
1842
|
+
}
|
|
1843
|
+
return { ok: true };
|
|
1844
|
+
}
|
|
1845
|
+
async function rebuildInstance(instanceName, deps, options) {
|
|
1846
|
+
const {
|
|
1847
|
+
force = false,
|
|
1848
|
+
configSource: overrideConfigSource,
|
|
1849
|
+
pull = true,
|
|
1850
|
+
noCache = true
|
|
1851
|
+
} = options ?? {};
|
|
1852
|
+
const wsLookup = await lookupWorkspace(instanceName, deps);
|
|
1853
|
+
if (!wsLookup.ok) {
|
|
1854
|
+
return { ok: false, error: wsLookup.error };
|
|
1855
|
+
}
|
|
1856
|
+
const { wsPath, state } = wsLookup;
|
|
1857
|
+
const containerName = state.containerName;
|
|
1858
|
+
const dockerAvailable = await deps.container.isDockerAvailable();
|
|
1859
|
+
if (!dockerAvailable) {
|
|
1860
|
+
return {
|
|
1861
|
+
ok: false,
|
|
1862
|
+
error: {
|
|
1863
|
+
code: "ORBSTACK_REQUIRED",
|
|
1864
|
+
message: "Docker is not available. OrbStack or Docker Desktop must be running.",
|
|
1865
|
+
suggestion: "Start OrbStack or Docker Desktop, then try again."
|
|
1866
|
+
}
|
|
1867
|
+
};
|
|
1868
|
+
}
|
|
1869
|
+
const configSource = overrideConfigSource ?? state.configSource;
|
|
1870
|
+
if (!configSource) {
|
|
1871
|
+
return {
|
|
1872
|
+
ok: false,
|
|
1873
|
+
error: {
|
|
1874
|
+
code: "CONFIG_SOURCE_UNKNOWN",
|
|
1875
|
+
message: `Instance '${instanceName}' was created before config tracking was added.`,
|
|
1876
|
+
suggestion: 'Set configSource manually in .agent-env/state.json ("baseline" or "repo"), then retry.'
|
|
1877
|
+
}
|
|
1878
|
+
};
|
|
1879
|
+
}
|
|
1880
|
+
const configResult = await refreshConfig(wsPath.root, containerName, configSource, deps);
|
|
1881
|
+
if (!configResult.ok) {
|
|
1882
|
+
return { ok: false, error: configResult.error };
|
|
1883
|
+
}
|
|
1884
|
+
const pullStepResult = await executePullStep(wsPath.root, pull, deps);
|
|
1885
|
+
if (!pullStepResult.ok) {
|
|
1886
|
+
return { ok: false, error: pullStepResult.error };
|
|
1887
|
+
}
|
|
1888
|
+
const { hasDockerfile } = pullStepResult;
|
|
1889
|
+
const statusResult = await deps.container.containerStatus(containerName);
|
|
1890
|
+
const wasRunning = statusResult.ok && statusResult.status === "running";
|
|
1891
|
+
if (wasRunning && !force) {
|
|
1892
|
+
return {
|
|
1893
|
+
ok: false,
|
|
1894
|
+
error: {
|
|
1895
|
+
code: "CONTAINER_RUNNING",
|
|
1896
|
+
message: `Container '${containerName}' is currently running`,
|
|
1897
|
+
suggestion: "Stop any active sessions first, or use --force to rebuild a running container."
|
|
1898
|
+
},
|
|
1899
|
+
wasRunning: true
|
|
1900
|
+
};
|
|
1901
|
+
}
|
|
1902
|
+
const teardownResult = await teardownContainer(containerName, deps.container, statusResult);
|
|
1903
|
+
if (!teardownResult.ok) {
|
|
1904
|
+
return { ok: false, error: teardownResult.error, wasRunning };
|
|
1905
|
+
}
|
|
1906
|
+
const buildNoCache = noCache && hasDockerfile;
|
|
1907
|
+
const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
|
|
1908
|
+
buildNoCache
|
|
1909
|
+
});
|
|
1910
|
+
if (!containerResult.ok) {
|
|
1911
|
+
return {
|
|
1912
|
+
ok: false,
|
|
1913
|
+
error: containerResult.error,
|
|
1914
|
+
wasRunning
|
|
1915
|
+
};
|
|
1916
|
+
}
|
|
1917
|
+
let actualContainerName = containerName;
|
|
1918
|
+
if (containerResult.containerId) {
|
|
1919
|
+
const discovered = await deps.container.getContainerNameById(containerResult.containerId);
|
|
1920
|
+
if (discovered) {
|
|
1921
|
+
actualContainerName = discovered;
|
|
1922
|
+
}
|
|
1923
|
+
}
|
|
1924
|
+
const updatedState = {
|
|
1925
|
+
...state,
|
|
1926
|
+
containerName: actualContainerName,
|
|
1927
|
+
lastRebuilt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1928
|
+
};
|
|
1929
|
+
await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
|
|
1930
|
+
return {
|
|
1931
|
+
ok: true,
|
|
1932
|
+
containerName: actualContainerName,
|
|
1933
|
+
wasRunning
|
|
1934
|
+
};
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
// src/commands/rebuild.ts
|
|
1938
|
+
function promptForConfirmation(instanceName) {
|
|
1939
|
+
return new Promise((resolve2) => {
|
|
1940
|
+
const rl = createInterface({
|
|
1941
|
+
input: process.stdin,
|
|
1942
|
+
output: process.stderr
|
|
1943
|
+
});
|
|
1944
|
+
rl.question(
|
|
1945
|
+
`
|
|
1946
|
+
${chalk.yellow("Warning:")} Rebuilding '${instanceName}' will destroy the current container and create a new one.
|
|
1947
|
+
Any active sessions will be lost. Continue? (y/N) `,
|
|
1948
|
+
(answer) => {
|
|
1949
|
+
rl.close();
|
|
1950
|
+
resolve2(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
|
|
1951
|
+
}
|
|
1952
|
+
);
|
|
1953
|
+
rl.on("SIGINT", () => {
|
|
1954
|
+
rl.close();
|
|
1955
|
+
resolve2(false);
|
|
1956
|
+
});
|
|
1957
|
+
});
|
|
1958
|
+
}
|
|
1959
|
+
var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by recreating its container").argument("<name>", "Instance name to rebuild").option("--force", "Rebuild even if the container is currently running").option("--yes", "Skip confirmation prompt").option("--no-pull", "Skip pulling fresh base images").option("--use-cache", "Allow Docker build layer cache reuse").action(
|
|
1960
|
+
async (name, options) => {
|
|
1961
|
+
const deps = createRebuildDefaultDeps();
|
|
1962
|
+
let confirmed = false;
|
|
1963
|
+
if (!options.yes && !options.force && process.stdin.isTTY) {
|
|
1964
|
+
confirmed = await promptForConfirmation(name);
|
|
1965
|
+
if (!confirmed) {
|
|
1966
|
+
console.log("Rebuild cancelled");
|
|
1967
|
+
return;
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
const force = options.force || options.yes || confirmed;
|
|
1971
|
+
const rebuildOptions = {
|
|
1972
|
+
force,
|
|
1973
|
+
pull: options.pull,
|
|
1974
|
+
noCache: !options.useCache
|
|
1975
|
+
};
|
|
1976
|
+
if (force) {
|
|
1977
|
+
console.log(`Force-rebuilding instance '${name}'...`);
|
|
1978
|
+
} else {
|
|
1979
|
+
console.log(`Rebuilding instance '${name}'...`);
|
|
1980
|
+
}
|
|
1981
|
+
const result = await rebuildInstance(name, deps, rebuildOptions);
|
|
1982
|
+
if (!result.ok) {
|
|
1983
|
+
if (result.error.code === "CONTAINER_RUNNING") {
|
|
1984
|
+
console.error("");
|
|
1985
|
+
console.error(
|
|
1986
|
+
chalk.yellow("Container is currently running.") + " Active sessions will be terminated during rebuild."
|
|
1987
|
+
);
|
|
1988
|
+
console.error("");
|
|
1989
|
+
console.error(`Use ${chalk.bold("--force")} to rebuild anyway.`);
|
|
1990
|
+
} else {
|
|
1991
|
+
const { code, message, suggestion } = result.error;
|
|
1992
|
+
console.error(formatError(createError(code, message, suggestion)));
|
|
1993
|
+
}
|
|
1994
|
+
process.exit(1);
|
|
1995
|
+
return;
|
|
1996
|
+
}
|
|
1997
|
+
console.log(`\x1B[32m\u2713\x1B[0m Instance '${name}' rebuilt successfully`);
|
|
1998
|
+
console.log(` Container: ${result.containerName}`);
|
|
1999
|
+
}
|
|
2000
|
+
);
|
|
2001
|
+
|
|
2002
|
+
// src/commands/remove.ts
|
|
2003
|
+
import chalk3 from "chalk";
|
|
2004
|
+
import { Command as Command7 } from "commander";
|
|
2005
|
+
import { createInterface as createInterface2 } from "readline";
|
|
2006
|
+
|
|
2007
|
+
// src/lib/audit-log.ts
|
|
2008
|
+
import { appendFile as appendFile6, mkdir as mkdir8 } from "fs/promises";
|
|
2009
|
+
import { homedir as homedir6 } from "os";
|
|
2010
|
+
import { join as join5 } from "path";
|
|
1500
2011
|
function createAuditLogDefaultDeps() {
|
|
1501
|
-
return { appendFile:
|
|
2012
|
+
return { appendFile: appendFile6, mkdir: mkdir8, homedir: homedir6 };
|
|
1502
2013
|
}
|
|
1503
2014
|
function getAuditLogPath(deps) {
|
|
1504
|
-
return
|
|
2015
|
+
return join5(deps.homedir(), AGENT_ENV_DIR, "audit.log");
|
|
1505
2016
|
}
|
|
1506
2017
|
async function writeAuditLogEntry(entry, deps = createAuditLogDefaultDeps()) {
|
|
1507
2018
|
const logPath = getAuditLogPath(deps);
|
|
1508
|
-
await deps.mkdir(
|
|
2019
|
+
await deps.mkdir(join5(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
|
|
1509
2020
|
const line = JSON.stringify(entry) + "\n";
|
|
1510
2021
|
await deps.appendFile(logPath, line, "utf-8");
|
|
1511
2022
|
}
|
|
@@ -1520,17 +2031,17 @@ function createAuditEntry(instanceName, gitState, confirmationMethod) {
|
|
|
1520
2031
|
}
|
|
1521
2032
|
|
|
1522
2033
|
// src/lib/remove-instance.ts
|
|
1523
|
-
import { mkdir as
|
|
1524
|
-
import { homedir as
|
|
2034
|
+
import { mkdir as mkdir9, readdir as readdir7, readFile as readFile7, rm as rm4, stat as stat7 } from "fs/promises";
|
|
2035
|
+
import { homedir as homedir7 } from "os";
|
|
1525
2036
|
function createRemoveDefaultDeps() {
|
|
1526
2037
|
const executor = createExecutor();
|
|
1527
2038
|
return {
|
|
1528
2039
|
executor,
|
|
1529
2040
|
container: createContainerLifecycle(executor),
|
|
1530
2041
|
gitDetector: createGitStateDetector(executor),
|
|
1531
|
-
workspaceFsDeps: { mkdir:
|
|
1532
|
-
stateFsDeps: { readFile:
|
|
1533
|
-
deleteFsDeps: { rm:
|
|
2042
|
+
workspaceFsDeps: { mkdir: mkdir9, readdir: readdir7, stat: stat7, homedir: homedir7 },
|
|
2043
|
+
stateFsDeps: { readFile: readFile7 },
|
|
2044
|
+
deleteFsDeps: { rm: rm4 }
|
|
1534
2045
|
};
|
|
1535
2046
|
}
|
|
1536
2047
|
function evaluateSafetyChecks(gitState) {
|
|
@@ -1690,7 +2201,7 @@ async function removeInstance(instanceName, deps, force = false) {
|
|
|
1690
2201
|
}
|
|
1691
2202
|
|
|
1692
2203
|
// src/lib/safety-report.ts
|
|
1693
|
-
import
|
|
2204
|
+
import chalk2 from "chalk";
|
|
1694
2205
|
var BLOCKER_NEVER_PUSHED = "never pushed";
|
|
1695
2206
|
var BLOCKER_DETACHED_HEAD = "detached HEAD";
|
|
1696
2207
|
function classifyBlocker(blocker) {
|
|
@@ -1743,27 +2254,27 @@ function formatSafetyReport(instanceName, blockers, gitState) {
|
|
|
1743
2254
|
message: blocker
|
|
1744
2255
|
}));
|
|
1745
2256
|
for (const item of items) {
|
|
1746
|
-
const prefix = item.severity === "Danger" ?
|
|
2257
|
+
const prefix = item.severity === "Danger" ? chalk2.red("[Danger]") : chalk2.yellow("[Warning]");
|
|
1747
2258
|
lines.push(` ${prefix} ${item.message}`);
|
|
1748
2259
|
}
|
|
1749
2260
|
const suggestions = getSuggestions(gitState);
|
|
1750
2261
|
if (suggestions.length > 0) {
|
|
1751
2262
|
lines.push("");
|
|
1752
|
-
lines.push(
|
|
2263
|
+
lines.push(chalk2.bold("Suggestions:"));
|
|
1753
2264
|
for (const suggestion of suggestions) {
|
|
1754
2265
|
lines.push(` - ${suggestion}`);
|
|
1755
2266
|
}
|
|
1756
2267
|
}
|
|
1757
2268
|
lines.push("");
|
|
1758
|
-
lines.push(
|
|
2269
|
+
lines.push(chalk2.gray("Or use --force to bypass safety checks (data loss is permanent)."));
|
|
1759
2270
|
return lines.join("\n");
|
|
1760
2271
|
}
|
|
1761
2272
|
|
|
1762
2273
|
// src/commands/remove.ts
|
|
1763
|
-
function
|
|
1764
|
-
return new Promise((
|
|
2274
|
+
function promptForConfirmation2(instanceName) {
|
|
2275
|
+
return new Promise((resolve2) => {
|
|
1765
2276
|
let resolved = false;
|
|
1766
|
-
const rl =
|
|
2277
|
+
const rl = createInterface2({
|
|
1767
2278
|
input: process.stdin,
|
|
1768
2279
|
output: process.stderr
|
|
1769
2280
|
});
|
|
@@ -1772,13 +2283,13 @@ Type the instance name "${instanceName}" to confirm: `, (answer) => {
|
|
|
1772
2283
|
if (!resolved) {
|
|
1773
2284
|
resolved = true;
|
|
1774
2285
|
rl.close();
|
|
1775
|
-
|
|
2286
|
+
resolve2(answer);
|
|
1776
2287
|
}
|
|
1777
2288
|
});
|
|
1778
2289
|
rl.on("close", () => {
|
|
1779
2290
|
if (!resolved) {
|
|
1780
2291
|
resolved = true;
|
|
1781
|
-
|
|
2292
|
+
resolve2(null);
|
|
1782
2293
|
}
|
|
1783
2294
|
});
|
|
1784
2295
|
});
|
|
@@ -1794,12 +2305,12 @@ async function writeAuditLog(name, gitState, confirmationMethod) {
|
|
|
1794
2305
|
}
|
|
1795
2306
|
function showForceWarning(name, blockers, gitState) {
|
|
1796
2307
|
console.error("");
|
|
1797
|
-
console.error(
|
|
2308
|
+
console.error(chalk3.red.bold("\u26A0\uFE0F WARNING: Force removing with unsaved work"));
|
|
1798
2309
|
console.error("");
|
|
1799
2310
|
console.error(
|
|
1800
2311
|
formatSafetyReport(name, blockers, gitState).replace(
|
|
1801
2312
|
/Or use --force.*/,
|
|
1802
|
-
|
|
2313
|
+
chalk3.red("This data will be PERMANENTLY DELETED.")
|
|
1803
2314
|
)
|
|
1804
2315
|
);
|
|
1805
2316
|
}
|
|
@@ -1810,20 +2321,20 @@ async function resolveConfirmation(name, options) {
|
|
|
1810
2321
|
if (!process.stdin.isTTY) {
|
|
1811
2322
|
console.error("");
|
|
1812
2323
|
console.error(
|
|
1813
|
-
|
|
2324
|
+
chalk3.red(
|
|
1814
2325
|
"Cannot prompt for confirmation in non-interactive mode. Use --yes to skip confirmation."
|
|
1815
2326
|
)
|
|
1816
2327
|
);
|
|
1817
2328
|
return null;
|
|
1818
2329
|
}
|
|
1819
|
-
const answer = await
|
|
2330
|
+
const answer = await promptForConfirmation2(name);
|
|
1820
2331
|
if (answer === null || answer !== name) {
|
|
1821
2332
|
console.log("Removal cancelled");
|
|
1822
2333
|
return null;
|
|
1823
2334
|
}
|
|
1824
2335
|
return "typed-name";
|
|
1825
2336
|
}
|
|
1826
|
-
var removeCommand = new
|
|
2337
|
+
var removeCommand = new Command7("remove").description("Remove an instance with safety checks").argument("<name>", "Instance name to remove").option("--force", "Force removal, bypassing safety checks").option(
|
|
1827
2338
|
"--yes",
|
|
1828
2339
|
"Skip confirmation prompt for --force (DANGEROUS: skips all safety prompts, for scripts only)"
|
|
1829
2340
|
).action(async (name, options) => {
|
|
@@ -1887,6 +2398,7 @@ var removeCommand = new Command6("remove").description("Remove an instance with
|
|
|
1887
2398
|
// src/components/InteractiveMenu.tsx
|
|
1888
2399
|
import { Select } from "@inkjs/ui";
|
|
1889
2400
|
import { Box as Box2, Text as Text3 } from "ink";
|
|
2401
|
+
import { useState } from "react";
|
|
1890
2402
|
import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
|
|
1891
2403
|
var COLUMN_PADDING = 2;
|
|
1892
2404
|
var SELECT_PREFIX_WIDTH = 4;
|
|
@@ -1927,11 +2439,32 @@ function buildOptionLabel(instance, terminalWidth) {
|
|
|
1927
2439
|
}
|
|
1928
2440
|
return parts.join(" ");
|
|
1929
2441
|
}
|
|
2442
|
+
function ActionMenu({
|
|
2443
|
+
instanceName,
|
|
2444
|
+
onSelectAction
|
|
2445
|
+
}) {
|
|
2446
|
+
const options = [
|
|
2447
|
+
{ label: "\u{1F680} Attach to session", value: "attach" },
|
|
2448
|
+
{ label: "\u{1F6E0} Rebuild container", value: "rebuild" },
|
|
2449
|
+
{ label: "\u{1F4DD} Show purpose", value: "purpose" },
|
|
2450
|
+
{ label: "\u{1F5D1} Remove instance", value: "remove" }
|
|
2451
|
+
];
|
|
2452
|
+
return /* @__PURE__ */ jsxs3(Box2, { flexDirection: "column", children: [
|
|
2453
|
+
/* @__PURE__ */ jsx3(Box2, { marginBottom: 1, children: /* @__PURE__ */ jsxs3(Text3, { children: [
|
|
2454
|
+
"Manage",
|
|
2455
|
+
" ",
|
|
2456
|
+
/* @__PURE__ */ jsx3(Text3, { bold: true, color: "cyan", children: instanceName }),
|
|
2457
|
+
":"
|
|
2458
|
+
] }) }),
|
|
2459
|
+
/* @__PURE__ */ jsx3(Select, { options, onChange: onSelectAction })
|
|
2460
|
+
] });
|
|
2461
|
+
}
|
|
1930
2462
|
function InteractiveMenu({
|
|
1931
2463
|
instances,
|
|
1932
|
-
|
|
2464
|
+
onAction,
|
|
1933
2465
|
terminalWidth
|
|
1934
2466
|
}) {
|
|
2467
|
+
const [selectedInstance, setSelectedInstance] = useState(null);
|
|
1935
2468
|
const width = terminalWidth ?? process.stdout.columns ?? 80;
|
|
1936
2469
|
if (instances.length === 0) {
|
|
1937
2470
|
return /* @__PURE__ */ jsxs3(Box2, { flexDirection: "column", children: [
|
|
@@ -1944,13 +2477,22 @@ function InteractiveMenu({
|
|
|
1944
2477
|
] })
|
|
1945
2478
|
] });
|
|
1946
2479
|
}
|
|
2480
|
+
if (selectedInstance) {
|
|
2481
|
+
return /* @__PURE__ */ jsx3(
|
|
2482
|
+
ActionMenu,
|
|
2483
|
+
{
|
|
2484
|
+
instanceName: selectedInstance,
|
|
2485
|
+
onSelectAction: (action) => onAction(action, selectedInstance)
|
|
2486
|
+
}
|
|
2487
|
+
);
|
|
2488
|
+
}
|
|
1947
2489
|
const options = instances.map((instance) => ({
|
|
1948
2490
|
label: buildOptionLabel(instance, width),
|
|
1949
2491
|
value: instance.name
|
|
1950
2492
|
}));
|
|
1951
2493
|
return /* @__PURE__ */ jsxs3(Box2, { flexDirection: "column", children: [
|
|
1952
|
-
/* @__PURE__ */ jsx3(Box2, { marginBottom: 1, children: /* @__PURE__ */ jsx3(Text3, { bold: true, children: "Select an instance
|
|
1953
|
-
/* @__PURE__ */ jsx3(Select, { options, onChange:
|
|
2494
|
+
/* @__PURE__ */ jsx3(Box2, { marginBottom: 1, children: /* @__PURE__ */ jsx3(Text3, { bold: true, children: "Select an instance:" }) }),
|
|
2495
|
+
/* @__PURE__ */ jsx3(Select, { options, onChange: setSelectedInstance })
|
|
1954
2496
|
] });
|
|
1955
2497
|
}
|
|
1956
2498
|
|
|
@@ -1973,38 +2515,66 @@ async function launchInteractiveMenu(deps) {
|
|
|
1973
2515
|
return { ok: true, action: "empty" };
|
|
1974
2516
|
}
|
|
1975
2517
|
let selectedName;
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
2518
|
+
let selectedAction;
|
|
2519
|
+
const selectionPromise = new Promise((resolve2) => {
|
|
2520
|
+
const { waitUntilExit } = deps.renderMenu(
|
|
2521
|
+
listResult.instances,
|
|
2522
|
+
(action2, name2) => {
|
|
2523
|
+
selectedAction = action2;
|
|
2524
|
+
selectedName = name2;
|
|
2525
|
+
resolve2({ action: action2, name: name2 });
|
|
2526
|
+
}
|
|
2527
|
+
);
|
|
1981
2528
|
void waitUntilExit().then(() => {
|
|
1982
|
-
if (!selectedName) {
|
|
1983
|
-
|
|
2529
|
+
if (!selectedName || !selectedAction) {
|
|
2530
|
+
resolve2({ action: "attach", name: "" });
|
|
1984
2531
|
}
|
|
1985
2532
|
});
|
|
1986
2533
|
});
|
|
1987
|
-
const name = await selectionPromise;
|
|
2534
|
+
const { action, name } = await selectionPromise;
|
|
1988
2535
|
if (!name) {
|
|
1989
2536
|
return { ok: true, action: "empty" };
|
|
1990
2537
|
}
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
ok: false,
|
|
1996
|
-
|
|
1997
|
-
}
|
|
2538
|
+
switch (action) {
|
|
2539
|
+
case "attach": {
|
|
2540
|
+
const attachDeps = deps.createAttachDeps();
|
|
2541
|
+
const attachResult = await deps.attachInstance(name, attachDeps);
|
|
2542
|
+
if (!attachResult.ok) return { ok: false, error: attachResult.error };
|
|
2543
|
+
return { ok: true, action: "attached", instanceName: name };
|
|
2544
|
+
}
|
|
2545
|
+
case "rebuild": {
|
|
2546
|
+
const rebuildDeps = deps.createRebuildDeps();
|
|
2547
|
+
const rebuildResult = await deps.rebuildInstance(name, rebuildDeps, { force: true });
|
|
2548
|
+
if (!rebuildResult.ok) return { ok: false, error: rebuildResult.error };
|
|
2549
|
+
return { ok: true, action: "rebuilt", instanceName: name };
|
|
2550
|
+
}
|
|
2551
|
+
case "purpose": {
|
|
2552
|
+
const instance = listResult.instances.find((i) => i.name === name);
|
|
2553
|
+
if (instance) {
|
|
2554
|
+
console.log(`
|
|
2555
|
+
Purpose for ${name}:`);
|
|
2556
|
+
console.log(instance.purpose || "No purpose set.");
|
|
2557
|
+
}
|
|
2558
|
+
return { ok: true, action: "purpose-shown", instanceName: name };
|
|
2559
|
+
}
|
|
2560
|
+
case "remove": {
|
|
2561
|
+
const removeDeps = deps.createRemoveDeps();
|
|
2562
|
+
const removeResult = await deps.removeInstance(name, removeDeps, false);
|
|
2563
|
+
if (!removeResult.ok) return { ok: false, error: removeResult.error };
|
|
2564
|
+
return { ok: true, action: "removed", instanceName: name };
|
|
2565
|
+
}
|
|
1998
2566
|
}
|
|
1999
|
-
return { ok: true, action: "attached", instanceName: name };
|
|
2000
2567
|
}
|
|
2001
2568
|
|
|
2002
2569
|
// src/cli.ts
|
|
2003
|
-
var
|
|
2570
|
+
var __dirname = dirname3(fileURLToPath2(import.meta.url));
|
|
2571
|
+
var isLinked = existsSync(resolve(__dirname, "..", "..", "..", "pnpm-workspace.yaml"));
|
|
2572
|
+
var version = package_default.version + (isLinked ? "+local" : "");
|
|
2004
2573
|
program.name("agent-env").description("CLI for creating isolated, AI-ready development environments").version(version);
|
|
2005
2574
|
program.addCommand(createCommand);
|
|
2006
2575
|
program.addCommand(listCommand);
|
|
2007
2576
|
program.addCommand(attachCommand);
|
|
2577
|
+
program.addCommand(rebuildCommand);
|
|
2008
2578
|
program.addCommand(removeCommand);
|
|
2009
2579
|
program.addCommand(purposeCommand);
|
|
2010
2580
|
program.addCommand(completionCommand);
|
|
@@ -2016,10 +2586,14 @@ program.action(async () => {
|
|
|
2016
2586
|
const result = await launchInteractiveMenu({
|
|
2017
2587
|
listInstances,
|
|
2018
2588
|
attachInstance,
|
|
2589
|
+
rebuildInstance,
|
|
2590
|
+
removeInstance,
|
|
2019
2591
|
createAttachDeps: createAttachDefaultDeps,
|
|
2020
|
-
|
|
2592
|
+
createRebuildDeps: createRebuildDefaultDeps,
|
|
2593
|
+
createRemoveDeps: createRemoveDefaultDeps,
|
|
2594
|
+
renderMenu: (instances, onAction) => {
|
|
2021
2595
|
const { waitUntilExit } = render2(
|
|
2022
|
-
|
|
2596
|
+
React3.createElement(InteractiveMenu, { instances, onAction })
|
|
2023
2597
|
);
|
|
2024
2598
|
return { waitUntilExit };
|
|
2025
2599
|
}
|
|
@@ -2028,6 +2602,10 @@ program.action(async () => {
|
|
|
2028
2602
|
const { code, message, suggestion } = result.error;
|
|
2029
2603
|
console.error(formatError(createError(code, message, suggestion)));
|
|
2030
2604
|
process.exitCode = 1;
|
|
2605
|
+
} else if (result.action === "rebuilt") {
|
|
2606
|
+
console.log(`\x1B[32m\u2713\x1B[0m Instance '${result.instanceName}' rebuilt successfully`);
|
|
2607
|
+
} else if (result.action === "removed") {
|
|
2608
|
+
console.log(`\x1B[32m\u2713\x1B[0m Instance '${result.instanceName}' removed`);
|
|
2031
2609
|
}
|
|
2032
2610
|
});
|
|
2033
2611
|
program.parse();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zookanalytics/agent-env",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "CLI for creating isolated, AI-ready development environments",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -33,6 +33,7 @@
|
|
|
33
33
|
"commander": "^14.0.2",
|
|
34
34
|
"execa": "^9.6.1",
|
|
35
35
|
"ink": "^6.6.0",
|
|
36
|
+
"jsonc-parser": "^3.3.1",
|
|
36
37
|
"react": "^19.2.3",
|
|
37
38
|
"timeago.js": "^4.0.2"
|
|
38
39
|
},
|