@zookanalytics/agent-env 0.2.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +127 -0
- package/config/baseline/devcontainer.json +2 -28
- package/config/baseline/init-host.sh +16 -8
- package/dist/cli.js +199 -77
- package/package.json +1 -1
- package/config/baseline/Dockerfile +0 -27
- package/config/baseline/post-create.sh +0 -23
package/README.md
CHANGED
|
@@ -13,6 +13,133 @@ npm install -g @zookanalytics/agent-env
|
|
|
13
13
|
- Node.js >= 20
|
|
14
14
|
- Docker (OrbStack recommended on macOS)
|
|
15
15
|
|
|
16
|
+
## Workspace Structure
|
|
17
|
+
|
|
18
|
+
Each agent environment creates a `.agent-env/` directory inside the workspace to store instance-specific data:
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
<workspace>/
|
|
22
|
+
├── .agent-env/ # Instance data (git-ignored)
|
|
23
|
+
│ ├── state.json # Instance metadata (repo URL, container name, config source)
|
|
24
|
+
│ ├── ssh/ # SSH host keys (container identity)
|
|
25
|
+
│ │ ├── ssh_host_ed25519_key
|
|
26
|
+
│ │ ├── ssh_host_ed25519_key.pub
|
|
27
|
+
│ │ ├── ssh_host_rsa_key
|
|
28
|
+
│ │ └── ssh_host_rsa_key.pub
|
|
29
|
+
│ ├── devcontainer.json # Baseline config (only if using baseline)
|
|
30
|
+
│ └── init-host.sh # Baseline init script (only if using baseline)
|
|
31
|
+
├── .devcontainer/ # Project's devcontainer config (if present)
|
|
32
|
+
└── <your code>
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
**What's in `.agent-env/`:**
|
|
36
|
+
|
|
37
|
+
- **`state.json`** - Instance metadata including repository URL, container name, and configuration source
|
|
38
|
+
- **`ssh/`** - SSH host keys that persist across container restarts, preventing "host identification changed" warnings
|
|
39
|
+
- **`devcontainer.json`** - Copied from baseline config when creating instances without their own `.devcontainer/`
|
|
40
|
+
- **`init-host.sh`** - Host-side initialization script (baseline configs only)
|
|
41
|
+
|
|
42
|
+
**Git exclusion:**
|
|
43
|
+
|
|
44
|
+
The `.agent-env/` directory is automatically added to `.git/info/exclude` so instance state doesn't appear as untracked files in your git status.
|
|
45
|
+
|
|
46
|
+
## SSH Access
|
|
47
|
+
|
|
48
|
+
Each agent environment runs an SSH server, allowing you to connect directly:
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
# On OrbStack (recommended)
|
|
52
|
+
ssh node@ae-<instance-name>.orb.local
|
|
53
|
+
|
|
54
|
+
# Via port forwarding (automatic fallback)
|
|
55
|
+
ssh -p <port> node@localhost
|
|
56
|
+
|
|
57
|
+
# Find connection details
|
|
58
|
+
agent-env list # Shows SSH connection strings
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
### How It Works
|
|
62
|
+
|
|
63
|
+
**Host Keys (Container Identity)**
|
|
64
|
+
|
|
65
|
+
Each container generates unique SSH host keys on first creation, stored in `.agent-env/ssh/` inside the workspace:
|
|
66
|
+
- `ssh_host_ed25519_key` / `ssh_host_ed25519_key.pub`
|
|
67
|
+
- `ssh_host_rsa_key` / `ssh_host_rsa_key.pub`
|
|
68
|
+
|
|
69
|
+
These persist across container stops/starts/rebuilds, ensuring you don't get "host identification changed" warnings. They identify the SSH **server** (the container's sshd).
|
|
70
|
+
|
|
71
|
+
**User Keys (Your Identity)**
|
|
72
|
+
|
|
73
|
+
Your public SSH keys from `~/.ssh/*.pub` are automatically staged into the container's `authorized_keys`. The private keys remain on your host - containers only see your public keys.
|
|
74
|
+
|
|
75
|
+
**Why separate host and user keys?**
|
|
76
|
+
- **Host keys**: Container proves "I'm the legitimate ae-my-project server"
|
|
77
|
+
- **User keys**: You prove "I'm authorized to access this container"
|
|
78
|
+
|
|
79
|
+
This is standard SSH architecture - the same pattern used by any SSH server.
|
|
80
|
+
|
|
81
|
+
## Commit Signing Setup
|
|
82
|
+
|
|
83
|
+
Agent environments support commit signing via **SSH signing** (recommended) or GPG signing.
|
|
84
|
+
|
|
85
|
+
### SSH Signing (Recommended)
|
|
86
|
+
|
|
87
|
+
SSH signing is recommended because:
|
|
88
|
+
- SSH agent forwarding is built into Docker Desktop
|
|
89
|
+
- No additional background processes needed
|
|
90
|
+
- Works reliably on macOS with Docker Desktop
|
|
91
|
+
- Supported by GitHub, GitLab, and Gitea
|
|
92
|
+
|
|
93
|
+
**Setup:**
|
|
94
|
+
|
|
95
|
+
1. **Configure git to use the public key content directly:**
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
# Configure git to use SSH signing with the actual key content
|
|
99
|
+
git config --global gpg.format ssh
|
|
100
|
+
git config --global user.signingkey "$(cat ~/.ssh/id_ed25519.pub)"
|
|
101
|
+
git config --global commit.gpgsign true
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
This embeds the public key content in your `.gitconfig`:
|
|
105
|
+
```ini
|
|
106
|
+
[gpg]
|
|
107
|
+
format = ssh
|
|
108
|
+
[user]
|
|
109
|
+
signingkey = ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... user@host
|
|
110
|
+
[commit]
|
|
111
|
+
gpgsign = true
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
**Why use the key content instead of a file path?**
|
|
115
|
+
|
|
116
|
+
Your `.gitconfig` is mounted from the host into containers, but SSH keys are NOT copied in. Instead, the SSH agent socket is forwarded. The public key content acts as an identifier telling git which key pair to use - the actual signing happens via the forwarded SSH agent using your private key.
|
|
117
|
+
|
|
118
|
+
File paths like `~/.ssh/id_ed25519.pub` won't work because:
|
|
119
|
+
- Host path: `/Users/you/.ssh/id_ed25519.pub`
|
|
120
|
+
- Container path: `/home/node/.ssh/id_ed25519.pub` (doesn't exist - keys aren't copied)
|
|
121
|
+
|
|
122
|
+
Using the key content directly avoids this path mismatch entirely.
|
|
123
|
+
|
|
124
|
+
2. **Verify SSH agent has your key:**
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
ssh-add -l # Should list your SSH key
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Commit signing will now work in all containers automatically.
|
|
131
|
+
|
|
132
|
+
### GPG Signing
|
|
133
|
+
|
|
134
|
+
GPG signing has limitations on macOS with Docker Desktop:
|
|
135
|
+
- Unix domain sockets cannot be bind-mounted from macOS to Linux containers
|
|
136
|
+
- Requires SSH tunneling or relay processes per container
|
|
137
|
+
- Complex lifecycle management
|
|
138
|
+
|
|
139
|
+
**If you must use GPG:**
|
|
140
|
+
- GPG signing works when opening containers in VS Code (built-in forwarding)
|
|
141
|
+
- For CLI-based workflows, consider SSH signing instead
|
|
142
|
+
|
|
16
143
|
## Usage
|
|
17
144
|
|
|
18
145
|
```bash
|
|
@@ -1,30 +1,4 @@
|
|
|
1
1
|
{
|
|
2
|
-
"
|
|
3
|
-
|
|
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.
|
|
45
|
+
version: "0.3.1",
|
|
46
46
|
description: "CLI for creating isolated, AI-ready development environments",
|
|
47
47
|
type: "module",
|
|
48
48
|
bin: {
|
|
@@ -105,9 +105,10 @@ import { Command } from "commander";
|
|
|
105
105
|
// src/lib/attach-instance.ts
|
|
106
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";
|
|
107
107
|
import { homedir as homedir3 } from "os";
|
|
108
|
+
import { join as join5 } from "path";
|
|
108
109
|
|
|
109
110
|
// src/lib/container.ts
|
|
110
|
-
var DEVCONTAINER_UP_TIMEOUT =
|
|
111
|
+
var DEVCONTAINER_UP_TIMEOUT = 3e5;
|
|
111
112
|
var DEVCONTAINER_UP_NO_CACHE_TIMEOUT = 3e5;
|
|
112
113
|
var DOCKER_PULL_TIMEOUT = 3e5;
|
|
113
114
|
var DOCKER_INSPECT_TIMEOUT = 1e4;
|
|
@@ -128,6 +129,51 @@ function parseDevcontainerOutput(stdout) {
|
|
|
128
129
|
}
|
|
129
130
|
return null;
|
|
130
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
|
+
}
|
|
131
177
|
function createContainerLifecycle(executor = createExecutor()) {
|
|
132
178
|
async function isDockerAvailable() {
|
|
133
179
|
const result = await executor("docker", ["info"], { timeout: DOCKER_INFO_TIMEOUT });
|
|
@@ -142,7 +188,8 @@ function createContainerLifecycle(executor = createExecutor()) {
|
|
|
142
188
|
return {
|
|
143
189
|
ok: true,
|
|
144
190
|
status: "not-found",
|
|
145
|
-
containerId: null
|
|
191
|
+
containerId: null,
|
|
192
|
+
ports: {}
|
|
146
193
|
};
|
|
147
194
|
}
|
|
148
195
|
return {
|
|
@@ -161,17 +208,28 @@ function createContainerLifecycle(executor = createExecutor()) {
|
|
|
161
208
|
return {
|
|
162
209
|
ok: true,
|
|
163
210
|
status: "not-found",
|
|
164
|
-
containerId: null
|
|
211
|
+
containerId: null,
|
|
212
|
+
ports: {}
|
|
165
213
|
};
|
|
166
214
|
}
|
|
167
215
|
const container = inspectData[0];
|
|
168
216
|
const containerId = container.Id ?? null;
|
|
169
217
|
const dockerStatus = container.State?.Status ?? "unknown";
|
|
170
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
|
+
}
|
|
171
228
|
return {
|
|
172
229
|
ok: true,
|
|
173
230
|
status,
|
|
174
|
-
containerId
|
|
231
|
+
containerId,
|
|
232
|
+
ports
|
|
175
233
|
};
|
|
176
234
|
} catch (e) {
|
|
177
235
|
const errorMessage = e instanceof Error ? e.message : String(e);
|
|
@@ -231,10 +289,19 @@ function createContainerLifecycle(executor = createExecutor()) {
|
|
|
231
289
|
};
|
|
232
290
|
}
|
|
233
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] : [];
|
|
234
297
|
const args = [
|
|
235
298
|
"up",
|
|
236
299
|
"--workspace-folder",
|
|
237
300
|
workspacePath,
|
|
301
|
+
...configArgs,
|
|
302
|
+
"--log-level",
|
|
303
|
+
"debug",
|
|
304
|
+
...remoteEnvArgs,
|
|
238
305
|
...buildNoCache ? ["--build-no-cache"] : []
|
|
239
306
|
];
|
|
240
307
|
const result = await executor("devcontainer", args, {
|
|
@@ -242,12 +309,7 @@ function createContainerLifecycle(executor = createExecutor()) {
|
|
|
242
309
|
});
|
|
243
310
|
const parsedOutput = parseDevcontainerOutput(result.stdout);
|
|
244
311
|
if (!result.ok) {
|
|
245
|
-
const
|
|
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";
|
|
312
|
+
const details = buildDevcontainerErrorDetails(result.stdout, result.stderr, parsedOutput);
|
|
251
313
|
const combined = `${result.stderr} ${result.stdout}`;
|
|
252
314
|
const isNameConflict = combined.includes("is already in use") || combined.includes("name is already in use") || combined.includes("Conflict.") || combined.includes("conflict");
|
|
253
315
|
return {
|
|
@@ -266,7 +328,8 @@ function createContainerLifecycle(executor = createExecutor()) {
|
|
|
266
328
|
return {
|
|
267
329
|
ok: true,
|
|
268
330
|
status: "running",
|
|
269
|
-
containerId
|
|
331
|
+
containerId,
|
|
332
|
+
ports: {}
|
|
270
333
|
};
|
|
271
334
|
}
|
|
272
335
|
async function containerStop(containerName) {
|
|
@@ -347,13 +410,32 @@ import {
|
|
|
347
410
|
writeFile as writeFile3
|
|
348
411
|
} from "fs/promises";
|
|
349
412
|
import { homedir as homedir2 } from "os";
|
|
350
|
-
import { dirname as dirname2 } from "path";
|
|
413
|
+
import { dirname as dirname2, join as join4 } from "path";
|
|
351
414
|
|
|
352
415
|
// src/lib/devcontainer.ts
|
|
353
416
|
import { parse as parseJsonc } from "jsonc-parser";
|
|
354
417
|
import { access, cp, mkdir, readdir, readFile, stat, writeFile } from "fs/promises";
|
|
355
418
|
import { dirname, join } from "path";
|
|
356
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
|
|
357
439
|
var defaultFsDeps = { access, cp, mkdir, readdir, readFile, stat, writeFile };
|
|
358
440
|
var DEVCONTAINER_DIR = ".devcontainer";
|
|
359
441
|
var DEVCONTAINER_JSON = "devcontainer.json";
|
|
@@ -394,7 +476,7 @@ async function copyBaselineConfig(workspacePath, deps = defaultFsDeps) {
|
|
|
394
476
|
} catch {
|
|
395
477
|
throw new Error(`Baseline config not found at ${baselinePath}. Package may be corrupted.`);
|
|
396
478
|
}
|
|
397
|
-
const targetDir = join(workspacePath,
|
|
479
|
+
const targetDir = join(workspacePath, AGENT_ENV_DIR);
|
|
398
480
|
await deps.mkdir(targetDir, { recursive: true });
|
|
399
481
|
await deps.cp(baselinePath, targetDir, { recursive: true });
|
|
400
482
|
}
|
|
@@ -407,11 +489,6 @@ async function patchContainerName(workspacePath, containerName, deps = defaultFs
|
|
|
407
489
|
config.runArgs = [...filtered, `--name=${containerName}`];
|
|
408
490
|
await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
|
|
409
491
|
}
|
|
410
|
-
async function listBaselineFiles(deps = defaultFsDeps) {
|
|
411
|
-
const baselinePath = getBaselineConfigPath();
|
|
412
|
-
const entries = await deps.readdir(baselinePath);
|
|
413
|
-
return entries.sort();
|
|
414
|
-
}
|
|
415
492
|
async function resolveDockerfilePath(workspacePath, deps) {
|
|
416
493
|
const candidates = [
|
|
417
494
|
join(workspacePath, DEVCONTAINER_DIR, DEVCONTAINER_JSON),
|
|
@@ -485,25 +562,6 @@ function parseDockerfileImages(content, logger) {
|
|
|
485
562
|
// src/lib/state.ts
|
|
486
563
|
import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
|
|
487
564
|
import { join as join2 } from "path";
|
|
488
|
-
|
|
489
|
-
// src/lib/types.ts
|
|
490
|
-
var AGENT_ENV_DIR = ".agent-env";
|
|
491
|
-
var WORKSPACES_DIR = "workspaces";
|
|
492
|
-
var STATE_FILE = "state.json";
|
|
493
|
-
var STATE_FILE_TMP = "state.json.tmp";
|
|
494
|
-
var CONTAINER_PREFIX = "ae-";
|
|
495
|
-
function createFallbackState(workspaceName) {
|
|
496
|
-
return {
|
|
497
|
-
name: workspaceName,
|
|
498
|
-
repo: "unknown",
|
|
499
|
-
createdAt: "unknown",
|
|
500
|
-
lastAttached: "unknown",
|
|
501
|
-
purpose: null,
|
|
502
|
-
containerName: `${CONTAINER_PREFIX}${workspaceName}`
|
|
503
|
-
};
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
// src/lib/state.ts
|
|
507
565
|
var defaultStateFsDeps = { readFile: readFile2, writeFile: writeFile2, rename, mkdir: mkdir2, appendFile };
|
|
508
566
|
async function readState(wsPath, deps = defaultStateFsDeps) {
|
|
509
567
|
try {
|
|
@@ -795,7 +853,7 @@ async function createInstance(instanceName, repoUrl, deps) {
|
|
|
795
853
|
};
|
|
796
854
|
}
|
|
797
855
|
try {
|
|
798
|
-
await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps);
|
|
856
|
+
await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps, AGENT_ENV_DIR);
|
|
799
857
|
} catch (err) {
|
|
800
858
|
await safeRollback(wsPath.root, deps.rm, deps.logger);
|
|
801
859
|
return {
|
|
@@ -821,17 +879,13 @@ async function createInstance(instanceName, repoUrl, deps) {
|
|
|
821
879
|
}
|
|
822
880
|
};
|
|
823
881
|
}
|
|
824
|
-
const
|
|
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
|
+
});
|
|
825
887
|
if (!containerResult.ok) {
|
|
826
|
-
|
|
827
|
-
await safeRollback(wsPath.root, deps.rm, deps.logger);
|
|
828
|
-
return {
|
|
829
|
-
ok: false,
|
|
830
|
-
error: containerResult.error ?? {
|
|
831
|
-
code: "CONTAINER_ERROR",
|
|
832
|
-
message: "Container startup failed for unknown reason."
|
|
833
|
-
}
|
|
834
|
-
};
|
|
888
|
+
return rollbackContainerFailure(containerName, wsPath, containerResult, deps);
|
|
835
889
|
}
|
|
836
890
|
let actualContainerName = containerName;
|
|
837
891
|
if (containerResult.containerId) {
|
|
@@ -856,6 +910,58 @@ async function createInstance(instanceName, repoUrl, deps) {
|
|
|
856
910
|
containerName: actualContainerName
|
|
857
911
|
};
|
|
858
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
|
+
}
|
|
859
965
|
async function safeRollback(workspacePath, rmFn, logger) {
|
|
860
966
|
try {
|
|
861
967
|
await rmFn(workspacePath, { recursive: true, force: true });
|
|
@@ -936,7 +1042,12 @@ async function attachInstance(instanceName, deps, onContainerStarting, onAttachi
|
|
|
936
1042
|
}
|
|
937
1043
|
if (statusResult.status === "stopped" || statusResult.status === "not-found") {
|
|
938
1044
|
onContainerStarting?.();
|
|
939
|
-
const
|
|
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
|
+
});
|
|
940
1051
|
if (!startResult.ok) {
|
|
941
1052
|
return {
|
|
942
1053
|
ok: false,
|
|
@@ -1281,6 +1392,13 @@ function formatPurpose(purpose) {
|
|
|
1281
1392
|
}
|
|
1282
1393
|
return purpose;
|
|
1283
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
|
+
}
|
|
1284
1402
|
function InstanceList({
|
|
1285
1403
|
instances,
|
|
1286
1404
|
dockerAvailable
|
|
@@ -1305,12 +1423,14 @@ function InstanceList({
|
|
|
1305
1423
|
const statusWidth = Math.max(6, ...augmentedInstances.map((i) => statusLabel(i.status, dockerAvailable).length)) + 2;
|
|
1306
1424
|
const gitWidth = Math.max(3, ...augmentedInstances.map((i) => i.indicatorText.length)) + 2;
|
|
1307
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;
|
|
1308
1427
|
return /* @__PURE__ */ jsxs2(Box, { flexDirection: "column", children: [
|
|
1309
1428
|
/* @__PURE__ */ jsxs2(Box, { children: [
|
|
1310
1429
|
/* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("NAME", nameWidth) }),
|
|
1311
1430
|
/* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("STATUS", statusWidth) }),
|
|
1312
1431
|
/* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("GIT", gitWidth) }),
|
|
1313
1432
|
/* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("LAST ATTACHED", lastAttachedWidth) }),
|
|
1433
|
+
/* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("SSH", sshWidth) }),
|
|
1314
1434
|
/* @__PURE__ */ jsx2(Text2, { bold: true, children: "PURPOSE" })
|
|
1315
1435
|
] }),
|
|
1316
1436
|
augmentedInstances.map((instance) => /* @__PURE__ */ jsxs2(Box, { children: [
|
|
@@ -1321,6 +1441,7 @@ function InstanceList({
|
|
|
1321
1441
|
ind.symbol
|
|
1322
1442
|
] }, idx)) }),
|
|
1323
1443
|
/* @__PURE__ */ jsx2(Text2, { children: pad(formatLastAttached(instance.lastAttached), lastAttachedWidth) }),
|
|
1444
|
+
/* @__PURE__ */ jsx2(Text2, { color: "cyan", children: pad(formatSSH(instance.sshConnection), sshWidth) }),
|
|
1324
1445
|
/* @__PURE__ */ jsx2(Text2, { color: "gray", children: formatPurpose(instance.purpose) })
|
|
1325
1446
|
] }, instance.name)),
|
|
1326
1447
|
!dockerAvailable && /* @__PURE__ */ jsx2(Box, { marginTop: 1, children: /* @__PURE__ */ jsx2(Text2, { color: "yellow", children: "\u26A0 Docker is not available. Container status cannot be determined." }) })
|
|
@@ -1493,12 +1614,23 @@ async function listInstances(deps) {
|
|
|
1493
1614
|
} else {
|
|
1494
1615
|
status = containerResult.status;
|
|
1495
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
|
+
}
|
|
1496
1627
|
return {
|
|
1497
1628
|
name: wsName,
|
|
1498
1629
|
status,
|
|
1499
1630
|
lastAttached: state.lastAttached !== "unknown" ? state.lastAttached : null,
|
|
1500
1631
|
purpose: state.purpose,
|
|
1501
|
-
gitState
|
|
1632
|
+
gitState,
|
|
1633
|
+
sshConnection
|
|
1502
1634
|
};
|
|
1503
1635
|
});
|
|
1504
1636
|
const instances = await Promise.all(instancePromises);
|
|
@@ -1544,7 +1676,8 @@ var listCommand = new Command4("list").alias("ps").description("List all instanc
|
|
|
1544
1676
|
status: i.status,
|
|
1545
1677
|
lastAttached: i.lastAttached,
|
|
1546
1678
|
purpose: i.purpose,
|
|
1547
|
-
gitState: i.gitState
|
|
1679
|
+
gitState: i.gitState,
|
|
1680
|
+
sshConnection: i.sshConnection
|
|
1548
1681
|
})),
|
|
1549
1682
|
error: null
|
|
1550
1683
|
};
|
|
@@ -1666,7 +1799,7 @@ import {
|
|
|
1666
1799
|
appendFile as appendFile5
|
|
1667
1800
|
} from "fs/promises";
|
|
1668
1801
|
import { homedir as homedir5 } from "os";
|
|
1669
|
-
import { join as
|
|
1802
|
+
import { join as join6 } from "path";
|
|
1670
1803
|
function createRebuildDefaultDeps() {
|
|
1671
1804
|
const executor = createExecutor();
|
|
1672
1805
|
return {
|
|
@@ -1681,30 +1814,15 @@ function createRebuildDefaultDeps() {
|
|
|
1681
1814
|
};
|
|
1682
1815
|
}
|
|
1683
1816
|
async function refreshConfig(wsRoot, containerName, configSource, deps) {
|
|
1684
|
-
const devcontainerDir = join4(wsRoot, ".devcontainer");
|
|
1685
|
-
const tempDevcontainerDir = join4(wsRoot, ".devcontainer.new");
|
|
1686
1817
|
if (configSource === "baseline") {
|
|
1818
|
+
const agentEnvDir = join6(wsRoot, AGENT_ENV_DIR);
|
|
1687
1819
|
try {
|
|
1688
|
-
|
|
1689
|
-
|
|
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, {
|
|
1820
|
+
await deps.devcontainerFsDeps.mkdir(agentEnvDir, { recursive: true });
|
|
1821
|
+
await deps.devcontainerFsDeps.cp(getBaselineConfigPath(), agentEnvDir, {
|
|
1701
1822
|
recursive: true
|
|
1702
1823
|
});
|
|
1703
|
-
await patchContainerName(wsRoot, containerName, deps.devcontainerFsDeps,
|
|
1704
|
-
await deps.rm(devcontainerDir, { recursive: true, force: true });
|
|
1705
|
-
await deps.rename(tempDevcontainerDir, devcontainerDir);
|
|
1824
|
+
await patchContainerName(wsRoot, containerName, deps.devcontainerFsDeps, AGENT_ENV_DIR);
|
|
1706
1825
|
} catch (err) {
|
|
1707
|
-
await deps.rm(tempDevcontainerDir, { recursive: true, force: true });
|
|
1708
1826
|
return {
|
|
1709
1827
|
ok: false,
|
|
1710
1828
|
error: {
|
|
@@ -1726,9 +1844,10 @@ async function refreshConfig(wsRoot, containerName, configSource, deps) {
|
|
|
1726
1844
|
}
|
|
1727
1845
|
};
|
|
1728
1846
|
}
|
|
1847
|
+
const devcontainerDir = join6(wsRoot, ".devcontainer");
|
|
1729
1848
|
const dirExists = await deps.devcontainerFsDeps.stat(devcontainerDir).catch(() => null);
|
|
1730
1849
|
if (dirExists) {
|
|
1731
|
-
const jsonExists = await deps.devcontainerFsDeps.stat(
|
|
1850
|
+
const jsonExists = await deps.devcontainerFsDeps.stat(join6(devcontainerDir, "devcontainer.json")).catch(() => null);
|
|
1732
1851
|
if (!jsonExists) {
|
|
1733
1852
|
return {
|
|
1734
1853
|
ok: false,
|
|
@@ -1904,8 +2023,11 @@ async function rebuildInstance(instanceName, deps, options) {
|
|
|
1904
2023
|
return { ok: false, error: teardownResult.error, wasRunning };
|
|
1905
2024
|
}
|
|
1906
2025
|
const buildNoCache = noCache && hasDockerfile;
|
|
2026
|
+
const baselineConfigPath = configSource === "baseline" ? join6(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
|
|
1907
2027
|
const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
|
|
1908
|
-
buildNoCache
|
|
2028
|
+
buildNoCache,
|
|
2029
|
+
remoteEnv: { AGENT_INSTANCE: wsPath.name },
|
|
2030
|
+
configPath: baselineConfigPath
|
|
1909
2031
|
});
|
|
1910
2032
|
if (!containerResult.ok) {
|
|
1911
2033
|
return {
|
|
@@ -2007,16 +2129,16 @@ import { createInterface as createInterface2 } from "readline";
|
|
|
2007
2129
|
// src/lib/audit-log.ts
|
|
2008
2130
|
import { appendFile as appendFile6, mkdir as mkdir8 } from "fs/promises";
|
|
2009
2131
|
import { homedir as homedir6 } from "os";
|
|
2010
|
-
import { join as
|
|
2132
|
+
import { join as join7 } from "path";
|
|
2011
2133
|
function createAuditLogDefaultDeps() {
|
|
2012
2134
|
return { appendFile: appendFile6, mkdir: mkdir8, homedir: homedir6 };
|
|
2013
2135
|
}
|
|
2014
2136
|
function getAuditLogPath(deps) {
|
|
2015
|
-
return
|
|
2137
|
+
return join7(deps.homedir(), AGENT_ENV_DIR, "audit.log");
|
|
2016
2138
|
}
|
|
2017
2139
|
async function writeAuditLogEntry(entry, deps = createAuditLogDefaultDeps()) {
|
|
2018
2140
|
const logPath = getAuditLogPath(deps);
|
|
2019
|
-
await deps.mkdir(
|
|
2141
|
+
await deps.mkdir(join7(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
|
|
2020
2142
|
const line = JSON.stringify(entry) + "\n";
|
|
2021
2143
|
await deps.appendFile(logPath, line, "utf-8");
|
|
2022
2144
|
}
|
package/package.json
CHANGED
|
@@ -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 ==="
|