@zookanalytics/agent-env 0.1.0 → 0.1.2

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/dist/cli.js ADDED
@@ -0,0 +1,2033 @@
1
+ #!/usr/bin/env node
2
+
3
+ // ../shared/dist/errors.js
4
+ function formatError(error) {
5
+ const lines = [];
6
+ lines.push(`\x1B[31m\u274C [${error.code}]\x1B[0m ${error.message}`);
7
+ if (error.suggestion) {
8
+ lines.push(` \x1B[36m\u{1F4A1} ${error.suggestion}\x1B[0m`);
9
+ }
10
+ return lines.join("\n");
11
+ }
12
+ function createError(code, message, suggestion) {
13
+ return { code, message, ...suggestion && { suggestion } };
14
+ }
15
+
16
+ // ../shared/dist/subprocess.js
17
+ import { execa } from "execa";
18
+ function createExecutor(executor = execa) {
19
+ return async function execute2(command, args = [], options = {}) {
20
+ const result = await executor(command, args, {
21
+ reject: false,
22
+ ...options
23
+ });
24
+ return {
25
+ ok: !result.failed,
26
+ stdout: String(result.stdout ?? ""),
27
+ stderr: String(result.stderr ?? ""),
28
+ exitCode: result.exitCode ?? -1
29
+ };
30
+ };
31
+ }
32
+ var execute = createExecutor();
33
+
34
+ // src/cli.ts
35
+ import { program } from "commander";
36
+ import { render as render2 } from "ink";
37
+ import React2 from "react";
38
+
39
+ // package.json
40
+ var package_default = {
41
+ name: "@zookanalytics/agent-env",
42
+ version: "0.1.2",
43
+ description: "CLI for creating isolated, AI-ready development environments",
44
+ type: "module",
45
+ bin: {
46
+ "agent-env": "bin/agent-env.js"
47
+ },
48
+ exports: {
49
+ ".": {
50
+ types: "./dist/cli.d.ts",
51
+ import: "./dist/cli.js"
52
+ }
53
+ },
54
+ repository: {
55
+ type: "git",
56
+ url: "https://github.com/zookanalytics/bmad-orchestrator",
57
+ directory: "packages/agent-env"
58
+ },
59
+ engines: {
60
+ node: ">=20"
61
+ },
62
+ files: [
63
+ "dist",
64
+ "bin",
65
+ "config",
66
+ "README.md",
67
+ "LICENSE"
68
+ ],
69
+ scripts: {
70
+ dev: "tsx src/cli.ts",
71
+ build: "tsup",
72
+ test: "vitest",
73
+ "test:run": "vitest run",
74
+ "test:coverage": "vitest run --coverage",
75
+ lint: "eslint src/",
76
+ "type-check": "tsc --noEmit",
77
+ check: "pnpm type-check && pnpm lint && pnpm test:run"
78
+ },
79
+ dependencies: {
80
+ "@inkjs/ui": "^2.0.0",
81
+ chalk: "^5.3.0",
82
+ commander: "^14.0.2",
83
+ execa: "^9.6.1",
84
+ ink: "^6.6.0",
85
+ react: "^19.2.3",
86
+ "timeago.js": "^4.0.2"
87
+ },
88
+ devDependencies: {
89
+ "@types/node": "^20.14.10",
90
+ "@types/react": "^19.2.8",
91
+ "@zookanalytics/shared": "workspace:*",
92
+ "ink-testing-library": "^4.0.0",
93
+ tsup: "^8.5.1",
94
+ tsx: "^4.21.0"
95
+ }
96
+ };
97
+
98
+ // src/commands/attach.ts
99
+ import { Command } from "commander";
100
+
101
+ // src/lib/attach-instance.ts
102
+ 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";
103
+ import { homedir as homedir3 } from "os";
104
+
105
+ // src/lib/container.ts
106
+ var DEVCONTAINER_UP_TIMEOUT = 12e4;
107
+ var DOCKER_INSPECT_TIMEOUT = 1e4;
108
+ var DOCKER_INFO_TIMEOUT = 5e3;
109
+ var DOCKER_STOP_TIMEOUT = 3e4;
110
+ var DOCKER_RM_TIMEOUT = 1e4;
111
+ function createContainerLifecycle(executor = createExecutor()) {
112
+ async function isDockerAvailable() {
113
+ const result = await executor("docker", ["info"], { timeout: DOCKER_INFO_TIMEOUT });
114
+ return result.ok;
115
+ }
116
+ async function containerStatus(containerName) {
117
+ const result = await executor("docker", ["inspect", containerName], {
118
+ timeout: DOCKER_INSPECT_TIMEOUT
119
+ });
120
+ if (!result.ok) {
121
+ if (result.stderr.includes("No such") || result.stderr.includes("not found")) {
122
+ return {
123
+ ok: true,
124
+ status: "not-found",
125
+ containerId: null
126
+ };
127
+ }
128
+ return {
129
+ ok: false,
130
+ status: "not-found",
131
+ containerId: null,
132
+ error: {
133
+ code: "CONTAINER_ERROR",
134
+ message: `Failed to inspect container '${containerName}': ${result.stderr}`
135
+ }
136
+ };
137
+ }
138
+ try {
139
+ const inspectData = JSON.parse(result.stdout);
140
+ if (!inspectData.length) {
141
+ return {
142
+ ok: true,
143
+ status: "not-found",
144
+ containerId: null
145
+ };
146
+ }
147
+ const container = inspectData[0];
148
+ const containerId = container.Id ?? null;
149
+ const dockerStatus = container.State?.Status ?? "unknown";
150
+ const status = dockerStatus === "running" ? "running" : "stopped";
151
+ return {
152
+ ok: true,
153
+ status,
154
+ containerId
155
+ };
156
+ } catch (e) {
157
+ const errorMessage = e instanceof Error ? e.message : String(e);
158
+ return {
159
+ ok: false,
160
+ status: "not-found",
161
+ containerId: null,
162
+ error: {
163
+ code: "CONTAINER_ERROR",
164
+ message: `Failed to parse docker inspect output for '${containerName}': ${errorMessage}`
165
+ }
166
+ };
167
+ }
168
+ }
169
+ async function getContainerNameById(containerId) {
170
+ const result = await executor("docker", ["inspect", containerId, "--format", "{{.Name}}"], {
171
+ timeout: DOCKER_INSPECT_TIMEOUT
172
+ });
173
+ if (!result.ok) {
174
+ return null;
175
+ }
176
+ const name = result.stdout.trim().replace(/^\//, "");
177
+ return name || null;
178
+ }
179
+ async function devcontainerUp(workspacePath, containerName) {
180
+ const dockerOk = await isDockerAvailable();
181
+ if (!dockerOk) {
182
+ return {
183
+ ok: false,
184
+ status: "not-found",
185
+ containerId: null,
186
+ error: {
187
+ code: "ORBSTACK_REQUIRED",
188
+ message: "Docker is not available. OrbStack or Docker Desktop must be running.",
189
+ suggestion: "Start OrbStack or Docker Desktop, then try again."
190
+ }
191
+ };
192
+ }
193
+ const result = await executor("devcontainer", ["up", "--workspace-folder", workspacePath], {
194
+ timeout: DEVCONTAINER_UP_TIMEOUT
195
+ });
196
+ let parsedOutput = null;
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
+ }
209
+ if (!result.ok) {
210
+ const details = parsedOutput?.message || parsedOutput?.description || result.stderr || result.stdout.slice(0, 500) || "No error details available";
211
+ return {
212
+ ok: false,
213
+ status: "not-found",
214
+ containerId: null,
215
+ error: {
216
+ code: "CONTAINER_ERROR",
217
+ message: `devcontainer up failed for '${containerName}':
218
+ ${details}`,
219
+ suggestion: "Check the devcontainer.json configuration and Docker logs."
220
+ }
221
+ };
222
+ }
223
+ const containerId = parsedOutput?.containerId ?? null;
224
+ return {
225
+ ok: true,
226
+ status: "running",
227
+ containerId
228
+ };
229
+ }
230
+ async function containerStop(containerName) {
231
+ const result = await executor("docker", ["stop", containerName], {
232
+ timeout: DOCKER_STOP_TIMEOUT
233
+ });
234
+ if (result.ok) {
235
+ return { ok: true };
236
+ }
237
+ if (result.stderr.includes("No such") || result.stderr.includes("not found") || result.stderr.includes("is not running")) {
238
+ return { ok: true };
239
+ }
240
+ return {
241
+ ok: false,
242
+ error: {
243
+ code: "CONTAINER_STOP_TIMEOUT",
244
+ message: `Failed to stop container '${containerName}': ${result.stderr}`,
245
+ suggestion: `Try manually: docker rm -f ${containerName}`
246
+ }
247
+ };
248
+ }
249
+ async function containerRemove(containerName) {
250
+ const result = await executor("docker", ["rm", containerName], {
251
+ timeout: DOCKER_RM_TIMEOUT
252
+ });
253
+ if (result.ok) {
254
+ return { ok: true };
255
+ }
256
+ if (result.stderr.includes("No such") || result.stderr.includes("not found")) {
257
+ return { ok: true };
258
+ }
259
+ return {
260
+ ok: false,
261
+ error: {
262
+ code: "CONTAINER_ERROR",
263
+ message: `Failed to remove container '${containerName}': ${result.stderr}`
264
+ }
265
+ };
266
+ }
267
+ return {
268
+ isDockerAvailable,
269
+ containerStatus,
270
+ getContainerNameById,
271
+ devcontainerUp,
272
+ containerStop,
273
+ containerRemove
274
+ };
275
+ }
276
+
277
+ // src/lib/create-instance.ts
278
+ import {
279
+ appendFile as appendFile2,
280
+ cp as cp2,
281
+ mkdir as mkdir4,
282
+ readdir as readdir3,
283
+ readFile as readFile3,
284
+ rename as rename2,
285
+ rm as rm2,
286
+ stat as stat3,
287
+ writeFile as writeFile3
288
+ } from "fs/promises";
289
+ import { homedir as homedir2 } from "os";
290
+ import { dirname as dirname2 } from "path";
291
+
292
+ // src/lib/devcontainer.ts
293
+ import { access, cp, mkdir, readdir, readFile, stat, writeFile } from "fs/promises";
294
+ import { dirname, join } from "path";
295
+ import { fileURLToPath } from "url";
296
+ var defaultFsDeps = { access, cp, mkdir, readdir, readFile, stat, writeFile };
297
+ var DEVCONTAINER_DIR = ".devcontainer";
298
+ var DEVCONTAINER_JSON = "devcontainer.json";
299
+ var DOT_DEVCONTAINER_JSON = ".devcontainer.json";
300
+ function getBaselineConfigPath() {
301
+ const currentFile = fileURLToPath(import.meta.url);
302
+ const packageRoot = dirname(dirname(dirname(currentFile)));
303
+ return join(packageRoot, "config", "baseline");
304
+ }
305
+ async function hasDevcontainerConfig(workspacePath, deps = defaultFsDeps) {
306
+ try {
307
+ const dirStats = await deps.stat(join(workspacePath, DEVCONTAINER_DIR));
308
+ if (dirStats.isDirectory()) {
309
+ return true;
310
+ }
311
+ } catch {
312
+ }
313
+ try {
314
+ const fileStats = await deps.stat(join(workspacePath, DEVCONTAINER_JSON));
315
+ if (fileStats.isFile()) {
316
+ return true;
317
+ }
318
+ } catch {
319
+ }
320
+ try {
321
+ const dotFileStats = await deps.stat(join(workspacePath, DOT_DEVCONTAINER_JSON));
322
+ if (dotFileStats.isFile()) {
323
+ return true;
324
+ }
325
+ } catch {
326
+ }
327
+ return false;
328
+ }
329
+ async function copyBaselineConfig(workspacePath, deps = defaultFsDeps) {
330
+ const baselinePath = getBaselineConfigPath();
331
+ try {
332
+ await deps.stat(baselinePath);
333
+ } catch {
334
+ throw new Error(`Baseline config not found at ${baselinePath}. Package may be corrupted.`);
335
+ }
336
+ const targetDir = join(workspacePath, DEVCONTAINER_DIR);
337
+ await deps.mkdir(targetDir, { recursive: true });
338
+ await deps.cp(baselinePath, targetDir, { recursive: true });
339
+ }
340
+ async function patchContainerName(workspacePath, containerName, deps = defaultFsDeps) {
341
+ const configPath = join(workspacePath, DEVCONTAINER_DIR, DEVCONTAINER_JSON);
342
+ const content = await deps.readFile(configPath, "utf-8");
343
+ const config = JSON.parse(content);
344
+ const existing = Array.isArray(config.runArgs) ? config.runArgs : [];
345
+ const filtered = existing.filter((arg) => !arg.startsWith("--name="));
346
+ config.runArgs = [...filtered, `--name=${containerName}`];
347
+ await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
348
+ }
349
+
350
+ // src/lib/state.ts
351
+ import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
352
+ import { join as join2 } from "path";
353
+
354
+ // src/lib/types.ts
355
+ var AGENT_ENV_DIR = ".agent-env";
356
+ var WORKSPACES_DIR = "workspaces";
357
+ var STATE_FILE = "state.json";
358
+ var STATE_FILE_TMP = "state.json.tmp";
359
+ var CONTAINER_PREFIX = "ae-";
360
+ function createFallbackState(workspaceName) {
361
+ return {
362
+ name: workspaceName,
363
+ repo: "unknown",
364
+ createdAt: "unknown",
365
+ lastAttached: "unknown",
366
+ purpose: null,
367
+ containerName: `${CONTAINER_PREFIX}${workspaceName}`
368
+ };
369
+ }
370
+
371
+ // src/lib/state.ts
372
+ var defaultStateFsDeps = { readFile: readFile2, writeFile: writeFile2, rename, mkdir: mkdir2, appendFile };
373
+ async function readState(wsPath, deps = defaultStateFsDeps) {
374
+ try {
375
+ const content = await deps.readFile(wsPath.stateFile, "utf-8");
376
+ const parsed = JSON.parse(content);
377
+ if (!isValidState(parsed)) {
378
+ return createFallbackState(wsPath.name);
379
+ }
380
+ return parsed;
381
+ } catch (err) {
382
+ if (err instanceof SyntaxError || err.code === "ENOENT") {
383
+ return createFallbackState(wsPath.name);
384
+ }
385
+ throw err;
386
+ }
387
+ }
388
+ async function writeStateAtomic(wsPath, state, deps = defaultStateFsDeps) {
389
+ const tmpPath = join2(wsPath.agentEnvDir, STATE_FILE_TMP);
390
+ await deps.mkdir(wsPath.agentEnvDir, { recursive: true });
391
+ const content = JSON.stringify(state, null, 2) + "\n";
392
+ await deps.writeFile(tmpPath, content, "utf-8");
393
+ await deps.rename(tmpPath, wsPath.stateFile);
394
+ }
395
+ function createInitialState(name, repo, containerName) {
396
+ const now = (/* @__PURE__ */ new Date()).toISOString();
397
+ return {
398
+ name,
399
+ repo,
400
+ createdAt: now,
401
+ lastAttached: now,
402
+ purpose: null,
403
+ containerName: containerName ?? `${CONTAINER_PREFIX}${name}`
404
+ };
405
+ }
406
+ function isValidState(value) {
407
+ if (typeof value !== "object" || value === null) return false;
408
+ const obj = value;
409
+ return typeof obj.name === "string" && typeof obj.repo === "string" && typeof obj.createdAt === "string" && typeof obj.lastAttached === "string" && (obj.purpose === null || typeof obj.purpose === "string") && typeof obj.containerName === "string";
410
+ }
411
+ var GIT_EXCLUDE_PATTERN = `${AGENT_ENV_DIR}/`;
412
+ async function ensureGitExclude(workspaceRoot, deps = defaultStateFsDeps) {
413
+ const excludePath = join2(workspaceRoot, ".git", "info", "exclude");
414
+ try {
415
+ const content = await deps.readFile(excludePath, "utf-8");
416
+ const lines = content.split("\n");
417
+ if (lines.some((line) => line.trim() === GIT_EXCLUDE_PATTERN)) {
418
+ return;
419
+ }
420
+ const prefix = content.endsWith("\n") ? "" : "\n";
421
+ await deps.appendFile(excludePath, `${prefix}${GIT_EXCLUDE_PATTERN}
422
+ `, "utf-8");
423
+ } catch (err) {
424
+ if (err.code === "ENOENT") {
425
+ return;
426
+ }
427
+ throw err;
428
+ }
429
+ }
430
+
431
+ // src/lib/workspace.ts
432
+ import { mkdir as mkdir3, readdir as readdir2, rm, stat as stat2 } from "fs/promises";
433
+ import { homedir } from "os";
434
+ import { join as join3 } from "path";
435
+ var defaultFsDeps2 = { mkdir: mkdir3, readdir: readdir2, stat: stat2, homedir };
436
+ var VALID_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
437
+ function validateNameSegment(value, label) {
438
+ if (!value) {
439
+ throw new Error(`${label} must not be empty`);
440
+ }
441
+ if (!VALID_NAME_PATTERN.test(value)) {
442
+ throw new Error(
443
+ `${label} contains invalid characters: "${value}". Only alphanumeric, dash, dot, and underscore are allowed (must start with alphanumeric).`
444
+ );
445
+ }
446
+ }
447
+ function getWorkspacesBaseDir(deps = defaultFsDeps2) {
448
+ return join3(deps.homedir(), AGENT_ENV_DIR, WORKSPACES_DIR);
449
+ }
450
+ function deriveWorkspaceName(repo, instance) {
451
+ validateNameSegment(repo, "repo");
452
+ validateNameSegment(instance, "instance");
453
+ return `${repo}-${instance}`;
454
+ }
455
+ function deriveContainerName(workspaceName) {
456
+ return `${CONTAINER_PREFIX}${workspaceName}`;
457
+ }
458
+ function getWorkspacePath(repo, instance, deps = defaultFsDeps2) {
459
+ const name = deriveWorkspaceName(repo, instance);
460
+ const root = join3(getWorkspacesBaseDir(deps), name);
461
+ const agentEnvDir = join3(root, AGENT_ENV_DIR);
462
+ const stateFile = join3(agentEnvDir, STATE_FILE);
463
+ return { root, name, agentEnvDir, stateFile };
464
+ }
465
+ function getWorkspacePathByName(workspaceName, deps = defaultFsDeps2) {
466
+ const root = join3(getWorkspacesBaseDir(deps), workspaceName);
467
+ const agentEnvDir = join3(root, AGENT_ENV_DIR);
468
+ const stateFile = join3(agentEnvDir, STATE_FILE);
469
+ return { root, name: workspaceName, agentEnvDir, stateFile };
470
+ }
471
+ async function workspaceExists(repo, instance, deps = defaultFsDeps2) {
472
+ const wsPath = getWorkspacePath(repo, instance, deps);
473
+ try {
474
+ const stats = await deps.stat(wsPath.root);
475
+ return stats.isDirectory();
476
+ } catch (err) {
477
+ if (err.code === "ENOENT") {
478
+ return false;
479
+ }
480
+ throw err;
481
+ }
482
+ }
483
+ async function scanWorkspaces(deps = defaultFsDeps2) {
484
+ const baseDir = getWorkspacesBaseDir(deps);
485
+ try {
486
+ const entries = await deps.readdir(baseDir, { withFileTypes: true });
487
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
488
+ } catch (err) {
489
+ if (err.code === "ENOENT") {
490
+ return [];
491
+ }
492
+ throw err;
493
+ }
494
+ }
495
+ var defaultDeleteFsDeps = { rm };
496
+ async function deleteWorkspace(wsPath, deps = defaultDeleteFsDeps) {
497
+ await deps.rm(wsPath.root, { recursive: true, force: true });
498
+ }
499
+
500
+ // src/lib/create-instance.ts
501
+ var GIT_CLONE_TIMEOUT = 12e4;
502
+ function extractRepoName(url) {
503
+ const cleaned = url.replace(/\/+$/, "").replace(/\.git$/, "");
504
+ const lastSlash = cleaned.lastIndexOf("/");
505
+ const lastColon = cleaned.lastIndexOf(":");
506
+ const lastSeparator = Math.max(lastSlash, lastColon);
507
+ if (lastSeparator === -1) {
508
+ if (!cleaned) {
509
+ throw new Error(`Cannot extract repository name from URL: ${url}`);
510
+ }
511
+ return cleaned;
512
+ }
513
+ const repoName = cleaned.slice(lastSeparator + 1);
514
+ if (!repoName) {
515
+ throw new Error(`Cannot extract repository name from URL: ${url}`);
516
+ }
517
+ return repoName;
518
+ }
519
+ async function resolveRepoUrl(repoArg, executor) {
520
+ if (repoArg !== ".") {
521
+ return { ok: true, url: repoArg };
522
+ }
523
+ const result = await executor("git", ["remote", "get-url", "origin"]);
524
+ if (!result.ok || !result.stdout.trim()) {
525
+ return {
526
+ ok: false,
527
+ error: {
528
+ code: "GIT_ERROR",
529
+ message: "No git remote found in current directory",
530
+ suggestion: 'Ensure you are in a git repository with an "origin" remote, or provide an explicit --repo URL.'
531
+ }
532
+ };
533
+ }
534
+ const url = result.stdout.trim();
535
+ return { ok: true, url };
536
+ }
537
+ async function attachToInstance(containerName, executor) {
538
+ const result = await executor(
539
+ "docker",
540
+ [
541
+ "exec",
542
+ "-it",
543
+ containerName,
544
+ "bash",
545
+ "-c",
546
+ "tmux attach-session -t main 2>/dev/null || tmux new-session -s main"
547
+ ],
548
+ { stdio: "inherit" }
549
+ );
550
+ if (!result.ok) {
551
+ const stderr = result.stderr.toLowerCase();
552
+ const isTmuxIssue = stderr.includes("tmux") || stderr.includes("command not found");
553
+ return {
554
+ ok: false,
555
+ error: {
556
+ code: "CONTAINER_ERROR",
557
+ message: isTmuxIssue ? `tmux is not available in container '${containerName}': ${result.stderr}` : `Failed to attach to container '${containerName}': ${result.stderr}`,
558
+ suggestion: isTmuxIssue ? "Ensure tmux is installed in the container image." : "Ensure the container is running. Use `agent-env list` to check status."
559
+ }
560
+ };
561
+ }
562
+ return { ok: true };
563
+ }
564
+ function createDefaultDeps() {
565
+ const executor = createExecutor();
566
+ return {
567
+ executor,
568
+ container: createContainerLifecycle(executor),
569
+ workspaceFsDeps: { mkdir: mkdir4, readdir: readdir3, stat: stat3, homedir: homedir2 },
570
+ stateFsDeps: { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
571
+ devcontainerFsDeps: { cp: cp2, mkdir: mkdir4, readFile: readFile3, stat: stat3, writeFile: writeFile3 },
572
+ rm: rm2
573
+ };
574
+ }
575
+ async function createInstance(instanceName, repoUrl, deps) {
576
+ let repoName;
577
+ try {
578
+ repoName = extractRepoName(repoUrl);
579
+ } catch {
580
+ return {
581
+ ok: false,
582
+ error: {
583
+ code: "GIT_ERROR",
584
+ message: `Invalid repository URL: ${repoUrl}`,
585
+ suggestion: "Provide a valid HTTPS or SSH git URL."
586
+ }
587
+ };
588
+ }
589
+ const wsPath = getWorkspacePath(repoName, instanceName, deps.workspaceFsDeps);
590
+ const containerName = deriveContainerName(wsPath.name);
591
+ const exists = await workspaceExists(repoName, instanceName, deps.workspaceFsDeps);
592
+ if (exists) {
593
+ return {
594
+ ok: false,
595
+ error: {
596
+ code: "INSTANCE_EXISTS",
597
+ message: `Instance '${instanceName}' already exists for repo '${repoName}'`,
598
+ suggestion: `Choose a different instance name or remove the existing one first.`
599
+ }
600
+ };
601
+ }
602
+ try {
603
+ await deps.workspaceFsDeps.mkdir(dirname2(wsPath.root), { recursive: true });
604
+ } catch (err) {
605
+ return {
606
+ ok: false,
607
+ error: {
608
+ code: "WORKSPACE_ERROR",
609
+ message: `Failed to create workspace directory: ${err instanceof Error ? err.message : String(err)}`,
610
+ suggestion: "Check filesystem permissions for the ~/.agent-env directory."
611
+ }
612
+ };
613
+ }
614
+ const cloneResult = await deps.executor("git", ["clone", repoUrl, wsPath.root], {
615
+ timeout: GIT_CLONE_TIMEOUT
616
+ });
617
+ if (!cloneResult.ok) {
618
+ await safeRollback(wsPath.root, deps.rm);
619
+ return {
620
+ ok: false,
621
+ error: {
622
+ code: "GIT_ERROR",
623
+ message: `Git clone failed: ${cloneResult.stderr}`,
624
+ suggestion: "Check the repository URL and your access permissions."
625
+ }
626
+ };
627
+ }
628
+ try {
629
+ await deps.workspaceFsDeps.mkdir(wsPath.agentEnvDir, { recursive: true });
630
+ } catch (err) {
631
+ await safeRollback(wsPath.root, deps.rm);
632
+ return {
633
+ ok: false,
634
+ error: {
635
+ code: "WORKSPACE_ERROR",
636
+ message: `Failed to create .agent-env directory: ${err instanceof Error ? err.message : String(err)}`,
637
+ suggestion: "Check filesystem permissions in the cloned workspace directory."
638
+ }
639
+ };
640
+ }
641
+ const hasConfig = await hasDevcontainerConfig(wsPath.root, deps.devcontainerFsDeps);
642
+ if (!hasConfig) {
643
+ try {
644
+ await copyBaselineConfig(wsPath.root, deps.devcontainerFsDeps);
645
+ } catch (err) {
646
+ await safeRollback(wsPath.root, deps.rm);
647
+ return {
648
+ ok: false,
649
+ error: {
650
+ code: "CONTAINER_ERROR",
651
+ message: `Failed to copy baseline devcontainer config: ${err instanceof Error ? err.message : String(err)}`
652
+ }
653
+ };
654
+ }
655
+ try {
656
+ await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps);
657
+ } catch (err) {
658
+ await safeRollback(wsPath.root, deps.rm);
659
+ return {
660
+ ok: false,
661
+ error: {
662
+ code: "CONTAINER_ERROR",
663
+ message: `Failed to patch devcontainer.json with container name: ${err instanceof Error ? err.message : String(err)}`
664
+ }
665
+ };
666
+ }
667
+ }
668
+ const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName);
669
+ if (!containerResult.ok) {
670
+ await safeRollback(wsPath.root, deps.rm);
671
+ return {
672
+ ok: false,
673
+ error: containerResult.error ?? {
674
+ code: "CONTAINER_ERROR",
675
+ message: "Container startup failed for unknown reason."
676
+ }
677
+ };
678
+ }
679
+ let actualContainerName = containerName;
680
+ if (containerResult.containerId) {
681
+ const discovered = await deps.container.getContainerNameById(containerResult.containerId);
682
+ if (discovered) {
683
+ actualContainerName = discovered;
684
+ }
685
+ } else {
686
+ console.warn(
687
+ `Warning: devcontainer started successfully but no containerId returned. Using derived name '${containerName}'.`
688
+ );
689
+ }
690
+ const state = createInitialState(wsPath.name, repoUrl, actualContainerName);
691
+ await writeStateAtomic(wsPath, state, deps.stateFsDeps);
692
+ await ensureGitExclude(wsPath.root, deps.stateFsDeps);
693
+ return {
694
+ ok: true,
695
+ workspacePath: wsPath,
696
+ containerName: actualContainerName
697
+ };
698
+ }
699
+ async function safeRollback(workspacePath, rmFn) {
700
+ try {
701
+ await rmFn(workspacePath, { recursive: true, force: true });
702
+ } catch {
703
+ console.warn(`Warning: Failed to clean up workspace at ${workspacePath}`);
704
+ }
705
+ }
706
+
707
+ // src/lib/attach-instance.ts
708
+ function createAttachDefaultDeps() {
709
+ const executor = createExecutor();
710
+ return {
711
+ executor,
712
+ container: createContainerLifecycle(executor),
713
+ workspaceFsDeps: { mkdir: mkdir5, readdir: readdir4, stat: stat4, homedir: homedir3 },
714
+ stateFsDeps: { readFile: readFile4, writeFile: writeFile4, rename: rename3, mkdir: mkdir5, appendFile: appendFile3 }
715
+ };
716
+ }
717
+ async function findWorkspaceByName(instanceName, deps) {
718
+ const workspaces = await scanWorkspaces(deps);
719
+ if (workspaces.includes(instanceName)) {
720
+ return { found: true, workspaceName: instanceName };
721
+ }
722
+ const suffixMatches = workspaces.filter((ws) => ws.endsWith(`-${instanceName}`));
723
+ if (suffixMatches.length === 1) {
724
+ return { found: true, workspaceName: suffixMatches[0] };
725
+ }
726
+ if (suffixMatches.length > 1) {
727
+ return { found: false, reason: "ambiguous", matches: suffixMatches };
728
+ }
729
+ return { found: false, reason: "not-found" };
730
+ }
731
+ async function attachInstance(instanceName, deps, onContainerStarting, onAttaching) {
732
+ const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
733
+ if (!lookup.found) {
734
+ if (lookup.reason === "ambiguous") {
735
+ return {
736
+ ok: false,
737
+ error: {
738
+ code: "AMBIGUOUS_MATCH",
739
+ message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
740
+ suggestion: "Use the full workspace name to specify which instance."
741
+ }
742
+ };
743
+ }
744
+ return {
745
+ ok: false,
746
+ error: {
747
+ code: "WORKSPACE_NOT_FOUND",
748
+ message: `Instance '${instanceName}' not found`,
749
+ suggestion: "Use `agent-env list` to see available instances."
750
+ }
751
+ };
752
+ }
753
+ const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
754
+ const state = await readState(wsPath, deps.stateFsDeps);
755
+ const containerName = state.containerName;
756
+ const dockerAvailable = await deps.container.isDockerAvailable();
757
+ if (!dockerAvailable) {
758
+ return {
759
+ ok: false,
760
+ error: {
761
+ code: "ORBSTACK_REQUIRED",
762
+ message: "Docker is not available. OrbStack or Docker Desktop must be running.",
763
+ suggestion: "Start OrbStack or Docker Desktop, then try again."
764
+ }
765
+ };
766
+ }
767
+ const statusResult = await deps.container.containerStatus(containerName);
768
+ if (!statusResult.ok) {
769
+ return {
770
+ ok: false,
771
+ error: statusResult.error ?? {
772
+ code: "CONTAINER_ERROR",
773
+ message: `Failed to check container status for '${containerName}'.`
774
+ }
775
+ };
776
+ }
777
+ if (statusResult.status === "stopped" || statusResult.status === "not-found") {
778
+ onContainerStarting?.();
779
+ const startResult = await deps.container.devcontainerUp(wsPath.root, containerName);
780
+ if (!startResult.ok) {
781
+ return {
782
+ ok: false,
783
+ error: startResult.error ?? {
784
+ code: "CONTAINER_ERROR",
785
+ message: `Failed to start container '${containerName}'.`,
786
+ suggestion: "Check Docker logs for details."
787
+ }
788
+ };
789
+ }
790
+ }
791
+ onAttaching?.();
792
+ const attachResult = await attachToInstance(containerName, deps.executor);
793
+ if (!attachResult.ok) {
794
+ return attachResult;
795
+ }
796
+ const updatedState = {
797
+ ...state,
798
+ lastAttached: (/* @__PURE__ */ new Date()).toISOString()
799
+ };
800
+ await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
801
+ return { ok: true };
802
+ }
803
+
804
+ // src/commands/attach.ts
805
+ var attachCommand = new Command("attach").description("Attach to an instance's tmux session").argument("<name>", "Instance name to attach to").action(async (name) => {
806
+ const deps = createAttachDefaultDeps();
807
+ const result = await attachInstance(
808
+ name,
809
+ deps,
810
+ () => {
811
+ console.log("Starting container...");
812
+ },
813
+ () => {
814
+ console.log();
815
+ console.log("Attaching to tmux session...");
816
+ }
817
+ );
818
+ if (!result.ok) {
819
+ const { code, message, suggestion } = result.error;
820
+ console.error(formatError(createError(code, message, suggestion)));
821
+ process.exit(1);
822
+ }
823
+ });
824
+
825
+ // src/commands/completion.ts
826
+ import { Command as Command2 } from "commander";
827
+
828
+ // src/lib/completion.ts
829
+ var COMMANDS = ["create", "list", "ps", "attach", "remove", "purpose", "completion"];
830
+ var INSTANCE_COMMANDS = ["attach", "purpose"];
831
+ function generateCompletionScript(shell) {
832
+ switch (shell) {
833
+ case "bash":
834
+ return generateBashCompletion();
835
+ case "zsh":
836
+ return generateZshCompletion();
837
+ }
838
+ }
839
+ function isValidShell(shell) {
840
+ return shell === "bash" || shell === "zsh";
841
+ }
842
+ function getInstallInstructions() {
843
+ return `Shell Completion Installation:
844
+
845
+ Bash:
846
+ # Add to ~/.bashrc:
847
+ eval "$(agent-env completion bash)"
848
+
849
+ # Or save to a file:
850
+ agent-env completion bash > /etc/bash_completion.d/agent-env
851
+
852
+ Zsh:
853
+ # Add to ~/.zshrc:
854
+ eval "$(agent-env completion zsh)"
855
+
856
+ # Or save to a file (ensure fpath includes the directory):
857
+ agent-env completion zsh > ~/.zsh/completions/_agent-env`;
858
+ }
859
+ function generateBashCompletion() {
860
+ const commandList = COMMANDS.join(" ");
861
+ const instanceCommandList = INSTANCE_COMMANDS.join("|");
862
+ return `#!/usr/bin/env bash
863
+ # agent-env bash completion script
864
+ # Install: eval "$(agent-env completion bash)"
865
+
866
+ _agent_env_instances() {
867
+ local ws_dir=~/.agent-env/workspaces
868
+ if [[ -d "\${ws_dir}" ]]; then
869
+ ls "\${ws_dir}" 2>/dev/null
870
+ fi
871
+ }
872
+
873
+ _agent_env_completions() {
874
+ local cur prev commands
875
+ cur="\${COMP_WORDS[COMP_CWORD]}"
876
+ prev="\${COMP_WORDS[COMP_CWORD-1]}"
877
+ commands="${commandList}"
878
+
879
+ # Complete commands at position 1
880
+ if [[ \${COMP_CWORD} -eq 1 ]]; then
881
+ COMPREPLY=($(compgen -W "\${commands}" -- "\${cur}"))
882
+ return 0
883
+ fi
884
+
885
+ # Complete based on command
886
+ case "\${prev}" in
887
+ ${instanceCommandList})
888
+ COMPREPLY=($(compgen -W "$(_agent_env_instances)" -- "\${cur}"))
889
+ return 0
890
+ ;;
891
+ create)
892
+ COMPREPLY=($(compgen -W "--repo --attach" -- "\${cur}"))
893
+ return 0
894
+ ;;
895
+ list|ps)
896
+ COMPREPLY=($(compgen -W "--json" -- "\${cur}"))
897
+ return 0
898
+ ;;
899
+ remove)
900
+ local instances
901
+ instances="$(_agent_env_instances)"
902
+ COMPREPLY=($(compgen -W "--force \${instances}" -- "\${cur}"))
903
+ return 0
904
+ ;;
905
+ completion)
906
+ COMPREPLY=($(compgen -W "bash zsh" -- "\${cur}"))
907
+ return 0
908
+ ;;
909
+ esac
910
+
911
+ return 0
912
+ }
913
+
914
+ complete -F _agent_env_completions agent-env`;
915
+ }
916
+ function generateZshCompletion() {
917
+ const commandDescriptions = [
918
+ "create:Create a new instance",
919
+ "list:List all instances",
920
+ "ps:List all instances (alias)",
921
+ "attach:Attach to an instance tmux session",
922
+ "remove:Remove an instance",
923
+ "purpose:Get or set instance purpose",
924
+ "completion:Generate shell completion script"
925
+ ];
926
+ return `#compdef agent-env
927
+ # agent-env zsh completion script
928
+ # Install: eval "$(agent-env completion zsh)"
929
+
930
+ _agent_env_instances() {
931
+ local ws_dir=~/.agent-env/workspaces
932
+ local -a instances
933
+ if [[ -d "\${ws_dir}" ]]; then
934
+ instances=(\${(f)"$(ls "\${ws_dir}" 2>/dev/null)"})
935
+ fi
936
+ _describe 'instance' instances
937
+ }
938
+
939
+ _agent_env() {
940
+ local -a commands
941
+ commands=(
942
+ ${commandDescriptions.map((desc) => ` '${desc}'`).join("\n")}
943
+ )
944
+
945
+ _arguments -C \\
946
+ '--help[Show help]' \\
947
+ '--version[Show version]' \\
948
+ '1:command:->command' \\
949
+ '*::arg:->args'
950
+
951
+ case $state in
952
+ command)
953
+ _describe 'command' commands
954
+ ;;
955
+ args)
956
+ case $words[1] in
957
+ attach|purpose)
958
+ _agent_env_instances
959
+ ;;
960
+ create)
961
+ _arguments \\
962
+ '--repo[Repository URL]:url:' \\
963
+ '--attach[Attach after creation]'
964
+ ;;
965
+ list|ps)
966
+ _arguments \\
967
+ '--json[Output as JSON]'
968
+ ;;
969
+ remove)
970
+ _arguments \\
971
+ '--force[Force removal]' \\
972
+ '1:instance:_agent_env_instances'
973
+ ;;
974
+ completion)
975
+ _describe 'shell' '(bash zsh)'
976
+ ;;
977
+ esac
978
+ ;;
979
+ esac
980
+ }
981
+
982
+ _agent_env`;
983
+ }
984
+
985
+ // src/commands/completion.ts
986
+ var completionCommand = new Command2("completion").description(`Generate shell completion script for bash or zsh
987
+
988
+ ${getInstallInstructions()}`).argument("<shell>", "Shell type (bash or zsh)").action((shell) => {
989
+ if (!isValidShell(shell)) {
990
+ const error = createError(
991
+ "UNSUPPORTED_SHELL",
992
+ `Unsupported shell "${shell}".`,
993
+ "Supported shells: bash, zsh"
994
+ );
995
+ console.error(formatError(error));
996
+ process.exit(1);
997
+ }
998
+ const script = generateCompletionScript(shell);
999
+ console.log(script);
1000
+ });
1001
+
1002
+ // src/commands/create.ts
1003
+ import { Command as Command3 } from "commander";
1004
+ var createCommand = new Command3("create").description("Create a new isolated development environment").argument("<name>", "Name for the new instance").option("--repo <url>", 'Git repository URL to clone (use "." for current directory)').option("--attach", "Attach immediately after creation").action(async (name, options) => {
1005
+ if (!options.repo) {
1006
+ console.error(
1007
+ formatError(
1008
+ createError(
1009
+ "MISSING_OPTION",
1010
+ "The --repo flag is required.",
1011
+ "Usage: agent-env create <name> --repo <url>"
1012
+ )
1013
+ )
1014
+ );
1015
+ process.exit(1);
1016
+ }
1017
+ const deps = createDefaultDeps();
1018
+ const resolved = await resolveRepoUrl(options.repo, deps.executor);
1019
+ if (!resolved.ok) {
1020
+ const { code, message, suggestion } = resolved.error;
1021
+ console.error(formatError(createError(code, message, suggestion)));
1022
+ process.exit(1);
1023
+ }
1024
+ const repoUrl = resolved.url;
1025
+ console.log(`Creating instance '${name}' from ${repoUrl}...`);
1026
+ const result = await createInstance(name, repoUrl, deps);
1027
+ if (!result.ok) {
1028
+ const { code, message, suggestion } = result.error;
1029
+ console.error(formatError(createError(code, message, suggestion)));
1030
+ process.exit(1);
1031
+ }
1032
+ const { workspacePath, containerName } = result;
1033
+ console.log(`\x1B[32m\u2713\x1B[0m Instance '${name}' created successfully`);
1034
+ console.log(` Workspace: ${workspacePath.root}`);
1035
+ console.log(` Container: ${containerName}`);
1036
+ if (options.attach) {
1037
+ console.log();
1038
+ console.log("Attaching to instance...");
1039
+ const attachResult = await attachToInstance(containerName, deps.executor);
1040
+ if (!attachResult.ok) {
1041
+ const { code, message, suggestion } = attachResult.error;
1042
+ console.error(formatError(createError(code, message, suggestion)));
1043
+ process.exit(1);
1044
+ }
1045
+ }
1046
+ });
1047
+
1048
+ // src/commands/list.ts
1049
+ import { Command as Command4 } from "commander";
1050
+ import { render } from "ink";
1051
+ import React from "react";
1052
+
1053
+ // src/components/InstanceList.tsx
1054
+ import { Box, Text as Text2 } from "ink";
1055
+ import { format as timeago } from "timeago.js";
1056
+
1057
+ // src/components/StatusIndicator.tsx
1058
+ import { Text } from "ink";
1059
+ import { jsx, jsxs } from "react/jsx-runtime";
1060
+ function formatGitIndicators(gitState) {
1061
+ if (!gitState || !gitState.ok) {
1062
+ return [{ symbol: "?", color: "gray" }];
1063
+ }
1064
+ const state = gitState.state;
1065
+ if (state.isClean) {
1066
+ return [{ symbol: "\u2713", color: "green" }];
1067
+ }
1068
+ const indicators = [];
1069
+ if (state.hasStaged || state.hasUnstaged || state.hasUntracked) {
1070
+ indicators.push({ symbol: "\u25CF", color: "yellow" });
1071
+ }
1072
+ if (state.unpushedBranches.length > 0) {
1073
+ indicators.push({ symbol: "\u2191", color: "blue" });
1074
+ }
1075
+ if (state.neverPushedBranches.length > 0) {
1076
+ indicators.push({
1077
+ symbol: `\u26A0 ${state.neverPushedBranches.length}`,
1078
+ color: "red"
1079
+ });
1080
+ }
1081
+ if (indicators.length === 0) {
1082
+ indicators.push({ symbol: "\u25CF", color: "yellow" });
1083
+ }
1084
+ return indicators;
1085
+ }
1086
+
1087
+ // src/components/InstanceList.tsx
1088
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
1089
+ function statusColor(status) {
1090
+ switch (status) {
1091
+ case "running":
1092
+ return "green";
1093
+ case "stopped":
1094
+ return "yellow";
1095
+ case "orphaned":
1096
+ return "red";
1097
+ case "unknown":
1098
+ return "gray";
1099
+ case "not-found":
1100
+ return "red";
1101
+ }
1102
+ }
1103
+ function statusLabel(status, dockerAvailable) {
1104
+ if (!dockerAvailable && status === "unknown") {
1105
+ return "unknown (Docker unavailable)";
1106
+ }
1107
+ return status;
1108
+ }
1109
+ function formatLastAttached(lastAttached) {
1110
+ if (!lastAttached) return "-";
1111
+ try {
1112
+ return timeago(lastAttached);
1113
+ } catch {
1114
+ return "-";
1115
+ }
1116
+ }
1117
+ function formatPurpose(purpose) {
1118
+ if (!purpose) return "-";
1119
+ if (purpose.length > 30) {
1120
+ return purpose.slice(0, 27) + "...";
1121
+ }
1122
+ return purpose;
1123
+ }
1124
+ function InstanceList({
1125
+ instances,
1126
+ dockerAvailable
1127
+ }) {
1128
+ if (instances.length === 0) {
1129
+ return /* @__PURE__ */ jsxs2(Box, { flexDirection: "column", children: [
1130
+ /* @__PURE__ */ jsx2(Text2, { children: "No instances found." }),
1131
+ /* @__PURE__ */ jsxs2(Text2, { color: "gray", children: [
1132
+ "Create one with: agent-env create ",
1133
+ "<name>",
1134
+ " --repo ",
1135
+ "<url>"
1136
+ ] })
1137
+ ] });
1138
+ }
1139
+ const augmentedInstances = instances.map((instance) => {
1140
+ const indicators = formatGitIndicators(instance.gitState);
1141
+ const indicatorText = indicators.map((ind) => ind.symbol).join(" ");
1142
+ return { ...instance, indicators, indicatorText };
1143
+ });
1144
+ const nameWidth = Math.max(4, ...augmentedInstances.map((i) => i.name.length)) + 2;
1145
+ const statusWidth = Math.max(6, ...augmentedInstances.map((i) => statusLabel(i.status, dockerAvailable).length)) + 2;
1146
+ const gitWidth = Math.max(3, ...augmentedInstances.map((i) => i.indicatorText.length)) + 2;
1147
+ const lastAttachedWidth = Math.max(13, ...augmentedInstances.map((i) => formatLastAttached(i.lastAttached).length)) + 2;
1148
+ return /* @__PURE__ */ jsxs2(Box, { flexDirection: "column", children: [
1149
+ /* @__PURE__ */ jsxs2(Box, { children: [
1150
+ /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("NAME", nameWidth) }),
1151
+ /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("STATUS", statusWidth) }),
1152
+ /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("GIT", gitWidth) }),
1153
+ /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("LAST ATTACHED", lastAttachedWidth) }),
1154
+ /* @__PURE__ */ jsx2(Text2, { bold: true, children: "PURPOSE" })
1155
+ ] }),
1156
+ augmentedInstances.map((instance) => /* @__PURE__ */ jsxs2(Box, { children: [
1157
+ /* @__PURE__ */ jsx2(Text2, { children: pad(instance.name, nameWidth) }),
1158
+ /* @__PURE__ */ jsx2(Text2, { color: statusColor(instance.status), children: pad(statusLabel(instance.status, dockerAvailable), statusWidth) }),
1159
+ /* @__PURE__ */ jsx2(Box, { width: gitWidth, children: instance.indicators.map((ind, idx) => /* @__PURE__ */ jsxs2(Text2, { color: ind.color, children: [
1160
+ idx > 0 ? " " : "",
1161
+ ind.symbol
1162
+ ] }, idx)) }),
1163
+ /* @__PURE__ */ jsx2(Text2, { children: pad(formatLastAttached(instance.lastAttached), lastAttachedWidth) }),
1164
+ /* @__PURE__ */ jsx2(Text2, { color: "gray", children: formatPurpose(instance.purpose) })
1165
+ ] }, instance.name)),
1166
+ !dockerAvailable && /* @__PURE__ */ jsx2(Box, { marginTop: 1, children: /* @__PURE__ */ jsx2(Text2, { color: "yellow", children: "\u26A0 Docker is not available. Container status cannot be determined." }) })
1167
+ ] });
1168
+ }
1169
+ function pad(str, width) {
1170
+ return str.padEnd(width);
1171
+ }
1172
+
1173
+ // src/lib/git.ts
1174
+ var GIT_COMMAND_TIMEOUT = 5e3;
1175
+ function createGitStateDetector(executor = createExecutor()) {
1176
+ async function getGitState(workspacePath) {
1177
+ const makeOpts = () => ({ timeout: GIT_COMMAND_TIMEOUT, cwd: workspacePath });
1178
+ const [statusResult, stashResult, branchResult, headResult] = await Promise.allSettled([
1179
+ executor("git", ["status", "--porcelain"], makeOpts()),
1180
+ executor("git", ["stash", "list"], makeOpts()),
1181
+ executor(
1182
+ "git",
1183
+ [
1184
+ "for-each-ref",
1185
+ "--format=%(refname:short) %(upstream:short) %(upstream:track)",
1186
+ "refs/heads"
1187
+ ],
1188
+ makeOpts()
1189
+ ),
1190
+ executor("git", ["symbolic-ref", "HEAD"], makeOpts())
1191
+ ]);
1192
+ const status = statusResult.status === "fulfilled" ? statusResult.value : null;
1193
+ const stash = stashResult.status === "fulfilled" ? stashResult.value : null;
1194
+ const branch = branchResult.status === "fulfilled" ? branchResult.value : null;
1195
+ const head = headResult.status === "fulfilled" ? headResult.value : null;
1196
+ if (!status || !status.ok) {
1197
+ const stderr = status?.stderr ?? "git status command failed";
1198
+ return {
1199
+ ok: false,
1200
+ state: null,
1201
+ error: {
1202
+ code: "GIT_ERROR",
1203
+ message: `Failed to read git status: ${stderr}`
1204
+ }
1205
+ };
1206
+ }
1207
+ const { hasStaged, stagedCount, hasUnstaged, unstagedCount, hasUntracked, untrackedCount } = parseStatus(status.stdout);
1208
+ const { stashCount, firstStashMessage } = parseStash(stash);
1209
+ const { unpushedBranches, unpushedCommitCounts, neverPushedBranches } = parseBranches(branch);
1210
+ const isDetachedHead = !head || !head.ok;
1211
+ const isClean = !hasStaged && !hasUnstaged && !hasUntracked && stashCount === 0 && unpushedBranches.length === 0 && neverPushedBranches.length === 0 && !isDetachedHead;
1212
+ const state = {
1213
+ hasStaged,
1214
+ stagedCount,
1215
+ hasUnstaged,
1216
+ unstagedCount,
1217
+ hasUntracked,
1218
+ untrackedCount,
1219
+ stashCount,
1220
+ firstStashMessage,
1221
+ unpushedBranches,
1222
+ unpushedCommitCounts,
1223
+ neverPushedBranches,
1224
+ isDetachedHead,
1225
+ isClean
1226
+ };
1227
+ return { ok: true, state };
1228
+ }
1229
+ return { getGitState };
1230
+ }
1231
+ function parseStatus(stdout) {
1232
+ let stagedCount = 0;
1233
+ let unstagedCount = 0;
1234
+ let untrackedCount = 0;
1235
+ if (!stdout.trim()) {
1236
+ return {
1237
+ hasStaged: false,
1238
+ stagedCount: 0,
1239
+ hasUnstaged: false,
1240
+ unstagedCount: 0,
1241
+ hasUntracked: false,
1242
+ untrackedCount: 0
1243
+ };
1244
+ }
1245
+ for (const line of stdout.split("\n")) {
1246
+ if (!line || line.length < 2) continue;
1247
+ if (line.startsWith("??")) {
1248
+ untrackedCount++;
1249
+ continue;
1250
+ }
1251
+ if (line.startsWith("!!")) {
1252
+ continue;
1253
+ }
1254
+ const indexStatus = line[0];
1255
+ const workTreeStatus = line[1];
1256
+ if ("MADRC".includes(indexStatus)) {
1257
+ stagedCount++;
1258
+ }
1259
+ if (workTreeStatus !== " ") {
1260
+ unstagedCount++;
1261
+ }
1262
+ }
1263
+ return {
1264
+ hasStaged: stagedCount > 0,
1265
+ stagedCount,
1266
+ hasUnstaged: unstagedCount > 0,
1267
+ unstagedCount,
1268
+ hasUntracked: untrackedCount > 0,
1269
+ untrackedCount
1270
+ };
1271
+ }
1272
+ function parseStash(result) {
1273
+ if (!result || !result.ok || !result.stdout.trim()) {
1274
+ return { stashCount: 0, firstStashMessage: "" };
1275
+ }
1276
+ const lines = result.stdout.trim().split("\n");
1277
+ let firstStashMessage = "";
1278
+ if (lines[0]) {
1279
+ const colonIndex = lines[0].indexOf(": ");
1280
+ firstStashMessage = colonIndex !== -1 ? lines[0].slice(colonIndex + 2) : lines[0];
1281
+ }
1282
+ return { stashCount: lines.length, firstStashMessage };
1283
+ }
1284
+ function parseBranches(result) {
1285
+ const unpushedBranches = [];
1286
+ const unpushedCommitCounts = {};
1287
+ const neverPushedBranches = [];
1288
+ if (!result || !result.ok || !result.stdout.trim()) {
1289
+ return { unpushedBranches, unpushedCommitCounts, neverPushedBranches };
1290
+ }
1291
+ for (const line of result.stdout.trim().split("\n")) {
1292
+ if (!line.trim()) continue;
1293
+ const parts = line.split(" ").filter(Boolean);
1294
+ const branchName = parts[0];
1295
+ const trackInfo = parts.slice(1).join(" ");
1296
+ if (parts.length === 1) {
1297
+ neverPushedBranches.push(branchName);
1298
+ } else if (trackInfo.includes("[ahead")) {
1299
+ const aheadMatch = trackInfo.match(/\[ahead (\d+)/);
1300
+ const count = aheadMatch ? parseInt(aheadMatch[1], 10) : 0;
1301
+ unpushedBranches.push(branchName);
1302
+ unpushedCommitCounts[branchName] = count;
1303
+ }
1304
+ }
1305
+ return { unpushedBranches, unpushedCommitCounts, neverPushedBranches };
1306
+ }
1307
+
1308
+ // src/lib/list-instances.ts
1309
+ async function listInstances(deps) {
1310
+ try {
1311
+ const container = deps?.container ?? createContainerLifecycle();
1312
+ const gitDetector = deps?.gitDetector ?? createGitStateDetector();
1313
+ const wsFsDeps = deps?.workspaceFsDeps;
1314
+ const stateFsDeps = deps?.stateFsDeps;
1315
+ const workspaceNames = await scanWorkspaces(wsFsDeps);
1316
+ if (workspaceNames.length === 0) {
1317
+ return { ok: true, instances: [], dockerAvailable: true };
1318
+ }
1319
+ const dockerAvailable = await container.isDockerAvailable();
1320
+ const instancePromises = workspaceNames.map(async (wsName) => {
1321
+ const wsPath = getWorkspacePathByName(wsName, wsFsDeps);
1322
+ const state = await readState(wsPath, stateFsDeps);
1323
+ const containerPromise = dockerAvailable ? container.containerStatus(state.containerName) : Promise.resolve(null);
1324
+ const gitPromise = gitDetector.getGitState(wsPath.root);
1325
+ const [containerResult, gitState] = await Promise.all([containerPromise, gitPromise]);
1326
+ let status;
1327
+ if (!dockerAvailable || containerResult === null) {
1328
+ status = "unknown";
1329
+ } else if (!containerResult.ok) {
1330
+ status = "unknown";
1331
+ } else if (containerResult.status === "not-found") {
1332
+ status = "orphaned";
1333
+ } else {
1334
+ status = containerResult.status;
1335
+ }
1336
+ return {
1337
+ name: wsName,
1338
+ status,
1339
+ lastAttached: state.lastAttached !== "unknown" ? state.lastAttached : null,
1340
+ purpose: state.purpose,
1341
+ gitState
1342
+ };
1343
+ });
1344
+ const instances = await Promise.all(instancePromises);
1345
+ return { ok: true, instances, dockerAvailable };
1346
+ } catch (err) {
1347
+ const message = err instanceof Error ? err.message : String(err);
1348
+ return {
1349
+ ok: false,
1350
+ instances: null,
1351
+ dockerAvailable: null,
1352
+ error: { code: "LIST_ERROR", message: `Failed to list instances: ${message}` }
1353
+ };
1354
+ }
1355
+ }
1356
+
1357
+ // src/commands/list.ts
1358
+ var listCommand = new Command4("list").alias("ps").description("List all instances with status").option("--json", "Output in JSON format").action(async (options) => {
1359
+ const result = await listInstances();
1360
+ if (!result.ok) {
1361
+ const error = createError(
1362
+ result.error.code,
1363
+ result.error.message,
1364
+ "Check if ~/.agent-env/workspaces/ is accessible."
1365
+ );
1366
+ if (options.json) {
1367
+ const output = {
1368
+ ok: false,
1369
+ data: null,
1370
+ error: { code: error.code, message: error.message, suggestion: error.suggestion }
1371
+ };
1372
+ console.log(JSON.stringify(output, null, 2));
1373
+ } else {
1374
+ console.error(formatError(error));
1375
+ }
1376
+ process.exitCode = 1;
1377
+ return;
1378
+ }
1379
+ if (options.json) {
1380
+ const output = {
1381
+ ok: true,
1382
+ data: result.instances.map((i) => ({
1383
+ name: i.name,
1384
+ status: i.status,
1385
+ lastAttached: i.lastAttached,
1386
+ purpose: i.purpose,
1387
+ gitState: i.gitState
1388
+ })),
1389
+ error: null
1390
+ };
1391
+ console.log(JSON.stringify(output, null, 2));
1392
+ return;
1393
+ }
1394
+ const { unmount, waitUntilExit } = render(
1395
+ React.createElement(InstanceList, {
1396
+ instances: result.instances,
1397
+ dockerAvailable: result.dockerAvailable
1398
+ })
1399
+ );
1400
+ unmount();
1401
+ await waitUntilExit();
1402
+ });
1403
+
1404
+ // src/commands/purpose.ts
1405
+ import { Command as Command5 } from "commander";
1406
+
1407
+ // src/lib/purpose-instance.ts
1408
+ import { appendFile as appendFile4, mkdir as mkdir6, readdir as readdir5, readFile as readFile5, rename as rename4, stat as stat5, writeFile as writeFile5 } from "fs/promises";
1409
+ import { homedir as homedir4 } from "os";
1410
+ function createPurposeDefaultDeps() {
1411
+ return {
1412
+ workspaceFsDeps: { mkdir: mkdir6, readdir: readdir5, stat: stat5, homedir: homedir4 },
1413
+ stateFsDeps: { readFile: readFile5, writeFile: writeFile5, rename: rename4, mkdir: mkdir6, appendFile: appendFile4 }
1414
+ };
1415
+ }
1416
+ function mapLookupError(lookup, instanceName) {
1417
+ if (lookup.reason === "ambiguous") {
1418
+ return {
1419
+ ok: false,
1420
+ error: {
1421
+ code: "AMBIGUOUS_MATCH",
1422
+ message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
1423
+ suggestion: "Use the full workspace name to specify which instance."
1424
+ }
1425
+ };
1426
+ }
1427
+ return {
1428
+ ok: false,
1429
+ error: {
1430
+ code: "WORKSPACE_NOT_FOUND",
1431
+ message: `Instance '${instanceName}' not found`,
1432
+ suggestion: "Use `agent-env list` to see available instances."
1433
+ }
1434
+ };
1435
+ }
1436
+ async function getPurpose(instanceName, deps) {
1437
+ const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1438
+ if (!lookup.found) {
1439
+ return mapLookupError(lookup, instanceName);
1440
+ }
1441
+ const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1442
+ const state = await readState(wsPath, deps.stateFsDeps);
1443
+ return { ok: true, purpose: state.purpose };
1444
+ }
1445
+ async function setPurpose(instanceName, value, deps) {
1446
+ const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1447
+ if (!lookup.found) {
1448
+ return mapLookupError(lookup, instanceName);
1449
+ }
1450
+ const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1451
+ const state = await readState(wsPath, deps.stateFsDeps);
1452
+ const cleared = value === "";
1453
+ const updatedState = {
1454
+ ...state,
1455
+ purpose: cleared ? null : value
1456
+ };
1457
+ await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
1458
+ return { ok: true, cleared };
1459
+ }
1460
+
1461
+ // src/commands/purpose.ts
1462
+ var purposeCommand = new Command5("purpose").description("Get or set the purpose/label for an instance").argument("<name>", "Instance name").argument("[value]", "New purpose value (omit to get current, empty string to clear)").action(async (name, value) => {
1463
+ const deps = createPurposeDefaultDeps();
1464
+ if (value === void 0) {
1465
+ const result = await getPurpose(name, deps);
1466
+ if (!result.ok) {
1467
+ const { code, message, suggestion } = result.error;
1468
+ console.error(formatError(createError(code, message, suggestion)));
1469
+ process.exit(1);
1470
+ }
1471
+ if (result.purpose === null) {
1472
+ console.log("(no purpose set)");
1473
+ } else {
1474
+ console.log(result.purpose);
1475
+ }
1476
+ } else {
1477
+ const result = await setPurpose(name, value, deps);
1478
+ if (!result.ok) {
1479
+ const { code, message, suggestion } = result.error;
1480
+ console.error(formatError(createError(code, message, suggestion)));
1481
+ process.exit(1);
1482
+ }
1483
+ if (result.cleared) {
1484
+ console.log("Purpose cleared");
1485
+ } else {
1486
+ console.log("Purpose updated");
1487
+ }
1488
+ }
1489
+ });
1490
+
1491
+ // src/commands/remove.ts
1492
+ import chalk2 from "chalk";
1493
+ import { Command as Command6 } from "commander";
1494
+ import { createInterface } from "readline";
1495
+
1496
+ // src/lib/audit-log.ts
1497
+ import { appendFile as appendFile5, mkdir as mkdir7 } from "fs/promises";
1498
+ import { homedir as homedir5 } from "os";
1499
+ import { join as join4 } from "path";
1500
+ function createAuditLogDefaultDeps() {
1501
+ return { appendFile: appendFile5, mkdir: mkdir7, homedir: homedir5 };
1502
+ }
1503
+ function getAuditLogPath(deps) {
1504
+ return join4(deps.homedir(), AGENT_ENV_DIR, "audit.log");
1505
+ }
1506
+ async function writeAuditLogEntry(entry, deps = createAuditLogDefaultDeps()) {
1507
+ const logPath = getAuditLogPath(deps);
1508
+ await deps.mkdir(join4(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
1509
+ const line = JSON.stringify(entry) + "\n";
1510
+ await deps.appendFile(logPath, line, "utf-8");
1511
+ }
1512
+ function createAuditEntry(instanceName, gitState, confirmationMethod) {
1513
+ return {
1514
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1515
+ action: "force-remove",
1516
+ instanceName,
1517
+ gitState,
1518
+ confirmationMethod
1519
+ };
1520
+ }
1521
+
1522
+ // src/lib/remove-instance.ts
1523
+ import { mkdir as mkdir8, readdir as readdir6, readFile as readFile6, rm as rm3, stat as stat6 } from "fs/promises";
1524
+ import { homedir as homedir6 } from "os";
1525
+ function createRemoveDefaultDeps() {
1526
+ const executor = createExecutor();
1527
+ return {
1528
+ executor,
1529
+ container: createContainerLifecycle(executor),
1530
+ gitDetector: createGitStateDetector(executor),
1531
+ workspaceFsDeps: { mkdir: mkdir8, readdir: readdir6, stat: stat6, homedir: homedir6 },
1532
+ stateFsDeps: { readFile: readFile6 },
1533
+ deleteFsDeps: { rm: rm3 }
1534
+ };
1535
+ }
1536
+ function evaluateSafetyChecks(gitState) {
1537
+ const blockers = [];
1538
+ if (gitState.hasStaged) {
1539
+ const count = gitState.stagedCount;
1540
+ blockers.push(`${count} staged ${count === 1 ? "file" : "files"} detected`);
1541
+ }
1542
+ if (gitState.hasUnstaged) {
1543
+ const count = gitState.unstagedCount;
1544
+ blockers.push(`${count} unstaged ${count === 1 ? "change" : "changes"} detected`);
1545
+ }
1546
+ if (gitState.hasUntracked) {
1547
+ const count = gitState.untrackedCount;
1548
+ blockers.push(`${count} untracked ${count === 1 ? "file" : "files"} detected`);
1549
+ }
1550
+ if (gitState.stashCount > 0) {
1551
+ const stashLabel = `${gitState.stashCount} stash${gitState.stashCount === 1 ? "" : "es"}`;
1552
+ const message = gitState.firstStashMessage ? ` \u2014 "${gitState.firstStashMessage}"` : "";
1553
+ blockers.push(`stashed changes detected (${stashLabel}${message})`);
1554
+ }
1555
+ if (gitState.unpushedBranches.length > 0) {
1556
+ const branchDetails = gitState.unpushedBranches.map((b) => {
1557
+ const count = gitState.unpushedCommitCounts[b];
1558
+ return count ? `${b} (${count} ${count === 1 ? "commit" : "commits"})` : b;
1559
+ }).join(", ");
1560
+ blockers.push(`unpushed commits on branches: ${branchDetails}`);
1561
+ }
1562
+ if (gitState.neverPushedBranches.length > 0) {
1563
+ blockers.push(`branches never pushed: ${gitState.neverPushedBranches.join(", ")}`);
1564
+ }
1565
+ if (gitState.isDetachedHead) {
1566
+ blockers.push("detached HEAD state (investigate manually)");
1567
+ }
1568
+ return blockers;
1569
+ }
1570
+ async function removeInstance(instanceName, deps, force = false) {
1571
+ const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1572
+ if (!lookup.found) {
1573
+ if (lookup.reason === "ambiguous") {
1574
+ return {
1575
+ ok: false,
1576
+ error: {
1577
+ code: "AMBIGUOUS_MATCH",
1578
+ message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
1579
+ suggestion: "Use the full workspace name to specify which instance."
1580
+ }
1581
+ };
1582
+ }
1583
+ return {
1584
+ ok: false,
1585
+ error: {
1586
+ code: "WORKSPACE_NOT_FOUND",
1587
+ message: `Instance '${instanceName}' not found`,
1588
+ suggestion: "Use `agent-env list` to see available instances."
1589
+ }
1590
+ };
1591
+ }
1592
+ const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1593
+ const state = await readState(wsPath, deps.stateFsDeps);
1594
+ const containerName = state.containerName;
1595
+ const dockerAvailable = await deps.container.isDockerAvailable();
1596
+ if (!dockerAvailable) {
1597
+ return {
1598
+ ok: false,
1599
+ error: {
1600
+ code: "ORBSTACK_REQUIRED",
1601
+ message: "Docker is not available. OrbStack or Docker Desktop must be running.",
1602
+ suggestion: "Start OrbStack or Docker Desktop, then try again."
1603
+ }
1604
+ };
1605
+ }
1606
+ const gitResult = await deps.gitDetector.getGitState(wsPath.root);
1607
+ let detectedGitState;
1608
+ let detectedBlockers;
1609
+ if (!gitResult.ok) {
1610
+ if (!force) {
1611
+ return {
1612
+ ok: false,
1613
+ error: {
1614
+ code: "GIT_ERROR",
1615
+ message: `Failed to check git state: ${gitResult.error.message}`,
1616
+ suggestion: "Ensure the workspace contains a valid git repository."
1617
+ }
1618
+ };
1619
+ }
1620
+ } else {
1621
+ detectedGitState = gitResult.state;
1622
+ const blockers = evaluateSafetyChecks(gitResult.state);
1623
+ if (blockers.length > 0) {
1624
+ detectedBlockers = blockers;
1625
+ if (!force) {
1626
+ return {
1627
+ ok: false,
1628
+ error: {
1629
+ code: "SAFETY_CHECK_FAILED",
1630
+ message: "Safety checks failed",
1631
+ suggestion: "Resolve the issues above, or use --force to bypass safety checks."
1632
+ },
1633
+ gitState: gitResult.state,
1634
+ blockers
1635
+ };
1636
+ }
1637
+ }
1638
+ }
1639
+ let containerCleanupFailed = false;
1640
+ const stopResult = await deps.container.containerStop(containerName);
1641
+ if (!stopResult.ok) {
1642
+ if (force) {
1643
+ console.error(
1644
+ `Warning: Failed to stop container ${containerName}: ${stopResult.error.message}`
1645
+ );
1646
+ containerCleanupFailed = true;
1647
+ } else {
1648
+ return {
1649
+ ok: false,
1650
+ error: stopResult.error
1651
+ };
1652
+ }
1653
+ }
1654
+ const removeResult = await deps.container.containerRemove(containerName);
1655
+ if (!removeResult.ok) {
1656
+ if (force) {
1657
+ console.error(
1658
+ `Warning: Failed to remove container ${containerName}: ${removeResult.error.message}`
1659
+ );
1660
+ containerCleanupFailed = true;
1661
+ } else {
1662
+ return {
1663
+ ok: false,
1664
+ error: removeResult.error
1665
+ };
1666
+ }
1667
+ }
1668
+ try {
1669
+ await deleteWorkspace(wsPath, deps.deleteFsDeps);
1670
+ } catch (err) {
1671
+ return {
1672
+ ok: false,
1673
+ error: {
1674
+ code: "WORKSPACE_DELETE_FAILED",
1675
+ message: `Failed to delete workspace: ${err instanceof Error ? err.message : String(err)}`,
1676
+ suggestion: `Container was removed but workspace remains at ${wsPath.root}. Remove manually with: rm -rf ${wsPath.root}`
1677
+ }
1678
+ };
1679
+ }
1680
+ if (force) {
1681
+ return {
1682
+ ok: true,
1683
+ forced: true,
1684
+ gitState: detectedGitState,
1685
+ blockers: detectedBlockers,
1686
+ containerCleanupFailed
1687
+ };
1688
+ }
1689
+ return { ok: true };
1690
+ }
1691
+
1692
+ // src/lib/safety-report.ts
1693
+ import chalk from "chalk";
1694
+ var BLOCKER_NEVER_PUSHED = "never pushed";
1695
+ var BLOCKER_DETACHED_HEAD = "detached HEAD";
1696
+ function classifyBlocker(blocker) {
1697
+ if (blocker.includes(BLOCKER_NEVER_PUSHED) || blocker.includes(BLOCKER_DETACHED_HEAD)) {
1698
+ return "Danger";
1699
+ }
1700
+ return "Warning";
1701
+ }
1702
+ var SUGGESTION_CONFIG = [
1703
+ {
1704
+ condition: (gitState) => gitState.hasStaged,
1705
+ generator: () => "Run `git commit` to commit staged changes"
1706
+ },
1707
+ {
1708
+ condition: (gitState) => gitState.hasUnstaged,
1709
+ generator: () => "Run `git add` and `git commit` to save unstaged changes"
1710
+ },
1711
+ {
1712
+ condition: (gitState) => gitState.hasUntracked,
1713
+ generator: () => "Run `git add` to track untracked files, then commit"
1714
+ },
1715
+ {
1716
+ condition: (gitState) => gitState.stashCount > 0,
1717
+ generator: () => "Run `git stash pop` to apply stashed changes, or `git stash drop` to discard them"
1718
+ },
1719
+ {
1720
+ condition: (gitState) => gitState.unpushedBranches.length > 0,
1721
+ generator: (gitState) => `Run \`git push\` to push unpushed commits on: ${gitState.unpushedBranches.join(", ")}`
1722
+ },
1723
+ {
1724
+ condition: (gitState) => gitState.neverPushedBranches.length > 0,
1725
+ generator: (gitState) => `Run \`git push -u origin <branch>\` for never-pushed branches: ${gitState.neverPushedBranches.join(", ")}`
1726
+ },
1727
+ {
1728
+ condition: (gitState) => gitState.isDetachedHead,
1729
+ generator: () => "Run `git checkout <branch>` to reattach HEAD, or `git checkout -b <new-branch>` to save work"
1730
+ }
1731
+ ];
1732
+ function getSuggestions(gitState) {
1733
+ return SUGGESTION_CONFIG.filter((entry) => entry.condition(gitState)).map(
1734
+ (entry) => entry.generator(gitState)
1735
+ );
1736
+ }
1737
+ function formatSafetyReport(instanceName, blockers, gitState) {
1738
+ const lines = [];
1739
+ lines.push(`Cannot remove '${instanceName}' \u2014 safety checks failed:`);
1740
+ lines.push("");
1741
+ const items = blockers.map((blocker) => ({
1742
+ severity: classifyBlocker(blocker),
1743
+ message: blocker
1744
+ }));
1745
+ for (const item of items) {
1746
+ const prefix = item.severity === "Danger" ? chalk.red("[Danger]") : chalk.yellow("[Warning]");
1747
+ lines.push(` ${prefix} ${item.message}`);
1748
+ }
1749
+ const suggestions = getSuggestions(gitState);
1750
+ if (suggestions.length > 0) {
1751
+ lines.push("");
1752
+ lines.push(chalk.bold("Suggestions:"));
1753
+ for (const suggestion of suggestions) {
1754
+ lines.push(` - ${suggestion}`);
1755
+ }
1756
+ }
1757
+ lines.push("");
1758
+ lines.push(chalk.gray("Or use --force to bypass safety checks (data loss is permanent)."));
1759
+ return lines.join("\n");
1760
+ }
1761
+
1762
+ // src/commands/remove.ts
1763
+ function promptForConfirmation(instanceName) {
1764
+ return new Promise((resolve) => {
1765
+ let resolved = false;
1766
+ const rl = createInterface({
1767
+ input: process.stdin,
1768
+ output: process.stderr
1769
+ });
1770
+ rl.question(`
1771
+ Type the instance name "${instanceName}" to confirm: `, (answer) => {
1772
+ if (!resolved) {
1773
+ resolved = true;
1774
+ rl.close();
1775
+ resolve(answer);
1776
+ }
1777
+ });
1778
+ rl.on("close", () => {
1779
+ if (!resolved) {
1780
+ resolved = true;
1781
+ resolve(null);
1782
+ }
1783
+ });
1784
+ });
1785
+ }
1786
+ async function writeAuditLog(name, gitState, confirmationMethod) {
1787
+ try {
1788
+ const auditDeps = createAuditLogDefaultDeps();
1789
+ const entry = createAuditEntry(name, gitState, confirmationMethod);
1790
+ await writeAuditLogEntry(entry, auditDeps);
1791
+ } catch {
1792
+ console.error("Warning: Failed to write audit log entry.");
1793
+ }
1794
+ }
1795
+ function showForceWarning(name, blockers, gitState) {
1796
+ console.error("");
1797
+ console.error(chalk2.red.bold("\u26A0\uFE0F WARNING: Force removing with unsaved work"));
1798
+ console.error("");
1799
+ console.error(
1800
+ formatSafetyReport(name, blockers, gitState).replace(
1801
+ /Or use --force.*/,
1802
+ chalk2.red("This data will be PERMANENTLY DELETED.")
1803
+ )
1804
+ );
1805
+ }
1806
+ async function resolveConfirmation(name, options) {
1807
+ if (options.yes) {
1808
+ return "yes-flag";
1809
+ }
1810
+ if (!process.stdin.isTTY) {
1811
+ console.error("");
1812
+ console.error(
1813
+ chalk2.red(
1814
+ "Cannot prompt for confirmation in non-interactive mode. Use --yes to skip confirmation."
1815
+ )
1816
+ );
1817
+ return null;
1818
+ }
1819
+ const answer = await promptForConfirmation(name);
1820
+ if (answer === null || answer !== name) {
1821
+ console.log("Removal cancelled");
1822
+ return null;
1823
+ }
1824
+ return "typed-name";
1825
+ }
1826
+ var removeCommand = new Command6("remove").description("Remove an instance with safety checks").argument("<name>", "Instance name to remove").option("--force", "Force removal, bypassing safety checks").option(
1827
+ "--yes",
1828
+ "Skip confirmation prompt for --force (DANGEROUS: skips all safety prompts, for scripts only)"
1829
+ ).action(async (name, options) => {
1830
+ if (options.yes && !options.force) {
1831
+ console.error(
1832
+ formatError(
1833
+ createError(
1834
+ "INVALID_OPTIONS",
1835
+ "--yes can only be used with --force",
1836
+ "Use `agent-env remove <name> --force --yes` to force-remove without confirmation."
1837
+ )
1838
+ )
1839
+ );
1840
+ process.exit(1);
1841
+ return;
1842
+ }
1843
+ const deps = createRemoveDefaultDeps();
1844
+ const checkResult = await removeInstance(name, deps, false);
1845
+ if (checkResult.ok) {
1846
+ if (options.force) {
1847
+ console.log(`Instance '${name}' force-removed. Data permanently deleted.`);
1848
+ await writeAuditLog(name, checkResult.gitState ?? null, "not-required");
1849
+ } else {
1850
+ console.log(`Instance '${name}' removed`);
1851
+ }
1852
+ return;
1853
+ }
1854
+ if (checkResult.error.code !== "SAFETY_CHECK_FAILED") {
1855
+ const { code, message, suggestion } = checkResult.error;
1856
+ console.error(formatError(createError(code, message, suggestion)));
1857
+ process.exit(1);
1858
+ return;
1859
+ }
1860
+ if (!options.force) {
1861
+ if (checkResult.gitState && checkResult.blockers) {
1862
+ console.error(formatSafetyReport(name, checkResult.blockers, checkResult.gitState));
1863
+ }
1864
+ process.exit(1);
1865
+ return;
1866
+ }
1867
+ const { gitState, blockers } = checkResult;
1868
+ if (gitState && blockers && blockers.length > 0) {
1869
+ showForceWarning(name, blockers, gitState);
1870
+ }
1871
+ const confirmationMethod = await resolveConfirmation(name, options);
1872
+ if (!confirmationMethod) {
1873
+ process.exit(1);
1874
+ return;
1875
+ }
1876
+ const forceResult = await removeInstance(name, deps, true);
1877
+ if (!forceResult.ok) {
1878
+ const { code, message, suggestion } = forceResult.error;
1879
+ console.error(formatError(createError(code, message, suggestion)));
1880
+ process.exit(1);
1881
+ return;
1882
+ }
1883
+ console.log(`Instance '${name}' force-removed. Data permanently deleted.`);
1884
+ await writeAuditLog(name, gitState ?? null, confirmationMethod);
1885
+ });
1886
+
1887
+ // src/components/InteractiveMenu.tsx
1888
+ import { Select } from "@inkjs/ui";
1889
+ import { Box as Box2, Text as Text3 } from "ink";
1890
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
1891
+ var COLUMN_PADDING = 2;
1892
+ var SELECT_PREFIX_WIDTH = 4;
1893
+ function statusSymbol(status) {
1894
+ switch (status) {
1895
+ case "running":
1896
+ return "\u25B6";
1897
+ case "stopped":
1898
+ return "\u25A0";
1899
+ case "orphaned":
1900
+ return "\u2717";
1901
+ case "unknown":
1902
+ return "?";
1903
+ case "not-found":
1904
+ return "\u2717";
1905
+ }
1906
+ }
1907
+ function gitIndicatorString(gitState) {
1908
+ const indicators = formatGitIndicators(gitState);
1909
+ return indicators.map((ind) => ind.symbol).join(" ");
1910
+ }
1911
+ function truncatePurpose(purpose, maxLen) {
1912
+ if (!purpose) return "";
1913
+ if (maxLen <= 3) return "";
1914
+ if (purpose.length <= maxLen) return purpose;
1915
+ return purpose.slice(0, maxLen - 3) + "...";
1916
+ }
1917
+ function buildOptionLabel(instance, terminalWidth) {
1918
+ const name = instance.name;
1919
+ const status = statusSymbol(instance.status);
1920
+ const git = gitIndicatorString(instance.gitState);
1921
+ const fixedWidth = name.length + COLUMN_PADDING + status.length + COLUMN_PADDING + git.length + COLUMN_PADDING;
1922
+ const availableForPurpose = Math.max(0, terminalWidth - fixedWidth - SELECT_PREFIX_WIDTH);
1923
+ const purpose = truncatePurpose(instance.purpose, availableForPurpose);
1924
+ const parts = [name, status, git];
1925
+ if (purpose) {
1926
+ parts.push(purpose);
1927
+ }
1928
+ return parts.join(" ");
1929
+ }
1930
+ function InteractiveMenu({
1931
+ instances,
1932
+ onSelect,
1933
+ terminalWidth
1934
+ }) {
1935
+ const width = terminalWidth ?? process.stdout.columns ?? 80;
1936
+ if (instances.length === 0) {
1937
+ return /* @__PURE__ */ jsxs3(Box2, { flexDirection: "column", children: [
1938
+ /* @__PURE__ */ jsx3(Text3, { children: "No instances found." }),
1939
+ /* @__PURE__ */ jsxs3(Text3, { color: "gray", children: [
1940
+ "Create one with: agent-env create ",
1941
+ "<name>",
1942
+ " --repo ",
1943
+ "<url>"
1944
+ ] })
1945
+ ] });
1946
+ }
1947
+ const options = instances.map((instance) => ({
1948
+ label: buildOptionLabel(instance, width),
1949
+ value: instance.name
1950
+ }));
1951
+ return /* @__PURE__ */ jsxs3(Box2, { flexDirection: "column", children: [
1952
+ /* @__PURE__ */ jsx3(Box2, { marginBottom: 1, children: /* @__PURE__ */ jsx3(Text3, { bold: true, children: "Select an instance to attach:" }) }),
1953
+ /* @__PURE__ */ jsx3(Select, { options, onChange: onSelect })
1954
+ ] });
1955
+ }
1956
+
1957
+ // src/lib/interactive-menu.ts
1958
+ async function launchInteractiveMenu(deps) {
1959
+ const listResult = await deps.listInstances();
1960
+ if (!listResult.ok) {
1961
+ return {
1962
+ ok: false,
1963
+ error: {
1964
+ code: listResult.error.code,
1965
+ message: listResult.error.message,
1966
+ suggestion: "Check if ~/.agent-env/workspaces/ is accessible."
1967
+ }
1968
+ };
1969
+ }
1970
+ if (listResult.instances.length === 0) {
1971
+ deps.renderMenu(listResult.instances, () => {
1972
+ });
1973
+ return { ok: true, action: "empty" };
1974
+ }
1975
+ let selectedName;
1976
+ const selectionPromise = new Promise((resolve) => {
1977
+ const { waitUntilExit } = deps.renderMenu(listResult.instances, (name2) => {
1978
+ selectedName = name2;
1979
+ resolve(name2);
1980
+ });
1981
+ void waitUntilExit().then(() => {
1982
+ if (!selectedName) {
1983
+ resolve("");
1984
+ }
1985
+ });
1986
+ });
1987
+ const name = await selectionPromise;
1988
+ if (!name) {
1989
+ return { ok: true, action: "empty" };
1990
+ }
1991
+ const attachDeps = deps.createAttachDeps();
1992
+ const attachResult = await deps.attachInstance(name, attachDeps);
1993
+ if (!attachResult.ok) {
1994
+ return {
1995
+ ok: false,
1996
+ error: attachResult.error
1997
+ };
1998
+ }
1999
+ return { ok: true, action: "attached", instanceName: name };
2000
+ }
2001
+
2002
+ // src/cli.ts
2003
+ var version = package_default.version;
2004
+ program.name("agent-env").description("CLI for creating isolated, AI-ready development environments").version(version);
2005
+ program.addCommand(createCommand);
2006
+ program.addCommand(listCommand);
2007
+ program.addCommand(attachCommand);
2008
+ program.addCommand(removeCommand);
2009
+ program.addCommand(purposeCommand);
2010
+ program.addCommand(completionCommand);
2011
+ program.action(async () => {
2012
+ if (!process.stdin.isTTY) {
2013
+ program.help();
2014
+ return;
2015
+ }
2016
+ const result = await launchInteractiveMenu({
2017
+ listInstances,
2018
+ attachInstance,
2019
+ createAttachDeps: createAttachDefaultDeps,
2020
+ renderMenu: (instances, onSelect) => {
2021
+ const { waitUntilExit } = render2(
2022
+ React2.createElement(InteractiveMenu, { instances, onSelect })
2023
+ );
2024
+ return { waitUntilExit };
2025
+ }
2026
+ });
2027
+ if (!result.ok) {
2028
+ const { code, message, suggestion } = result.error;
2029
+ console.error(formatError(createError(code, message, suggestion)));
2030
+ process.exitCode = 1;
2031
+ }
2032
+ });
2033
+ program.parse();