@zookanalytics/agent-env 0.1.3 → 0.3.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.
@@ -1,30 +1,4 @@
1
1
  {
2
- "build": {
3
- "dockerfile": "Dockerfile",
4
- "context": "."
5
- },
6
- "remoteUser": "node",
7
- "containerUser": "node",
8
- "initializeCommand": "bash .devcontainer/init-host.sh",
9
- "mounts": [
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"
13
- ],
14
- "containerEnv": {
15
- "SSH_AUTH_SOCK": "/run/host-services/ssh-auth.sock"
16
- },
17
- "features": {
18
- "ghcr.io/devcontainers/features/git:1": {},
19
- "ghcr.io/devcontainers/features/git-lfs:1": {}
20
- },
21
- "postCreateCommand": "bash .devcontainer/post-create.sh",
22
- "postStartCommand": "tmux new-session -d -s main 2>/dev/null || true",
23
- "customizations": {
24
- "vscode": {
25
- "settings": {
26
- "terminal.integrated.defaultProfile.linux": "zsh"
27
- }
28
- }
29
- }
2
+ "image": "ghcr.io/zookanalytics/bmad-orchestrator/devcontainer:latest",
3
+ "initializeCommand": "bash .agent-env/init-host.sh"
30
4
  }
@@ -1,25 +1,33 @@
1
1
  #!/usr/bin/env bash
2
2
  # init-host.sh - Runs on the HOST before container creation (initializeCommand)
3
- # Ensures mount sources exist to prevent devcontainer up failures
3
+ # Ensures mount sources exist to prevent devcontainer up failures.
4
+ # The .gitconfig and SSH socket mounts are provided by the image LABEL metadata.
4
5
 
5
6
  set -euo pipefail
6
7
 
7
- CLAUDE_DIR="$HOME/.claude"
8
8
  GITCONFIG="$HOME/.gitconfig"
9
9
  SSH_SOCKET="/run/host-services/ssh-auth.sock"
10
10
 
11
- # Ensure ~/.claude directory exists (mounted read-only into container)
12
- if [ ! -d "$CLAUDE_DIR" ]; then
13
- echo "agent-env: Creating $CLAUDE_DIR (mount source)"
14
- mkdir -p "$CLAUDE_DIR"
15
- fi
16
-
17
11
  # Ensure ~/.gitconfig exists (mounted read-only into container)
18
12
  if [ ! -f "$GITCONFIG" ]; then
19
13
  echo "agent-env: Creating $GITCONFIG (mount source)"
20
14
  touch "$GITCONFIG"
21
15
  fi
22
16
 
17
+ # Stage only SSH public keys for container mount (never expose private keys)
18
+ SSH_PUB_DIR="$HOME/.agent-env/ssh-pub-keys"
19
+ mkdir -p "$SSH_PUB_DIR"
20
+ rm -f "$SSH_PUB_DIR"/*.pub 2>/dev/null || true
21
+ if ls "$HOME/.ssh/"*.pub &>/dev/null; then
22
+ cp -p "$HOME/.ssh/"*.pub "$SSH_PUB_DIR/"
23
+ echo "agent-env: Staged SSH public keys:"
24
+ for f in "$SSH_PUB_DIR"/*.pub; do
25
+ echo " - $(basename "$f")"
26
+ done
27
+ else
28
+ echo "agent-env: Warning: No SSH public keys found in ~/.ssh. SSH access will require manual setup."
29
+ fi
30
+
23
31
  # Verify SSH agent socket exists (provided by Docker Desktop / OrbStack on macOS)
24
32
  if [ ! -S "$SSH_SOCKET" ]; then
25
33
  echo "agent-env: Warning: SSH agent socket not found at $SSH_SOCKET"
package/dist/cli.js CHANGED
@@ -42,7 +42,7 @@ import React3 from "react";
42
42
  // package.json
43
43
  var package_default = {
44
44
  name: "@zookanalytics/agent-env",
45
- version: "0.1.3",
45
+ version: "0.3.0",
46
46
  description: "CLI for creating isolated, AI-ready development environments",
47
47
  type: "module",
48
48
  bin: {
@@ -85,6 +85,7 @@ var package_default = {
85
85
  commander: "^14.0.2",
86
86
  execa: "^9.6.1",
87
87
  ink: "^6.6.0",
88
+ "jsonc-parser": "^3.3.1",
88
89
  react: "^19.2.3",
89
90
  "timeago.js": "^4.0.2"
90
91
  },
@@ -104,13 +105,75 @@ import { Command } from "commander";
104
105
  // src/lib/attach-instance.ts
105
106
  import { appendFile as appendFile3, mkdir as mkdir5, readdir as readdir4, readFile as readFile4, rename as rename3, stat as stat4, writeFile as writeFile4 } from "fs/promises";
106
107
  import { homedir as homedir3 } from "os";
108
+ import { join as join5 } from "path";
107
109
 
108
110
  // src/lib/container.ts
109
- var DEVCONTAINER_UP_TIMEOUT = 12e4;
111
+ var DEVCONTAINER_UP_TIMEOUT = 3e5;
112
+ var DEVCONTAINER_UP_NO_CACHE_TIMEOUT = 3e5;
113
+ var DOCKER_PULL_TIMEOUT = 3e5;
110
114
  var DOCKER_INSPECT_TIMEOUT = 1e4;
111
115
  var DOCKER_INFO_TIMEOUT = 5e3;
112
116
  var DOCKER_STOP_TIMEOUT = 3e4;
113
117
  var DOCKER_RM_TIMEOUT = 1e4;
118
+ function parseDevcontainerOutput(stdout) {
119
+ try {
120
+ return JSON.parse(stdout);
121
+ } catch {
122
+ const lines = stdout.trim().split("\n");
123
+ for (let i = lines.length - 1; i >= 0; i--) {
124
+ try {
125
+ return JSON.parse(lines[i]);
126
+ } catch {
127
+ }
128
+ }
129
+ }
130
+ return null;
131
+ }
132
+ function extractLifecycleOutput(stdout) {
133
+ if (!stdout) return "";
134
+ const lines = stdout.trim().split("\n");
135
+ const nonJsonLines = [];
136
+ for (const line of lines) {
137
+ const trimmed = line.trim();
138
+ if (!trimmed) continue;
139
+ try {
140
+ JSON.parse(trimmed);
141
+ } catch {
142
+ nonJsonLines.push(line);
143
+ }
144
+ }
145
+ return nonJsonLines.join("\n");
146
+ }
147
+ var MAX_OUTPUT_LINES = 100;
148
+ function truncateOutput(output, maxLines) {
149
+ const outputLines = output.trimEnd().split("\n");
150
+ if (outputLines.length > maxLines) {
151
+ return [
152
+ `[... ${outputLines.length - maxLines} earlier lifecycle output lines omitted]`,
153
+ outputLines.slice(-maxLines).join("\n")
154
+ ];
155
+ }
156
+ return [output];
157
+ }
158
+ function buildDevcontainerErrorDetails(stdout, stderr, parsedOutput) {
159
+ const parts = [];
160
+ if (parsedOutput?.message) parts.push(parsedOutput.message);
161
+ if (parsedOutput?.description) parts.push(parsedOutput.description);
162
+ const lifecycleOutput = extractLifecycleOutput(stdout);
163
+ if (lifecycleOutput) {
164
+ parts.push(...truncateOutput(lifecycleOutput, MAX_OUTPUT_LINES));
165
+ }
166
+ if (stderr) {
167
+ const stderrLines = stderr.trimEnd().split("\n");
168
+ if (stderrLines.length > MAX_OUTPUT_LINES) {
169
+ parts.push(`[... ${stderrLines.length - MAX_OUTPUT_LINES} earlier stderr lines omitted]`);
170
+ parts.push(stderrLines.slice(-MAX_OUTPUT_LINES).join("\n"));
171
+ } else {
172
+ parts.push(stderr);
173
+ }
174
+ }
175
+ return parts.join("\n ") || "No error details available";
176
+ }
114
177
  function createContainerLifecycle(executor = createExecutor()) {
115
178
  async function isDockerAvailable() {
116
179
  const result = await executor("docker", ["info"], { timeout: DOCKER_INFO_TIMEOUT });
@@ -125,7 +188,8 @@ function createContainerLifecycle(executor = createExecutor()) {
125
188
  return {
126
189
  ok: true,
127
190
  status: "not-found",
128
- containerId: null
191
+ containerId: null,
192
+ ports: {}
129
193
  };
130
194
  }
131
195
  return {
@@ -144,17 +208,28 @@ function createContainerLifecycle(executor = createExecutor()) {
144
208
  return {
145
209
  ok: true,
146
210
  status: "not-found",
147
- containerId: null
211
+ containerId: null,
212
+ ports: {}
148
213
  };
149
214
  }
150
215
  const container = inspectData[0];
151
216
  const containerId = container.Id ?? null;
152
217
  const dockerStatus = container.State?.Status ?? "unknown";
153
218
  const status = dockerStatus === "running" ? "running" : "stopped";
219
+ const ports = {};
220
+ const dockerPorts = container.NetworkSettings?.Ports;
221
+ if (dockerPorts) {
222
+ for (const [key, mappings] of Object.entries(dockerPorts)) {
223
+ if (mappings && mappings.length > 0) {
224
+ ports[key] = mappings[0].HostPort;
225
+ }
226
+ }
227
+ }
154
228
  return {
155
229
  ok: true,
156
230
  status,
157
- containerId
231
+ containerId,
232
+ ports
158
233
  };
159
234
  } catch (e) {
160
235
  const errorMessage = e instanceof Error ? e.message : String(e);
@@ -199,7 +274,7 @@ function createContainerLifecycle(executor = createExecutor()) {
199
274
  const name = result.stdout.trim().split("\n")[0]?.trim();
200
275
  return name || null;
201
276
  }
202
- async function devcontainerUp(workspacePath, containerName) {
277
+ async function devcontainerUp(workspacePath, containerName, options) {
203
278
  const dockerOk = await isDockerAvailable();
204
279
  if (!dockerOk) {
205
280
  return {
@@ -213,29 +288,28 @@ function createContainerLifecycle(executor = createExecutor()) {
213
288
  }
214
289
  };
215
290
  }
216
- const result = await executor("devcontainer", ["up", "--workspace-folder", workspacePath], {
217
- timeout: DEVCONTAINER_UP_TIMEOUT
291
+ const buildNoCache = options?.buildNoCache === true;
292
+ const remoteEnvArgs = Object.entries(options?.remoteEnv ?? {}).flatMap(([key, value]) => [
293
+ "--remote-env",
294
+ `${key}=${value}`
295
+ ]);
296
+ const configArgs = options?.configPath ? ["--config", options.configPath] : [];
297
+ const args = [
298
+ "up",
299
+ "--workspace-folder",
300
+ workspacePath,
301
+ ...configArgs,
302
+ "--log-level",
303
+ "debug",
304
+ ...remoteEnvArgs,
305
+ ...buildNoCache ? ["--build-no-cache"] : []
306
+ ];
307
+ const result = await executor("devcontainer", args, {
308
+ timeout: buildNoCache ? DEVCONTAINER_UP_NO_CACHE_TIMEOUT : DEVCONTAINER_UP_TIMEOUT
218
309
  });
219
- let parsedOutput = null;
220
- try {
221
- parsedOutput = JSON.parse(result.stdout);
222
- } catch {
223
- const lines = result.stdout.trim().split("\n");
224
- for (let i = lines.length - 1; i >= 0; i--) {
225
- try {
226
- parsedOutput = JSON.parse(lines[i]);
227
- break;
228
- } catch {
229
- }
230
- }
231
- }
310
+ const parsedOutput = parseDevcontainerOutput(result.stdout);
232
311
  if (!result.ok) {
233
- const parts = [];
234
- if (parsedOutput?.message) parts.push(parsedOutput.message);
235
- if (parsedOutput?.description) parts.push(parsedOutput.description);
236
- if (result.stderr) parts.push(result.stderr);
237
- if (parts.length === 0 && result.stdout) parts.push(result.stdout.slice(0, 1e3));
238
- const details = parts.join("\n ") || "No error details available";
312
+ const details = buildDevcontainerErrorDetails(result.stdout, result.stderr, parsedOutput);
239
313
  const combined = `${result.stderr} ${result.stdout}`;
240
314
  const isNameConflict = combined.includes("is already in use") || combined.includes("name is already in use") || combined.includes("Conflict.") || combined.includes("conflict");
241
315
  return {
@@ -254,7 +328,8 @@ function createContainerLifecycle(executor = createExecutor()) {
254
328
  return {
255
329
  ok: true,
256
330
  status: "running",
257
- containerId
331
+ containerId,
332
+ ports: {}
258
333
  };
259
334
  }
260
335
  async function containerStop(containerName) {
@@ -294,12 +369,29 @@ function createContainerLifecycle(executor = createExecutor()) {
294
369
  }
295
370
  };
296
371
  }
372
+ async function dockerPull(image) {
373
+ const result = await executor("docker", ["pull", image], {
374
+ timeout: DOCKER_PULL_TIMEOUT
375
+ });
376
+ if (result.ok) {
377
+ return { ok: true };
378
+ }
379
+ return {
380
+ ok: false,
381
+ error: {
382
+ code: "IMAGE_PULL_FAILED",
383
+ message: `Failed to pull '${image}': ${result.stderr}`,
384
+ suggestion: "Check network connectivity and image name. Use --no-pull to skip pulling and use cached images."
385
+ }
386
+ };
387
+ }
297
388
  return {
298
389
  isDockerAvailable,
299
390
  containerStatus,
300
391
  getContainerNameById,
301
392
  findContainerByWorkspaceLabel,
302
393
  devcontainerUp,
394
+ dockerPull,
303
395
  containerStop,
304
396
  containerRemove
305
397
  };
@@ -318,12 +410,32 @@ import {
318
410
  writeFile as writeFile3
319
411
  } from "fs/promises";
320
412
  import { homedir as homedir2 } from "os";
321
- import { dirname as dirname2 } from "path";
413
+ import { dirname as dirname2, join as join4 } from "path";
322
414
 
323
415
  // src/lib/devcontainer.ts
416
+ import { parse as parseJsonc } from "jsonc-parser";
324
417
  import { access, cp, mkdir, readdir, readFile, stat, writeFile } from "fs/promises";
325
418
  import { dirname, join } from "path";
326
419
  import { fileURLToPath } from "url";
420
+
421
+ // src/lib/types.ts
422
+ var AGENT_ENV_DIR = ".agent-env";
423
+ var WORKSPACES_DIR = "workspaces";
424
+ var STATE_FILE = "state.json";
425
+ var STATE_FILE_TMP = "state.json.tmp";
426
+ var CONTAINER_PREFIX = "ae-";
427
+ function createFallbackState(workspaceName) {
428
+ return {
429
+ name: workspaceName,
430
+ repo: "unknown",
431
+ createdAt: "unknown",
432
+ lastAttached: "unknown",
433
+ purpose: null,
434
+ containerName: `${CONTAINER_PREFIX}${workspaceName}`
435
+ };
436
+ }
437
+
438
+ // src/lib/devcontainer.ts
327
439
  var defaultFsDeps = { access, cp, mkdir, readdir, readFile, stat, writeFile };
328
440
  var DEVCONTAINER_DIR = ".devcontainer";
329
441
  var DEVCONTAINER_JSON = "devcontainer.json";
@@ -364,7 +476,7 @@ async function copyBaselineConfig(workspacePath, deps = defaultFsDeps) {
364
476
  } catch {
365
477
  throw new Error(`Baseline config not found at ${baselinePath}. Package may be corrupted.`);
366
478
  }
367
- const targetDir = join(workspacePath, DEVCONTAINER_DIR);
479
+ const targetDir = join(workspacePath, AGENT_ENV_DIR);
368
480
  await deps.mkdir(targetDir, { recursive: true });
369
481
  await deps.cp(baselinePath, targetDir, { recursive: true });
370
482
  }
@@ -377,34 +489,79 @@ async function patchContainerName(workspacePath, containerName, deps = defaultFs
377
489
  config.runArgs = [...filtered, `--name=${containerName}`];
378
490
  await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
379
491
  }
380
- async function listBaselineFiles(deps = defaultFsDeps) {
381
- const baselinePath = getBaselineConfigPath();
382
- const entries = await deps.readdir(baselinePath);
383
- return entries.sort();
492
+ async function resolveDockerfilePath(workspacePath, deps) {
493
+ const candidates = [
494
+ join(workspacePath, DEVCONTAINER_DIR, DEVCONTAINER_JSON),
495
+ join(workspacePath, DEVCONTAINER_JSON),
496
+ join(workspacePath, DOT_DEVCONTAINER_JSON)
497
+ ];
498
+ let configPath = null;
499
+ for (const candidate of candidates) {
500
+ try {
501
+ await deps.stat(candidate);
502
+ configPath = candidate;
503
+ break;
504
+ } catch {
505
+ }
506
+ }
507
+ if (!configPath) {
508
+ return null;
509
+ }
510
+ const content = await deps.readFile(configPath, "utf-8");
511
+ const errors = [];
512
+ const config = parseJsonc(content, errors, { allowTrailingComma: true });
513
+ if (errors.length > 0) {
514
+ throw new Error(`Failed to parse devcontainer config at ${configPath}: Invalid JSONC`);
515
+ }
516
+ const configDir = dirname(configPath);
517
+ if (config?.build?.dockerfile) {
518
+ return join(configDir, config.build.dockerfile);
519
+ }
520
+ if (config?.dockerfile) {
521
+ return join(configDir, config.dockerfile);
522
+ }
523
+ try {
524
+ await deps.stat(join(configDir, "Dockerfile"));
525
+ return join(configDir, "Dockerfile");
526
+ } catch {
527
+ return null;
528
+ }
529
+ }
530
+ function parseDockerfileImages(content, logger) {
531
+ const fromRegex = /^\s*FROM\s+(?:--\S+\s+)*(\S+)(?:\s+[Aa][Ss]\s+(\S+))?/i;
532
+ const stageNames = /* @__PURE__ */ new Set();
533
+ const images = /* @__PURE__ */ new Set();
534
+ for (const line of content.split("\n")) {
535
+ if (line.trim().startsWith("#")) continue;
536
+ const match = fromRegex.exec(line);
537
+ if (match?.[2]) {
538
+ stageNames.add(match[2].toLowerCase());
539
+ }
540
+ }
541
+ for (const line of content.split("\n")) {
542
+ const trimmed = line.trim();
543
+ if (trimmed.startsWith("#")) continue;
544
+ const match = fromRegex.exec(line);
545
+ if (!match) continue;
546
+ const image = match[1];
547
+ if (image.includes("$")) {
548
+ logger?.warn(`Skipping parameterized FROM: ${image}`);
549
+ continue;
550
+ }
551
+ if (image.toLowerCase() === "scratch") {
552
+ continue;
553
+ }
554
+ if (stageNames.has(image.toLowerCase())) {
555
+ continue;
556
+ }
557
+ images.add(image);
558
+ }
559
+ return [...images];
384
560
  }
385
561
 
386
562
  // src/lib/state.ts
387
563
  import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
388
564
  import { join as join2 } from "path";
389
-
390
- // src/lib/types.ts
391
- var AGENT_ENV_DIR = ".agent-env";
392
- var WORKSPACES_DIR = "workspaces";
393
- var STATE_FILE = "state.json";
394
- var STATE_FILE_TMP = "state.json.tmp";
395
- var CONTAINER_PREFIX = "ae-";
396
- function createFallbackState(workspaceName) {
397
- return {
398
- name: workspaceName,
399
- repo: "unknown",
400
- createdAt: "unknown",
401
- lastAttached: "unknown",
402
- purpose: null,
403
- containerName: `${CONTAINER_PREFIX}${workspaceName}`
404
- };
405
- }
406
-
407
- // src/lib/state.ts
408
565
  var defaultStateFsDeps = { readFile: readFile2, writeFile: writeFile2, rename, mkdir: mkdir2, appendFile };
409
566
  async function readState(wsPath, deps = defaultStateFsDeps) {
410
567
  try {
@@ -696,7 +853,7 @@ async function createInstance(instanceName, repoUrl, deps) {
696
853
  };
697
854
  }
698
855
  try {
699
- await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps);
856
+ await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps, AGENT_ENV_DIR);
700
857
  } catch (err) {
701
858
  await safeRollback(wsPath.root, deps.rm, deps.logger);
702
859
  return {
@@ -722,17 +879,13 @@ async function createInstance(instanceName, repoUrl, deps) {
722
879
  }
723
880
  };
724
881
  }
725
- const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName);
882
+ const baselineConfigPath = configSource === "baseline" ? join4(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
883
+ const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
884
+ remoteEnv: { AGENT_INSTANCE: wsPath.name },
885
+ configPath: baselineConfigPath
886
+ });
726
887
  if (!containerResult.ok) {
727
- deps.logger?.warn(`Rolling back workspace at ${wsPath.root} due to container startup failure.`);
728
- await safeRollback(wsPath.root, deps.rm, deps.logger);
729
- return {
730
- ok: false,
731
- error: containerResult.error ?? {
732
- code: "CONTAINER_ERROR",
733
- message: "Container startup failed for unknown reason."
734
- }
735
- };
888
+ return rollbackContainerFailure(containerName, wsPath, containerResult, deps);
736
889
  }
737
890
  let actualContainerName = containerName;
738
891
  if (containerResult.containerId) {
@@ -757,6 +910,58 @@ async function createInstance(instanceName, repoUrl, deps) {
757
910
  containerName: actualContainerName
758
911
  };
759
912
  }
913
+ async function rollbackContainerFailure(containerName, wsPath, containerResult, deps) {
914
+ deps.logger?.warn(`Rolling back workspace at ${wsPath.root} due to container startup failure.`);
915
+ const dockerLogs = await safeCaptureDockerLogs(containerName, wsPath.root, deps);
916
+ await safeContainerCleanup(containerName, wsPath.root, deps.container, deps.logger);
917
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
918
+ const baseError = containerResult.error ?? {
919
+ code: "CONTAINER_ERROR",
920
+ message: "Container startup failed for unknown reason."
921
+ };
922
+ const error = dockerLogs ? { ...baseError, message: `${baseError.message}
923
+ --- docker logs ---
924
+ ${dockerLogs}` } : baseError;
925
+ return { ok: false, error };
926
+ }
927
+ var DOCKER_LOGS_TIMEOUT = 5e3;
928
+ async function safeCaptureDockerLogs(containerName, workspacePath, deps) {
929
+ const candidates = [containerName];
930
+ try {
931
+ const labelMatch = await deps.container.findContainerByWorkspaceLabel(workspacePath);
932
+ if (labelMatch && labelMatch !== containerName) candidates.push(labelMatch);
933
+ } catch {
934
+ }
935
+ for (const name of candidates) {
936
+ try {
937
+ const result = await deps.executor("docker", ["logs", "--tail", "100", name], {
938
+ timeout: DOCKER_LOGS_TIMEOUT
939
+ });
940
+ if (result.ok) {
941
+ const combined = [result.stdout.trim(), result.stderr.trim()].filter(Boolean).join("\n--- stderr ---\n");
942
+ if (combined) return combined;
943
+ }
944
+ } catch {
945
+ }
946
+ }
947
+ return null;
948
+ }
949
+ async function safeContainerCleanup(containerName, workspacePath, container, logger) {
950
+ const candidates = /* @__PURE__ */ new Set([containerName]);
951
+ try {
952
+ const labelMatch = await container.findContainerByWorkspaceLabel(workspacePath);
953
+ if (labelMatch) candidates.add(labelMatch);
954
+ } catch {
955
+ }
956
+ for (const name of candidates) {
957
+ try {
958
+ await container.containerStop(name);
959
+ await container.containerRemove(name);
960
+ } catch {
961
+ logger?.warn(`Warning: Failed to clean up container '${name}'`);
962
+ }
963
+ }
964
+ }
760
965
  async function safeRollback(workspacePath, rmFn, logger) {
761
966
  try {
762
967
  await rmFn(workspacePath, { recursive: true, force: true });
@@ -837,7 +1042,12 @@ async function attachInstance(instanceName, deps, onContainerStarting, onAttachi
837
1042
  }
838
1043
  if (statusResult.status === "stopped" || statusResult.status === "not-found") {
839
1044
  onContainerStarting?.();
840
- const startResult = await deps.container.devcontainerUp(wsPath.root, containerName);
1045
+ const configSource = state.configSource ?? "baseline";
1046
+ const baselineConfigPath = configSource === "baseline" ? join5(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1047
+ const startResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
1048
+ remoteEnv: { AGENT_INSTANCE: wsPath.name },
1049
+ configPath: baselineConfigPath
1050
+ });
841
1051
  if (!startResult.ok) {
842
1052
  return {
843
1053
  ok: false,
@@ -1182,6 +1392,13 @@ function formatPurpose(purpose) {
1182
1392
  }
1183
1393
  return purpose;
1184
1394
  }
1395
+ function formatSSH(ssh) {
1396
+ if (!ssh) return "-";
1397
+ if (ssh.length > 40) {
1398
+ return ssh.slice(0, 37) + "...";
1399
+ }
1400
+ return ssh;
1401
+ }
1185
1402
  function InstanceList({
1186
1403
  instances,
1187
1404
  dockerAvailable
@@ -1206,12 +1423,14 @@ function InstanceList({
1206
1423
  const statusWidth = Math.max(6, ...augmentedInstances.map((i) => statusLabel(i.status, dockerAvailable).length)) + 2;
1207
1424
  const gitWidth = Math.max(3, ...augmentedInstances.map((i) => i.indicatorText.length)) + 2;
1208
1425
  const lastAttachedWidth = Math.max(13, ...augmentedInstances.map((i) => formatLastAttached(i.lastAttached).length)) + 2;
1426
+ const sshWidth = Math.max(4, ...augmentedInstances.map((i) => formatSSH(i.sshConnection).length)) + 2;
1209
1427
  return /* @__PURE__ */ jsxs2(Box, { flexDirection: "column", children: [
1210
1428
  /* @__PURE__ */ jsxs2(Box, { children: [
1211
1429
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("NAME", nameWidth) }),
1212
1430
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("STATUS", statusWidth) }),
1213
1431
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("GIT", gitWidth) }),
1214
1432
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("LAST ATTACHED", lastAttachedWidth) }),
1433
+ /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("SSH", sshWidth) }),
1215
1434
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: "PURPOSE" })
1216
1435
  ] }),
1217
1436
  augmentedInstances.map((instance) => /* @__PURE__ */ jsxs2(Box, { children: [
@@ -1222,6 +1441,7 @@ function InstanceList({
1222
1441
  ind.symbol
1223
1442
  ] }, idx)) }),
1224
1443
  /* @__PURE__ */ jsx2(Text2, { children: pad(formatLastAttached(instance.lastAttached), lastAttachedWidth) }),
1444
+ /* @__PURE__ */ jsx2(Text2, { color: "cyan", children: pad(formatSSH(instance.sshConnection), sshWidth) }),
1225
1445
  /* @__PURE__ */ jsx2(Text2, { color: "gray", children: formatPurpose(instance.purpose) })
1226
1446
  ] }, instance.name)),
1227
1447
  !dockerAvailable && /* @__PURE__ */ jsx2(Box, { marginTop: 1, children: /* @__PURE__ */ jsx2(Text2, { color: "yellow", children: "\u26A0 Docker is not available. Container status cannot be determined." }) })
@@ -1394,12 +1614,23 @@ async function listInstances(deps) {
1394
1614
  } else {
1395
1615
  status = containerResult.status;
1396
1616
  }
1617
+ let sshConnection = null;
1618
+ if (status === "running" && containerResult && containerResult.ok) {
1619
+ const sshPort = containerResult.ports["22/tcp"];
1620
+ if (sshPort) {
1621
+ sshConnection = `node@${state.containerName}.orb.local`;
1622
+ if (sshPort !== "22") {
1623
+ sshConnection += ` (localhost:${sshPort})`;
1624
+ }
1625
+ }
1626
+ }
1397
1627
  return {
1398
1628
  name: wsName,
1399
1629
  status,
1400
1630
  lastAttached: state.lastAttached !== "unknown" ? state.lastAttached : null,
1401
1631
  purpose: state.purpose,
1402
- gitState
1632
+ gitState,
1633
+ sshConnection
1403
1634
  };
1404
1635
  });
1405
1636
  const instances = await Promise.all(instancePromises);
@@ -1445,7 +1676,8 @@ var listCommand = new Command4("list").alias("ps").description("List all instanc
1445
1676
  status: i.status,
1446
1677
  lastAttached: i.lastAttached,
1447
1678
  purpose: i.purpose,
1448
- gitState: i.gitState
1679
+ gitState: i.gitState,
1680
+ sshConnection: i.sshConnection
1449
1681
  })),
1450
1682
  error: null
1451
1683
  };
@@ -1567,7 +1799,7 @@ import {
1567
1799
  appendFile as appendFile5
1568
1800
  } from "fs/promises";
1569
1801
  import { homedir as homedir5 } from "os";
1570
- import { join as join4 } from "path";
1802
+ import { join as join6 } from "path";
1571
1803
  function createRebuildDefaultDeps() {
1572
1804
  const executor = createExecutor();
1573
1805
  return {
@@ -1582,30 +1814,15 @@ function createRebuildDefaultDeps() {
1582
1814
  };
1583
1815
  }
1584
1816
  async function refreshConfig(wsRoot, containerName, configSource, deps) {
1585
- const devcontainerDir = join4(wsRoot, ".devcontainer");
1586
- const tempDevcontainerDir = join4(wsRoot, ".devcontainer.new");
1587
1817
  if (configSource === "baseline") {
1818
+ const agentEnvDir = join6(wsRoot, AGENT_ENV_DIR);
1588
1819
  try {
1589
- try {
1590
- const currentFiles = await deps.devcontainerFsDeps.readdir(devcontainerDir);
1591
- const baselineFiles = await listBaselineFiles(deps.devcontainerFsDeps);
1592
- const baselineSet = new Set(baselineFiles);
1593
- const extras = currentFiles.filter((f) => !baselineSet.has(f));
1594
- if (extras.length > 0) {
1595
- deps.logger?.warn(`Extra files in .devcontainer/ will be deleted: ${extras.join(", ")}`);
1596
- }
1597
- } catch {
1598
- }
1599
- await deps.rm(tempDevcontainerDir, { recursive: true, force: true });
1600
- await deps.devcontainerFsDeps.mkdir(tempDevcontainerDir, { recursive: true });
1601
- await deps.devcontainerFsDeps.cp(getBaselineConfigPath(), tempDevcontainerDir, {
1820
+ await deps.devcontainerFsDeps.mkdir(agentEnvDir, { recursive: true });
1821
+ await deps.devcontainerFsDeps.cp(getBaselineConfigPath(), agentEnvDir, {
1602
1822
  recursive: true
1603
1823
  });
1604
- await patchContainerName(wsRoot, containerName, deps.devcontainerFsDeps, ".devcontainer.new");
1605
- await deps.rm(devcontainerDir, { recursive: true, force: true });
1606
- await deps.rename(tempDevcontainerDir, devcontainerDir);
1824
+ await patchContainerName(wsRoot, containerName, deps.devcontainerFsDeps, AGENT_ENV_DIR);
1607
1825
  } catch (err) {
1608
- await deps.rm(tempDevcontainerDir, { recursive: true, force: true });
1609
1826
  return {
1610
1827
  ok: false,
1611
1828
  error: {
@@ -1627,9 +1844,10 @@ async function refreshConfig(wsRoot, containerName, configSource, deps) {
1627
1844
  }
1628
1845
  };
1629
1846
  }
1847
+ const devcontainerDir = join6(wsRoot, ".devcontainer");
1630
1848
  const dirExists = await deps.devcontainerFsDeps.stat(devcontainerDir).catch(() => null);
1631
1849
  if (dirExists) {
1632
- const jsonExists = await deps.devcontainerFsDeps.stat(join4(devcontainerDir, "devcontainer.json")).catch(() => null);
1850
+ const jsonExists = await deps.devcontainerFsDeps.stat(join6(devcontainerDir, "devcontainer.json")).catch(() => null);
1633
1851
  if (!jsonExists) {
1634
1852
  return {
1635
1853
  ok: false,
@@ -1644,7 +1862,7 @@ async function refreshConfig(wsRoot, containerName, configSource, deps) {
1644
1862
  }
1645
1863
  return { ok: true };
1646
1864
  }
1647
- async function rebuildInstance(instanceName, deps, force = false, overrideConfigSource) {
1865
+ async function lookupWorkspace(instanceName, deps) {
1648
1866
  const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1649
1867
  if (!lookup.found) {
1650
1868
  if (lookup.reason === "ambiguous") {
@@ -1668,6 +1886,93 @@ async function rebuildInstance(instanceName, deps, force = false, overrideConfig
1668
1886
  }
1669
1887
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1670
1888
  const state = await readState(wsPath, deps.stateFsDeps);
1889
+ return { ok: true, wsPath, state };
1890
+ }
1891
+ async function executePullStep(wsRoot, pull, deps) {
1892
+ let dockerfilePath;
1893
+ try {
1894
+ dockerfilePath = await resolveDockerfilePath(wsRoot, deps.devcontainerFsDeps);
1895
+ } catch (err) {
1896
+ return {
1897
+ ok: false,
1898
+ error: {
1899
+ code: "CONFIG_PARSE_FAILED",
1900
+ message: err instanceof Error ? err.message : String(err),
1901
+ suggestion: "Check that your devcontainer.json is valid JSON or JSONC."
1902
+ }
1903
+ };
1904
+ }
1905
+ const hasDockerfile = dockerfilePath !== null;
1906
+ if (!pull) {
1907
+ return { ok: true, hasDockerfile };
1908
+ }
1909
+ if (dockerfilePath === null) {
1910
+ deps.logger?.info("No Dockerfile found \u2014 skipping image pull.");
1911
+ return { ok: true, hasDockerfile: false };
1912
+ }
1913
+ let dockerfileContent;
1914
+ try {
1915
+ dockerfileContent = await deps.devcontainerFsDeps.readFile(dockerfilePath, "utf-8");
1916
+ } catch {
1917
+ return {
1918
+ ok: false,
1919
+ error: {
1920
+ code: "DOCKERFILE_MISSING",
1921
+ message: `Dockerfile not found at ${dockerfilePath}`,
1922
+ suggestion: "Ensure the Dockerfile exists at the configured path, or use --no-pull to skip."
1923
+ }
1924
+ };
1925
+ }
1926
+ const images = parseDockerfileImages(dockerfileContent, deps.logger);
1927
+ if (images.length === 0) {
1928
+ deps.logger?.info("No pullable FROM images found.");
1929
+ return { ok: true, hasDockerfile };
1930
+ }
1931
+ const results = await Promise.allSettled(
1932
+ images.map(async (image) => {
1933
+ deps.logger?.info(`Pulling ${image}...`);
1934
+ const pullResult = await deps.container.dockerPull(image);
1935
+ if (!pullResult.ok) {
1936
+ throw pullResult.error;
1937
+ }
1938
+ deps.logger?.info(`Pulled ${image}`);
1939
+ })
1940
+ );
1941
+ const firstFailure = results.find((r) => r.status === "rejected");
1942
+ if (firstFailure) {
1943
+ return {
1944
+ ok: false,
1945
+ error: firstFailure.reason
1946
+ };
1947
+ }
1948
+ return { ok: true, hasDockerfile };
1949
+ }
1950
+ async function teardownContainer(containerName, container, statusResult) {
1951
+ if (!statusResult.ok || statusResult.status === "not-found") {
1952
+ return { ok: true };
1953
+ }
1954
+ const stopResult = await container.containerStop(containerName);
1955
+ if (!stopResult.ok) {
1956
+ return { ok: false, error: stopResult.error };
1957
+ }
1958
+ const removeResult = await container.containerRemove(containerName);
1959
+ if (!removeResult.ok) {
1960
+ return { ok: false, error: removeResult.error };
1961
+ }
1962
+ return { ok: true };
1963
+ }
1964
+ async function rebuildInstance(instanceName, deps, options) {
1965
+ const {
1966
+ force = false,
1967
+ configSource: overrideConfigSource,
1968
+ pull = true,
1969
+ noCache = true
1970
+ } = options ?? {};
1971
+ const wsLookup = await lookupWorkspace(instanceName, deps);
1972
+ if (!wsLookup.ok) {
1973
+ return { ok: false, error: wsLookup.error };
1974
+ }
1975
+ const { wsPath, state } = wsLookup;
1671
1976
  const containerName = state.containerName;
1672
1977
  const dockerAvailable = await deps.container.isDockerAvailable();
1673
1978
  if (!dockerAvailable) {
@@ -1695,6 +2000,11 @@ async function rebuildInstance(instanceName, deps, force = false, overrideConfig
1695
2000
  if (!configResult.ok) {
1696
2001
  return { ok: false, error: configResult.error };
1697
2002
  }
2003
+ const pullStepResult = await executePullStep(wsPath.root, pull, deps);
2004
+ if (!pullStepResult.ok) {
2005
+ return { ok: false, error: pullStepResult.error };
2006
+ }
2007
+ const { hasDockerfile } = pullStepResult;
1698
2008
  const statusResult = await deps.container.containerStatus(containerName);
1699
2009
  const wasRunning = statusResult.ok && statusResult.status === "running";
1700
2010
  if (wasRunning && !force) {
@@ -1708,27 +2018,17 @@ async function rebuildInstance(instanceName, deps, force = false, overrideConfig
1708
2018
  wasRunning: true
1709
2019
  };
1710
2020
  }
1711
- if (statusResult.ok && statusResult.status !== "not-found") {
1712
- const stopResult = await deps.container.containerStop(containerName);
1713
- if (!stopResult.ok) {
1714
- return {
1715
- ok: false,
1716
- error: stopResult.error,
1717
- wasRunning
1718
- };
1719
- }
1720
- }
1721
- if (statusResult.ok && statusResult.status !== "not-found") {
1722
- const removeResult = await deps.container.containerRemove(containerName);
1723
- if (!removeResult.ok) {
1724
- return {
1725
- ok: false,
1726
- error: removeResult.error,
1727
- wasRunning
1728
- };
1729
- }
2021
+ const teardownResult = await teardownContainer(containerName, deps.container, statusResult);
2022
+ if (!teardownResult.ok) {
2023
+ return { ok: false, error: teardownResult.error, wasRunning };
1730
2024
  }
1731
- const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName);
2025
+ const buildNoCache = noCache && hasDockerfile;
2026
+ const baselineConfigPath = configSource === "baseline" ? join6(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
2027
+ const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
2028
+ buildNoCache,
2029
+ remoteEnv: { AGENT_INSTANCE: wsPath.name },
2030
+ configPath: baselineConfigPath
2031
+ });
1732
2032
  if (!containerResult.ok) {
1733
2033
  return {
1734
2034
  ok: false,
@@ -1778,41 +2078,48 @@ Any active sessions will be lost. Continue? (y/N) `,
1778
2078
  });
1779
2079
  });
1780
2080
  }
1781
- 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").action(async (name, options) => {
1782
- const deps = createRebuildDefaultDeps();
1783
- let confirmed = false;
1784
- if (!options.yes && !options.force && process.stdin.isTTY) {
1785
- confirmed = await promptForConfirmation(name);
1786
- if (!confirmed) {
1787
- console.log("Rebuild cancelled");
1788
- return;
2081
+ 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(
2082
+ async (name, options) => {
2083
+ const deps = createRebuildDefaultDeps();
2084
+ let confirmed = false;
2085
+ if (!options.yes && !options.force && process.stdin.isTTY) {
2086
+ confirmed = await promptForConfirmation(name);
2087
+ if (!confirmed) {
2088
+ console.log("Rebuild cancelled");
2089
+ return;
2090
+ }
1789
2091
  }
1790
- }
1791
- const force = options.force || options.yes || confirmed;
1792
- if (force) {
1793
- console.log(`Force-rebuilding instance '${name}'...`);
1794
- } else {
1795
- console.log(`Rebuilding instance '${name}'...`);
1796
- }
1797
- const result = await rebuildInstance(name, deps, force);
1798
- if (!result.ok) {
1799
- if (result.error.code === "CONTAINER_RUNNING") {
1800
- console.error("");
1801
- console.error(
1802
- chalk.yellow("Container is currently running.") + " Active sessions will be terminated during rebuild."
1803
- );
1804
- console.error("");
1805
- console.error(`Use ${chalk.bold("--force")} to rebuild anyway.`);
2092
+ const force = options.force || options.yes || confirmed;
2093
+ const rebuildOptions = {
2094
+ force,
2095
+ pull: options.pull,
2096
+ noCache: !options.useCache
2097
+ };
2098
+ if (force) {
2099
+ console.log(`Force-rebuilding instance '${name}'...`);
1806
2100
  } else {
1807
- const { code, message, suggestion } = result.error;
1808
- console.error(formatError(createError(code, message, suggestion)));
2101
+ console.log(`Rebuilding instance '${name}'...`);
1809
2102
  }
1810
- process.exit(1);
1811
- return;
2103
+ const result = await rebuildInstance(name, deps, rebuildOptions);
2104
+ if (!result.ok) {
2105
+ if (result.error.code === "CONTAINER_RUNNING") {
2106
+ console.error("");
2107
+ console.error(
2108
+ chalk.yellow("Container is currently running.") + " Active sessions will be terminated during rebuild."
2109
+ );
2110
+ console.error("");
2111
+ console.error(`Use ${chalk.bold("--force")} to rebuild anyway.`);
2112
+ } else {
2113
+ const { code, message, suggestion } = result.error;
2114
+ console.error(formatError(createError(code, message, suggestion)));
2115
+ }
2116
+ process.exit(1);
2117
+ return;
2118
+ }
2119
+ console.log(`\x1B[32m\u2713\x1B[0m Instance '${name}' rebuilt successfully`);
2120
+ console.log(` Container: ${result.containerName}`);
1812
2121
  }
1813
- console.log(`\x1B[32m\u2713\x1B[0m Instance '${name}' rebuilt successfully`);
1814
- console.log(` Container: ${result.containerName}`);
1815
- });
2122
+ );
1816
2123
 
1817
2124
  // src/commands/remove.ts
1818
2125
  import chalk3 from "chalk";
@@ -1822,16 +2129,16 @@ import { createInterface as createInterface2 } from "readline";
1822
2129
  // src/lib/audit-log.ts
1823
2130
  import { appendFile as appendFile6, mkdir as mkdir8 } from "fs/promises";
1824
2131
  import { homedir as homedir6 } from "os";
1825
- import { join as join5 } from "path";
2132
+ import { join as join7 } from "path";
1826
2133
  function createAuditLogDefaultDeps() {
1827
2134
  return { appendFile: appendFile6, mkdir: mkdir8, homedir: homedir6 };
1828
2135
  }
1829
2136
  function getAuditLogPath(deps) {
1830
- return join5(deps.homedir(), AGENT_ENV_DIR, "audit.log");
2137
+ return join7(deps.homedir(), AGENT_ENV_DIR, "audit.log");
1831
2138
  }
1832
2139
  async function writeAuditLogEntry(entry, deps = createAuditLogDefaultDeps()) {
1833
2140
  const logPath = getAuditLogPath(deps);
1834
- await deps.mkdir(join5(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
2141
+ await deps.mkdir(join7(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
1835
2142
  const line = JSON.stringify(entry) + "\n";
1836
2143
  await deps.appendFile(logPath, line, "utf-8");
1837
2144
  }
@@ -2359,7 +2666,7 @@ async function launchInteractiveMenu(deps) {
2359
2666
  }
2360
2667
  case "rebuild": {
2361
2668
  const rebuildDeps = deps.createRebuildDeps();
2362
- const rebuildResult = await deps.rebuildInstance(name, rebuildDeps, true);
2669
+ const rebuildResult = await deps.rebuildInstance(name, rebuildDeps, { force: true });
2363
2670
  if (!rebuildResult.ok) return { ok: false, error: rebuildResult.error };
2364
2671
  return { ok: true, action: "rebuilt", instanceName: name };
2365
2672
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zookanalytics/agent-env",
3
- "version": "0.1.3",
3
+ "version": "0.3.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
  },
@@ -1,27 +0,0 @@
1
- FROM node:22-bookworm-slim
2
-
3
- # Install system dependencies
4
- RUN apt-get update && apt-get install -y --no-install-recommends \
5
- tmux \
6
- zsh \
7
- git \
8
- gnupg \
9
- openssh-client \
10
- curl \
11
- sudo \
12
- && rm -rf /var/lib/apt/lists/*
13
-
14
- # Install Claude Code CLI globally
15
- RUN npm install -g @anthropic-ai/claude-code@2.1.29
16
-
17
- # Configure non-root user with sudo access
18
- RUN echo "node ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers.d/node \
19
- && chmod 0440 /etc/sudoers.d/node
20
-
21
- # Switch to non-root user
22
- USER node
23
-
24
- # Set zsh as default shell
25
- RUN sudo chsh -s /usr/bin/zsh node
26
-
27
- WORKDIR /workspace
@@ -1,23 +0,0 @@
1
- #!/usr/bin/env bash
2
- # post-create.sh - Runtime initialization for agent-env devcontainers
3
- # Runs once after the container is created
4
-
5
- set -euo pipefail
6
-
7
- echo "=== agent-env: post-create initialization ==="
8
-
9
- # Verify tool installation
10
- echo "--- Tool verification ---"
11
- echo "Node.js: $(node --version)"
12
- echo "npm: $(npm --version)"
13
- echo "git: $(git --version)"
14
- echo "tmux: $(tmux -V)"
15
- echo "zsh: $(zsh --version)"
16
-
17
- if command -v claude &>/dev/null; then
18
- echo "Claude Code: installed"
19
- else
20
- echo "Warning: Claude Code CLI not found in PATH"
21
- fi
22
-
23
- echo "=== agent-env: post-create complete ==="