@zookanalytics/agent-env 0.8.0 → 0.9.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.
@@ -14,18 +14,29 @@ if [ ! -f "$GITCONFIG" ]; then
14
14
  touch "$GITCONFIG"
15
15
  fi
16
16
 
17
- # Stage only SSH public keys for container mount (never expose private keys)
17
+ # Stage only SSH public keys for container mount (never expose private keys).
18
+ # Non-fatal — SSH agent socket provides auth; pub keys are only for sshd authorized_keys.
18
19
  SSH_PUB_DIR="$HOME/.agent-env/ssh-pub-keys"
19
20
  mkdir -p "$SSH_PUB_DIR"
20
- rm -f "$SSH_PUB_DIR"/*.pub 2>/dev/null || true
21
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
22
+ # Atomic replace: copy to temp dir, then swap
23
+ STAGING_TMP="$SSH_PUB_DIR/.staging.$$"
24
+ mkdir -p "$STAGING_TMP"
25
+ if cp -p "$HOME/.ssh/"*.pub "$STAGING_TMP/" 2>/dev/null; then
26
+ rm -f "$SSH_PUB_DIR"/*.pub 2>/dev/null || true
27
+ mv "$STAGING_TMP"/*.pub "$SSH_PUB_DIR/" 2>/dev/null || true
28
+ echo "agent-env: Staged SSH public keys:"
29
+ for f in "$SSH_PUB_DIR"/*.pub; do
30
+ [ -f "$f" ] && echo " - $(basename "$f")"
31
+ done
32
+ else
33
+ rm -f "$SSH_PUB_DIR"/*.pub 2>/dev/null || true
34
+ echo "agent-env: Warning: Failed to stage SSH public keys — cleared stale keys (non-fatal)"
35
+ fi
36
+ rm -rf "$STAGING_TMP" 2>/dev/null || true
27
37
  else
28
- echo "agent-env: Warning: No SSH public keys found in ~/.ssh. SSH access will require manual setup."
38
+ rm -f "$SSH_PUB_DIR"/*.pub 2>/dev/null || true
39
+ echo "agent-env: Warning: No SSH public keys found in ~/.ssh — cleared stale keys. SSH access will require manual setup."
29
40
  fi
30
41
 
31
42
  # Stage PulseAudio cookie for audio passthrough (if setup-audio was run)
package/dist/cli.js CHANGED
@@ -17,10 +17,24 @@ function createError(code, message, suggestion) {
17
17
  import { execa } from "execa";
18
18
  function createExecutor(executor = execa) {
19
19
  return async function execute2(command, args = [], options = {}) {
20
- const result = await executor(command, args, {
20
+ const { onLine, ...execaOptions } = options;
21
+ const subprocess = executor(command, args, {
21
22
  reject: false,
22
- ...options
23
+ ...execaOptions
23
24
  });
25
+ if (onLine) {
26
+ const sub = subprocess;
27
+ const handleChunk = (chunk) => {
28
+ for (const line of chunk.toString().split("\n")) {
29
+ const trimmed = line.trim();
30
+ if (trimmed)
31
+ onLine(trimmed);
32
+ }
33
+ };
34
+ sub.stdout?.on?.("data", handleChunk);
35
+ sub.stderr?.on?.("data", handleChunk);
36
+ }
37
+ const result = await subprocess;
24
38
  return {
25
39
  ok: !result.failed,
26
40
  stdout: String(result.stdout ?? ""),
@@ -35,14 +49,14 @@ var execute = createExecutor();
35
49
  import { program } from "commander";
36
50
  import { render as render2 } from "ink";
37
51
  import { existsSync } from "fs";
38
- import { dirname as dirname3, resolve } from "path";
52
+ import { dirname as dirname4, resolve } from "path";
39
53
  import { fileURLToPath as fileURLToPath2 } from "url";
40
54
  import React3 from "react";
41
55
 
42
56
  // package.json
43
57
  var package_default = {
44
58
  name: "@zookanalytics/agent-env",
45
- version: "0.8.0",
59
+ version: "0.9.1",
46
60
  description: "CLI for creating isolated, AI-ready development environments",
47
61
  type: "module",
48
62
  bin: {
@@ -311,7 +325,8 @@ function createContainerLifecycle(executor = createExecutor()) {
311
325
  ...buildNoCache ? ["--build-no-cache"] : []
312
326
  ];
313
327
  const result = await executor("devcontainer", args, {
314
- timeout: buildNoCache ? DEVCONTAINER_UP_NO_CACHE_TIMEOUT : DEVCONTAINER_UP_TIMEOUT
328
+ timeout: buildNoCache ? DEVCONTAINER_UP_NO_CACHE_TIMEOUT : DEVCONTAINER_UP_TIMEOUT,
329
+ onLine: options?.onProgress
315
330
  });
316
331
  const parsedOutput = parseDevcontainerOutput(result.stdout);
317
332
  if (!result.ok) {
@@ -423,7 +438,7 @@ import { dirname as dirname2, join as join6 } from "path";
423
438
  // src/lib/devcontainer-merge.ts
424
439
  import { parse as parseJsonc2 } from "jsonc-parser";
425
440
  import { constants } from "fs";
426
- import { access as access2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
441
+ import { access as access2, lstat, readFile as readFile2, readlink, rename, writeFile as writeFile2 } from "fs/promises";
427
442
  import { createRequire } from "module";
428
443
  import { join as join2 } from "path";
429
444
 
@@ -599,11 +614,18 @@ function parseDockerfileImages(content, logger) {
599
614
  }
600
615
 
601
616
  // src/lib/devcontainer-merge.ts
602
- var defaultMergeDeps = { readFile: readFile2, writeFile: writeFile2, rename, access: access2 };
617
+ var defaultMergeDeps = {
618
+ readFile: readFile2,
619
+ writeFile: writeFile2,
620
+ rename,
621
+ access: access2,
622
+ lstat,
623
+ readlink
624
+ };
603
625
  var STATUS_BAR_JSON_FILENAME = "statusBar.json";
604
626
  var LABEL_LIFECYCLE_CMDS = {
605
627
  postCreateCommand: "/usr/local/bin/post-create.sh",
606
- postStartCommand: "sudo /usr/local/bin/start-sshd.sh; tmux new-session -d -s main 2>/dev/null || true; : > /tmp/install-shared-skills.log; /usr/local/bin/install-shared-skills.sh >> /tmp/install-shared-skills.log 2>&1 || true"
628
+ postStartCommand: "sudo /usr/local/bin/start-sshd.sh; tmux new-session -d -s agent-env 2>/dev/null || true; agent-env tmux-restore 2>/dev/null || true; : > /tmp/install-shared-skills.log; /usr/local/bin/install-shared-skills.sh >> /tmp/install-shared-skills.log 2>&1 || true"
607
629
  };
608
630
  var COMPOSABLE_LIFECYCLE_CMDS = [
609
631
  "postCreateCommand",
@@ -620,6 +642,21 @@ async function readRepoConfig(workspacePath, deps = defaultMergeDeps, logger) {
620
642
  join2(workspacePath, ".devcontainer.json")
621
643
  ];
622
644
  for (const candidate of candidates) {
645
+ if (deps.lstat && deps.readlink) {
646
+ try {
647
+ const linkStat = await deps.lstat(candidate);
648
+ if (linkStat.isSymbolicLink()) {
649
+ const target = await deps.readlink(candidate);
650
+ if (target.includes(AGENT_ENV_DIR)) {
651
+ logger?.warn(
652
+ `Skipping symlink to agent-env config at ${candidate} \u2014 not a repo config`
653
+ );
654
+ continue;
655
+ }
656
+ }
657
+ } catch {
658
+ }
659
+ }
623
660
  let content;
624
661
  try {
625
662
  await deps.access(candidate, constants.F_OK);
@@ -651,7 +688,7 @@ async function readRepoConfig(workspacePath, deps = defaultMergeDeps, logger) {
651
688
  }
652
689
  return void 0;
653
690
  }
654
- function validateRepoConfig(config, logger) {
691
+ function validateRepoConfig(config, managedImage, logger) {
655
692
  const rejectedProps = ["build", "dockerFile", "dockerfile", "dockerComposeFile"];
656
693
  for (const prop of rejectedProps) {
657
694
  if (prop in config && config[prop] !== void 0) {
@@ -662,9 +699,11 @@ function validateRepoConfig(config, logger) {
662
699
  }
663
700
  if ("image" in config && config.image !== void 0) {
664
701
  const repoImage = String(config.image);
665
- logger?.warn(
666
- `Repo config specifies image '${repoImage}' which will be overridden by agent-env managed image.`
667
- );
702
+ if (repoImage !== managedImage) {
703
+ logger?.warn(
704
+ `Repo config specifies image '${repoImage}' which will be overridden by agent-env managed image.`
705
+ );
706
+ }
668
707
  }
669
708
  }
670
709
  function composeName(instanceName, repoName) {
@@ -1547,14 +1586,7 @@ async function resolveRepoUrl(repoArg, executor) {
1547
1586
  async function attachToInstance(containerName, executor) {
1548
1587
  const result = await executor(
1549
1588
  "docker",
1550
- [
1551
- "exec",
1552
- "-it",
1553
- containerName,
1554
- "bash",
1555
- "-c",
1556
- "tmux attach-session -t main 2>/dev/null || tmux new-session -s main"
1557
- ],
1589
+ ["exec", "-it", containerName, "bash", "-c", "/home/node/.local/bin/tmux-session"],
1558
1590
  { stdio: "inherit" }
1559
1591
  );
1560
1592
  if (!result.ok) {
@@ -1598,7 +1630,7 @@ async function setupMergedConfig(wsPath, containerName, repoName, purposeText, d
1598
1630
  });
1599
1631
  const repoConfig = await readRepoConfig(wsPath.root, deps.mergeDeps, deps.logger);
1600
1632
  if (repoConfig) {
1601
- validateRepoConfig(repoConfig, deps.logger);
1633
+ validateRepoConfig(repoConfig, defaults.image, deps.logger);
1602
1634
  }
1603
1635
  const merged = mergeDevcontainerConfigs(managed, repoConfig);
1604
1636
  await copyManagedAssets(wsPath.root, deps.devcontainerFsDeps);
@@ -1727,7 +1759,8 @@ async function createInstance(instanceName, repoUrl, deps, options) {
1727
1759
  AGENT_INSTANCE: wsPath.name,
1728
1760
  AGENT_ENV_PURPOSE: purposeText
1729
1761
  },
1730
- configPath
1762
+ configPath,
1763
+ onProgress: options?.onProgress
1731
1764
  });
1732
1765
  if (!containerResult.ok) {
1733
1766
  return rollbackContainerFailure(containerName, wsPath, containerResult, deps);
@@ -1924,9 +1957,184 @@ var attachCommand = new Command("attach").description("Attach to an instance's t
1924
1957
  }
1925
1958
  });
1926
1959
 
1927
- // src/commands/completion.ts
1960
+ // src/commands/code.ts
1928
1961
  import { Command as Command2 } from "commander";
1929
1962
 
1963
+ // src/lib/code-instance.ts
1964
+ import {
1965
+ appendFile as appendFile5,
1966
+ lstat as lstat2,
1967
+ mkdir as mkdir7,
1968
+ readdir as readdir6,
1969
+ readFile as readFile9,
1970
+ readlink as readlink2,
1971
+ rename as rename6,
1972
+ stat as stat6,
1973
+ symlink,
1974
+ unlink,
1975
+ writeFile as writeFile8
1976
+ } from "fs/promises";
1977
+ import { homedir as homedir5 } from "os";
1978
+ import { join as join8 } from "path";
1979
+ function createCodeDefaultDeps() {
1980
+ const executor = createExecutor();
1981
+ return {
1982
+ executor,
1983
+ container: createContainerLifecycle(executor),
1984
+ workspaceFsDeps: { mkdir: mkdir7, readdir: readdir6, stat: stat6, homedir: homedir5 },
1985
+ stateFsDeps: { readFile: readFile9, writeFile: writeFile8, rename: rename6, mkdir: mkdir7, appendFile: appendFile5 },
1986
+ codeFsDeps: { lstat: lstat2, symlink, readlink: readlink2, unlink }
1987
+ };
1988
+ }
1989
+ var DEVCONTAINER_OPEN_TIMEOUT = 3e4;
1990
+ async function ensureConfigSymlink(wsRoot, deps) {
1991
+ const symlinkPath = join8(wsRoot, ".devcontainer.json");
1992
+ const target = join8(AGENT_ENV_DIR, "devcontainer.json");
1993
+ try {
1994
+ const linkStat = await deps.lstat(symlinkPath);
1995
+ if (linkStat.isSymbolicLink()) {
1996
+ const existing = await deps.readlink(symlinkPath);
1997
+ if (existing === target) return;
1998
+ await deps.unlink(symlinkPath);
1999
+ } else {
2000
+ return;
2001
+ }
2002
+ } catch (err) {
2003
+ if (err.code !== "ENOENT") throw err;
2004
+ }
2005
+ await deps.symlink(target, symlinkPath);
2006
+ }
2007
+ async function removeConfigSymlink(wsRoot, deps) {
2008
+ const symlinkPath = join8(wsRoot, ".devcontainer.json");
2009
+ try {
2010
+ const linkStat = await deps.lstat(symlinkPath);
2011
+ if (!linkStat.isSymbolicLink()) return;
2012
+ await deps.unlink(symlinkPath);
2013
+ } catch {
2014
+ }
2015
+ }
2016
+ async function codeInstance(instanceName, deps, onContainerStarting, onOpening, repoSlug) {
2017
+ const lookup = await resolveInstance(instanceName, repoSlug, {
2018
+ fsDeps: deps.workspaceFsDeps,
2019
+ readFile: deps.stateFsDeps.readFile
2020
+ });
2021
+ if (!lookup.found) {
2022
+ return { ok: false, error: lookup.error };
2023
+ }
2024
+ const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
2025
+ const state = await readState(wsPath, deps.stateFsDeps);
2026
+ const containerName = state.containerName;
2027
+ const dockerAvailable = await deps.container.isDockerAvailable();
2028
+ if (!dockerAvailable) {
2029
+ return {
2030
+ ok: false,
2031
+ error: {
2032
+ code: "ORBSTACK_REQUIRED",
2033
+ message: "Docker is not available. OrbStack or Docker Desktop must be running.",
2034
+ suggestion: "Start OrbStack or Docker Desktop, then try again."
2035
+ }
2036
+ };
2037
+ }
2038
+ const statusResult = await deps.container.containerStatus(containerName);
2039
+ if (!statusResult.ok) {
2040
+ return {
2041
+ ok: false,
2042
+ error: statusResult.error ?? {
2043
+ code: "CONTAINER_ERROR",
2044
+ message: `Failed to check container status for '${containerName}'.`
2045
+ }
2046
+ };
2047
+ }
2048
+ const configPath = join8(wsPath.root, AGENT_ENV_DIR, "devcontainer.json");
2049
+ if (statusResult.status === "stopped" || statusResult.status === "not-found") {
2050
+ onContainerStarting?.();
2051
+ const startResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
2052
+ remoteEnv: { AGENT_INSTANCE: wsPath.name },
2053
+ configPath
2054
+ });
2055
+ if (!startResult.ok) {
2056
+ return {
2057
+ ok: false,
2058
+ error: startResult.error ?? {
2059
+ code: "CONTAINER_ERROR",
2060
+ message: `Failed to start container '${containerName}'.`,
2061
+ suggestion: "Check Docker logs for details."
2062
+ }
2063
+ };
2064
+ }
2065
+ }
2066
+ const needsSymlink = !state.repoConfigDetected;
2067
+ if (needsSymlink) {
2068
+ try {
2069
+ await ensureConfigSymlink(wsPath.root, deps.codeFsDeps);
2070
+ } catch (err) {
2071
+ const detail = err instanceof Error ? err.message : String(err);
2072
+ return {
2073
+ ok: false,
2074
+ error: {
2075
+ code: "SYMLINK_FAILED",
2076
+ message: `Failed to create .devcontainer symlink in '${wsPath.root}': ${detail}`,
2077
+ suggestion: "Check file permissions in the workspace directory."
2078
+ }
2079
+ };
2080
+ }
2081
+ }
2082
+ let openResult;
2083
+ try {
2084
+ onOpening?.();
2085
+ openResult = await deps.executor(
2086
+ "devcontainer",
2087
+ ["open", wsPath.root, "--config", configPath],
2088
+ { stdio: "inherit", timeout: DEVCONTAINER_OPEN_TIMEOUT }
2089
+ );
2090
+ } finally {
2091
+ if (needsSymlink) {
2092
+ await removeConfigSymlink(wsPath.root, deps.codeFsDeps);
2093
+ }
2094
+ }
2095
+ if (!openResult.ok) {
2096
+ return {
2097
+ ok: false,
2098
+ error: {
2099
+ code: "VSCODE_OPEN_FAILED",
2100
+ message: `Failed to open VS Code for instance '${instanceName}'.`,
2101
+ suggestion: "Ensure VS Code and the Dev Containers extension are installed."
2102
+ }
2103
+ };
2104
+ }
2105
+ const updatedState = {
2106
+ ...state,
2107
+ lastAttached: (/* @__PURE__ */ new Date()).toISOString()
2108
+ };
2109
+ await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
2110
+ return { ok: true };
2111
+ }
2112
+
2113
+ // src/commands/code.ts
2114
+ var codeCommand = new Command2("code").description("Open an instance in VS Code via Dev Containers").argument("<name>", "Instance name to open").option("--repo <slug>", "Repo slug or URL to scope instance lookup").action(async (name, options) => {
2115
+ const deps = createCodeDefaultDeps();
2116
+ const repoSlug = await resolveRepoOrExit({ repo: options.repo, cwd: process.cwd() });
2117
+ const result = await codeInstance(
2118
+ name,
2119
+ deps,
2120
+ () => {
2121
+ console.log("Starting container...");
2122
+ },
2123
+ () => {
2124
+ console.log("Opening VS Code...");
2125
+ },
2126
+ repoSlug
2127
+ );
2128
+ if (!result.ok) {
2129
+ const { code, message, suggestion } = result.error;
2130
+ console.error(formatError(createError(code, message, suggestion)));
2131
+ process.exit(1);
2132
+ }
2133
+ });
2134
+
2135
+ // src/commands/completion.ts
2136
+ import { Command as Command3 } from "commander";
2137
+
1930
2138
  // src/lib/completion.ts
1931
2139
  var COMMANDS = [
1932
2140
  "create",
@@ -2181,7 +2389,7 @@ compdef _agent_env agent-env`;
2181
2389
  }
2182
2390
 
2183
2391
  // src/commands/completion.ts
2184
- var completionCommand = new Command2("completion").description(`Generate shell completion script for bash or zsh
2392
+ var completionCommand = new Command3("completion").description(`Generate shell completion script for bash or zsh
2185
2393
 
2186
2394
  ${getInstallInstructions()}`).argument("<shell>", "Shell type (bash or zsh)").action((shell) => {
2187
2395
  if (!isValidShell(shell)) {
@@ -2198,7 +2406,35 @@ ${getInstallInstructions()}`).argument("<shell>", "Shell type (bash or zsh)").ac
2198
2406
  });
2199
2407
 
2200
2408
  // src/commands/create.ts
2201
- import { Command as Command3 } from "commander";
2409
+ import { Command as Command4 } from "commander";
2410
+
2411
+ // src/lib/progress-line.ts
2412
+ var ERASE_LINE = "\x1B[K";
2413
+ function createProgressLine(stream = process.stderr, columns) {
2414
+ if (!stream.isTTY) {
2415
+ return { update() {
2416
+ }, clear() {
2417
+ } };
2418
+ }
2419
+ const maxWidth = columns ?? stream.columns ?? 80;
2420
+ const PREFIX = "\u23F3 ";
2421
+ const prefixLen = 3;
2422
+ let active = false;
2423
+ return {
2424
+ update(line) {
2425
+ const clean = line.replace(/\x1b\[[0-9;]*m/g, "");
2426
+ const truncated = clean.length + prefixLen > maxWidth ? clean.slice(0, maxWidth - prefixLen - 1) + "\u2026" : clean;
2427
+ stream.write(`\r${ERASE_LINE}${PREFIX}${truncated}`);
2428
+ active = true;
2429
+ },
2430
+ clear() {
2431
+ if (active) {
2432
+ stream.write(`\r${ERASE_LINE}`);
2433
+ active = false;
2434
+ }
2435
+ }
2436
+ };
2437
+ }
2202
2438
 
2203
2439
  // src/lib/list-repos.ts
2204
2440
  async function listRepos(deps) {
@@ -2278,7 +2514,7 @@ async function resolveRepoArg(repoArg, deps) {
2278
2514
  }
2279
2515
 
2280
2516
  // src/commands/create.ts
2281
- var createCommand = new Command3("create").description("Create a new isolated development environment").argument("<name>", "Name for the new instance").option("--repo <url|slug>", 'Git repo URL, registered slug, or "." for current directory').option("--purpose <text>", "Set the instance purpose/label at creation time").option("--attach", "Attach immediately after creation").option("--baseline", "[REMOVED] Config merge replaces this flag").option("--no-baseline", "[REMOVED] Config merge replaces this flag").action(async (name, options) => {
2517
+ var createCommand = new Command4("create").description("Create a new isolated development environment").argument("<name>", "Name for the new instance").option("--repo <url|slug>", 'Git repo URL, registered slug, or "." for current directory').option("--purpose <text>", "Set the instance purpose/label at creation time").option("--attach", "Attach immediately after creation").option("--baseline", "[REMOVED] Config merge replaces this flag").option("--no-baseline", "[REMOVED] Config merge replaces this flag").action(async (name, options) => {
2282
2518
  if (options.baseline !== void 0) {
2283
2519
  console.error(
2284
2520
  formatError(
@@ -2322,32 +2558,39 @@ var createCommand = new Command3("create").description("Create a new isolated de
2322
2558
  }
2323
2559
  const repoUrl = resolved.url;
2324
2560
  console.log(`Creating instance '${name}' from ${repoUrl}...`);
2325
- const result = await createInstance(name, repoUrl, deps, {
2326
- purpose: options.purpose
2327
- });
2328
- if (!result.ok) {
2329
- const { code, message, suggestion } = result.error;
2330
- console.error(formatError(createError(code, message, suggestion)));
2331
- process.exit(1);
2332
- }
2333
- const { workspacePath, containerName } = result;
2334
- console.log(`\x1B[32m\u2713\x1B[0m Instance '${name}' created successfully`);
2335
- console.log(` Workspace: ${workspacePath.root}`);
2336
- console.log(` Container: ${containerName}`);
2337
- if (options.attach) {
2338
- console.log();
2339
- console.log("Attaching to instance...");
2340
- const attachResult = await attachToInstance(containerName, deps.executor);
2341
- if (!attachResult.ok) {
2342
- const { code, message, suggestion } = attachResult.error;
2561
+ const progress = createProgressLine();
2562
+ try {
2563
+ const result = await createInstance(name, repoUrl, deps, {
2564
+ purpose: options.purpose,
2565
+ onProgress: progress.update
2566
+ });
2567
+ progress.clear();
2568
+ if (!result.ok) {
2569
+ const { code, message, suggestion } = result.error;
2343
2570
  console.error(formatError(createError(code, message, suggestion)));
2344
2571
  process.exit(1);
2345
2572
  }
2573
+ const { workspacePath, containerName } = result;
2574
+ console.log(`\x1B[32m\u2713\x1B[0m Instance '${name}' created successfully`);
2575
+ console.log(` Workspace: ${workspacePath.root}`);
2576
+ console.log(` Container: ${containerName}`);
2577
+ if (options.attach) {
2578
+ console.log();
2579
+ console.log("Attaching to instance...");
2580
+ const attachResult = await attachToInstance(containerName, deps.executor);
2581
+ if (!attachResult.ok) {
2582
+ const { code, message, suggestion } = attachResult.error;
2583
+ console.error(formatError(createError(code, message, suggestion)));
2584
+ process.exit(1);
2585
+ }
2586
+ }
2587
+ } finally {
2588
+ progress.clear();
2346
2589
  }
2347
2590
  });
2348
2591
 
2349
2592
  // src/commands/list.ts
2350
- import { Command as Command4 } from "commander";
2593
+ import { Command as Command5 } from "commander";
2351
2594
  import { render } from "ink";
2352
2595
  import React from "react";
2353
2596
 
@@ -2694,7 +2937,7 @@ async function listInstances(deps, opts) {
2694
2937
  }
2695
2938
 
2696
2939
  // src/commands/list.ts
2697
- var listCommand = new Command4("list").alias("ps").description("List all instances with status").option("--json", "Output in JSON format").option("--repo <slug>", "Filter instances by repo slug").action(async (options) => {
2940
+ var listCommand = new Command5("list").alias("ps").description("List all instances with status").option("--json", "Output in JSON format").option("--repo <slug>", "Filter instances by repo slug").action(async (options) => {
2698
2941
  const result = await listInstances(void 0, {
2699
2942
  repoFilter: options.repo
2700
2943
  });
@@ -2746,12 +2989,12 @@ var listCommand = new Command4("list").alias("ps").description("List all instanc
2746
2989
  });
2747
2990
 
2748
2991
  // src/commands/purpose.ts
2749
- import { Command as Command5 } from "commander";
2992
+ import { Command as Command6 } from "commander";
2750
2993
  var defaultPurposeCommandDeps = {
2751
2994
  isInsideContainer
2752
2995
  };
2753
2996
  function createPurposeCommand(deps = defaultPurposeCommandDeps) {
2754
- return new Command5("purpose").description(
2997
+ return new Command6("purpose").description(
2755
2998
  "Get or set the purpose/label for an instance. Inside a container: no instance name needed (agent-env purpose [value])"
2756
2999
  ).argument("[nameOrValue]", "Instance name (host) or purpose value (container)").argument("[value]", "New purpose value (omit to get current, empty string to clear)").option("--repo <slug>", "Repo slug or URL to scope instance lookup (host mode only)").action(async (nameOrValue, value, options) => {
2757
3000
  if (deps.isInsideContainer()) {
@@ -2826,35 +3069,35 @@ function handleSetResult(result) {
2826
3069
 
2827
3070
  // src/commands/rebuild.ts
2828
3071
  import chalk from "chalk";
2829
- import { Command as Command6 } from "commander";
3072
+ import { Command as Command7 } from "commander";
2830
3073
  import { createInterface } from "readline";
2831
3074
 
2832
3075
  // src/lib/rebuild-instance.ts
2833
3076
  import {
2834
3077
  access as access4,
2835
3078
  cp as cp3,
2836
- mkdir as mkdir7,
2837
- readdir as readdir6,
2838
- readFile as readFile9,
2839
- rename as rename6,
3079
+ mkdir as mkdir8,
3080
+ readdir as readdir7,
3081
+ readFile as readFile10,
3082
+ rename as rename7,
2840
3083
  rm as rm3,
2841
- stat as stat6,
2842
- writeFile as writeFile8,
2843
- appendFile as appendFile5
3084
+ stat as stat7,
3085
+ writeFile as writeFile9,
3086
+ appendFile as appendFile6
2844
3087
  } from "fs/promises";
2845
- import { homedir as homedir5 } from "os";
2846
- import { join as join8 } from "path";
3088
+ import { homedir as homedir6 } from "os";
3089
+ import { join as join9 } from "path";
2847
3090
  function createRebuildDefaultDeps() {
2848
3091
  const executor = createExecutor();
2849
3092
  return {
2850
3093
  executor,
2851
3094
  container: createContainerLifecycle(executor),
2852
- workspaceFsDeps: { mkdir: mkdir7, readdir: readdir6, stat: stat6, homedir: homedir5 },
2853
- stateFsDeps: { readFile: readFile9, writeFile: writeFile8, rename: rename6, mkdir: mkdir7, appendFile: appendFile5 },
2854
- devcontainerFsDeps: { cp: cp3, mkdir: mkdir7, readdir: readdir6, readFile: readFile9, stat: stat6, writeFile: writeFile8 },
2855
- mergeDeps: { readFile: readFile9, writeFile: writeFile8, rename: rename6, access: access4 },
3095
+ workspaceFsDeps: { mkdir: mkdir8, readdir: readdir7, stat: stat7, homedir: homedir6 },
3096
+ stateFsDeps: { readFile: readFile10, writeFile: writeFile9, rename: rename7, mkdir: mkdir8, appendFile: appendFile6 },
3097
+ devcontainerFsDeps: { cp: cp3, mkdir: mkdir8, readdir: readdir7, readFile: readFile10, stat: stat7, writeFile: writeFile9 },
3098
+ mergeDeps: { readFile: readFile10, writeFile: writeFile9, rename: rename7, access: access4 },
2856
3099
  rm: rm3,
2857
- rename: rename6,
3100
+ rename: rename7,
2858
3101
  logger: { warn: (msg) => console.warn(msg), info: (msg) => console.info(msg) }
2859
3102
  };
2860
3103
  }
@@ -2879,11 +3122,11 @@ async function refreshMergedConfig(wsRoot, containerName, wsName, repoSlug, purp
2879
3122
  };
2880
3123
  }
2881
3124
  if (repoConfig) {
2882
- validateRepoConfig(repoConfig, deps.logger);
3125
+ validateRepoConfig(repoConfig, defaults.image, deps.logger);
2883
3126
  }
2884
3127
  const merged = mergeDevcontainerConfigs(managed, repoConfig);
2885
3128
  await copyManagedAssets(wsRoot, deps.devcontainerFsDeps);
2886
- const configPath = join8(wsRoot, AGENT_ENV_DIR, "devcontainer.json");
3129
+ const configPath = join9(wsRoot, AGENT_ENV_DIR, "devcontainer.json");
2887
3130
  await writeGeneratedConfig(configPath, merged, deps.mergeDeps);
2888
3131
  return { ok: true, repoConfigDetected: repoConfig !== void 0 };
2889
3132
  } catch (err) {
@@ -2968,6 +3211,20 @@ async function executePullStep(wsRoot, pull, deps) {
2968
3211
  }
2969
3212
  return { ok: true, hasDockerfile };
2970
3213
  }
3214
+ async function saveTmuxState(containerName, deps) {
3215
+ const result = await deps.executor("docker", [
3216
+ "exec",
3217
+ containerName,
3218
+ "bash",
3219
+ "-lc",
3220
+ "agent-env tmux-save"
3221
+ ]);
3222
+ if (result.ok) {
3223
+ deps.logger?.info("Saved tmux session state");
3224
+ } else {
3225
+ deps.logger?.warn("Could not save tmux session state (non-fatal)");
3226
+ }
3227
+ }
2971
3228
  async function teardownContainer(containerName, container, statusResult) {
2972
3229
  if (!statusResult.ok || statusResult.status === "not-found") {
2973
3230
  return { ok: true };
@@ -2982,12 +3239,13 @@ async function teardownContainer(containerName, container, statusResult) {
2982
3239
  }
2983
3240
  return { ok: true };
2984
3241
  }
2985
- async function startAndDiscoverContainer(wsPath, containerName, purpose, buildNoCache, container) {
2986
- const configPath = join8(wsPath.root, AGENT_ENV_DIR, "devcontainer.json");
3242
+ async function startAndDiscoverContainer(wsPath, containerName, purpose, buildNoCache, container, onProgress) {
3243
+ const configPath = join9(wsPath.root, AGENT_ENV_DIR, "devcontainer.json");
2987
3244
  const containerResult = await container.devcontainerUp(wsPath.root, containerName, {
2988
3245
  buildNoCache,
2989
3246
  remoteEnv: { AGENT_INSTANCE: wsPath.name, AGENT_ENV_PURPOSE: purpose },
2990
- configPath
3247
+ configPath,
3248
+ onProgress
2991
3249
  });
2992
3250
  if (!containerResult.ok) {
2993
3251
  return { ok: false, error: containerResult.error };
@@ -3002,13 +3260,14 @@ async function startAndDiscoverContainer(wsPath, containerName, purpose, buildNo
3002
3260
  return { ok: true, containerName: actualName };
3003
3261
  }
3004
3262
  async function rebuildInstance(instanceName, deps, options, repoSlug) {
3005
- const { force = false, pull = true, noCache = true } = options ?? {};
3263
+ const { force = false, pull = true, noCache = true, onProgress } = options ?? {};
3006
3264
  const wsLookup = await lookupWorkspace(instanceName, deps, repoSlug);
3007
3265
  if (!wsLookup.ok) {
3008
3266
  return { ok: false, error: wsLookup.error };
3009
3267
  }
3010
3268
  const { wsPath, state } = wsLookup;
3011
- const containerName = state.containerName;
3269
+ const oldContainerName = state.containerName;
3270
+ const containerName = deriveContainerName(wsPath.name);
3012
3271
  const dockerAvailable = await deps.container.isDockerAvailable();
3013
3272
  if (!dockerAvailable) {
3014
3273
  return {
@@ -3037,20 +3296,23 @@ async function rebuildInstance(instanceName, deps, options, repoSlug) {
3037
3296
  return { ok: false, error: pullStepResult.error };
3038
3297
  }
3039
3298
  const { hasDockerfile } = pullStepResult;
3040
- const statusResult = await deps.container.containerStatus(containerName);
3299
+ const statusResult = await deps.container.containerStatus(oldContainerName);
3041
3300
  const wasRunning = statusResult.ok && statusResult.status === "running";
3042
3301
  if (wasRunning && !force) {
3043
3302
  return {
3044
3303
  ok: false,
3045
3304
  error: {
3046
3305
  code: "CONTAINER_RUNNING",
3047
- message: `Container '${containerName}' is currently running`,
3306
+ message: `Container '${oldContainerName}' is currently running`,
3048
3307
  suggestion: "Stop any active sessions first, or use --force to rebuild a running container."
3049
3308
  },
3050
3309
  wasRunning: true
3051
3310
  };
3052
3311
  }
3053
- const teardownResult = await teardownContainer(containerName, deps.container, statusResult);
3312
+ if (wasRunning) {
3313
+ await saveTmuxState(oldContainerName, deps);
3314
+ }
3315
+ const teardownResult = await teardownContainer(oldContainerName, deps.container, statusResult);
3054
3316
  if (!teardownResult.ok) {
3055
3317
  return { ok: false, error: teardownResult.error, wasRunning };
3056
3318
  }
@@ -3059,7 +3321,8 @@ async function rebuildInstance(instanceName, deps, options, repoSlug) {
3059
3321
  containerName,
3060
3322
  state.purpose ?? "",
3061
3323
  noCache && hasDockerfile,
3062
- deps.container
3324
+ deps.container,
3325
+ onProgress
3063
3326
  );
3064
3327
  if (!startResult.ok) {
3065
3328
  return { ok: false, error: startResult.error, wasRunning };
@@ -3100,7 +3363,7 @@ Any active sessions will be lost. Continue? (y/N) `,
3100
3363
  });
3101
3364
  });
3102
3365
  }
3103
- var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by recreating its container").argument("<name>", "Instance name to rebuild").option("--force", "Rebuild even if the container is currently running").option("--yes", "Skip confirmation prompt").option("--no-pull", "Skip pulling fresh base images").option("--use-cache", "Allow Docker build layer cache reuse").option("--repo <slug>", "Repo slug or URL to scope instance lookup").action(
3366
+ var rebuildCommand = new Command7("rebuild").description("Rebuild an instance by recreating its container").argument("<name>", "Instance name to rebuild").option("--force", "Rebuild even if the container is currently running").option("--yes", "Skip confirmation prompt").option("--no-pull", "Skip pulling fresh base images").option("--use-cache", "Allow Docker build layer cache reuse").option("--repo <slug>", "Repo slug or URL to scope instance lookup").action(
3104
3367
  async (name, options) => {
3105
3368
  const deps = createRebuildDefaultDeps();
3106
3369
  const repoSlug = await resolveRepoOrExit({ repo: options.repo, cwd: process.cwd() });
@@ -3113,55 +3376,62 @@ var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by
3113
3376
  }
3114
3377
  }
3115
3378
  const force = options.force || options.yes || confirmed;
3379
+ const progress = createProgressLine();
3116
3380
  const rebuildOptions = {
3117
3381
  force,
3118
3382
  pull: options.pull,
3119
- noCache: !options.useCache
3383
+ noCache: !options.useCache,
3384
+ onProgress: progress.update
3120
3385
  };
3121
3386
  if (force) {
3122
3387
  console.log(`Force-rebuilding instance '${name}'...`);
3123
3388
  } else {
3124
3389
  console.log(`Rebuilding instance '${name}'...`);
3125
3390
  }
3126
- const result = await rebuildInstance(name, deps, rebuildOptions, repoSlug);
3127
- if (!result.ok) {
3128
- if (result.error.code === "CONTAINER_RUNNING") {
3129
- console.error("");
3130
- console.error(
3131
- chalk.yellow("Container is currently running.") + " Active sessions will be terminated during rebuild."
3132
- );
3133
- console.error("");
3134
- console.error(`Use ${chalk.bold("--force")} to rebuild anyway.`);
3135
- } else {
3136
- const { code, message, suggestion } = result.error;
3137
- console.error(formatError(createError(code, message, suggestion)));
3391
+ try {
3392
+ const result = await rebuildInstance(name, deps, rebuildOptions, repoSlug);
3393
+ progress.clear();
3394
+ if (!result.ok) {
3395
+ if (result.error.code === "CONTAINER_RUNNING") {
3396
+ console.error("");
3397
+ console.error(
3398
+ chalk.yellow("Container is currently running.") + " Active sessions will be terminated during rebuild."
3399
+ );
3400
+ console.error("");
3401
+ console.error(`Use ${chalk.bold("--force")} to rebuild anyway.`);
3402
+ } else {
3403
+ const { code, message, suggestion } = result.error;
3404
+ console.error(formatError(createError(code, message, suggestion)));
3405
+ }
3406
+ process.exit(1);
3407
+ return;
3138
3408
  }
3139
- process.exit(1);
3140
- return;
3409
+ console.log(`\x1B[32m\u2713\x1B[0m Instance '${name}' rebuilt successfully`);
3410
+ console.log(` Container: ${result.containerName}`);
3411
+ } finally {
3412
+ progress.clear();
3141
3413
  }
3142
- console.log(`\x1B[32m\u2713\x1B[0m Instance '${name}' rebuilt successfully`);
3143
- console.log(` Container: ${result.containerName}`);
3144
3414
  }
3145
3415
  );
3146
3416
 
3147
3417
  // src/commands/remove.ts
3148
3418
  import chalk3 from "chalk";
3149
- import { Command as Command7 } from "commander";
3419
+ import { Command as Command8 } from "commander";
3150
3420
  import { createInterface as createInterface2 } from "readline";
3151
3421
 
3152
3422
  // src/lib/audit-log.ts
3153
- import { appendFile as appendFile6, mkdir as mkdir8 } from "fs/promises";
3154
- import { homedir as homedir6 } from "os";
3155
- import { join as join9 } from "path";
3423
+ import { appendFile as appendFile7, mkdir as mkdir9 } from "fs/promises";
3424
+ import { homedir as homedir7 } from "os";
3425
+ import { join as join10 } from "path";
3156
3426
  function createAuditLogDefaultDeps() {
3157
- return { appendFile: appendFile6, mkdir: mkdir8, homedir: homedir6 };
3427
+ return { appendFile: appendFile7, mkdir: mkdir9, homedir: homedir7 };
3158
3428
  }
3159
3429
  function getAuditLogPath(deps) {
3160
- return join9(deps.homedir(), AGENT_ENV_DIR, "audit.log");
3430
+ return join10(deps.homedir(), AGENT_ENV_DIR, "audit.log");
3161
3431
  }
3162
3432
  async function writeAuditLogEntry(entry, deps = createAuditLogDefaultDeps()) {
3163
3433
  const logPath = getAuditLogPath(deps);
3164
- await deps.mkdir(join9(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
3434
+ await deps.mkdir(join10(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
3165
3435
  const line = JSON.stringify(entry) + "\n";
3166
3436
  await deps.appendFile(logPath, line, "utf-8");
3167
3437
  }
@@ -3176,16 +3446,16 @@ function createAuditEntry(instanceName, gitState, confirmationMethod) {
3176
3446
  }
3177
3447
 
3178
3448
  // src/lib/remove-instance.ts
3179
- import { mkdir as mkdir9, readdir as readdir7, readFile as readFile10, rm as rm4, stat as stat7 } from "fs/promises";
3180
- import { homedir as homedir7 } from "os";
3449
+ import { mkdir as mkdir10, readdir as readdir8, readFile as readFile11, rm as rm4, stat as stat8 } from "fs/promises";
3450
+ import { homedir as homedir8 } from "os";
3181
3451
  function createRemoveDefaultDeps() {
3182
3452
  const executor = createExecutor();
3183
3453
  return {
3184
3454
  executor,
3185
3455
  container: createContainerLifecycle(executor),
3186
3456
  gitDetector: createGitStateDetector(executor),
3187
- workspaceFsDeps: { mkdir: mkdir9, readdir: readdir7, stat: stat7, homedir: homedir7 },
3188
- stateFsDeps: { readFile: readFile10 },
3457
+ workspaceFsDeps: { mkdir: mkdir10, readdir: readdir8, stat: stat8, homedir: homedir8 },
3458
+ stateFsDeps: { readFile: readFile11 },
3189
3459
  deleteFsDeps: { rm: rm4 }
3190
3460
  };
3191
3461
  }
@@ -3465,7 +3735,7 @@ async function resolveConfirmation(name, options) {
3465
3735
  }
3466
3736
  return "typed-name";
3467
3737
  }
3468
- var removeCommand = new Command7("remove").description("Remove an instance with safety checks").argument("<name>", "Instance name to remove").option("--repo <slug>", "Repo slug or URL to scope instance lookup").option("--force", "Force removal, bypassing safety checks").option(
3738
+ var removeCommand = new Command8("remove").description("Remove an instance with safety checks").argument("<name>", "Instance name to remove").option("--repo <slug>", "Repo slug or URL to scope instance lookup").option("--force", "Force removal, bypassing safety checks").option(
3469
3739
  "--yes",
3470
3740
  "Skip confirmation prompt for --force (DANGEROUS: skips all safety prompts, for scripts only)"
3471
3741
  ).action(async (name, options) => {
@@ -3528,8 +3798,8 @@ var removeCommand = new Command7("remove").description("Remove an instance with
3528
3798
  });
3529
3799
 
3530
3800
  // src/commands/repos.ts
3531
- import { Command as Command8 } from "commander";
3532
- var reposCommand = new Command8("repos").description("List tracked repositories").option("--json", "Output in JSON format").action(async (options) => {
3801
+ import { Command as Command9 } from "commander";
3802
+ var reposCommand = new Command9("repos").description("List tracked repositories").option("--json", "Output in JSON format").action(async (options) => {
3533
3803
  const result = await listRepos();
3534
3804
  if (!result.ok) {
3535
3805
  const error = createError(
@@ -3580,9 +3850,9 @@ var reposCommand = new Command8("repos").description("List tracked repositories"
3580
3850
  });
3581
3851
 
3582
3852
  // src/commands/setup-audio.ts
3583
- import { Command as Command9 } from "commander";
3584
- import { copyFile, mkdir as mkdir10, readFile as readFile11, writeFile as writeFile9, access as access5 } from "fs/promises";
3585
- import { homedir as homedir8, platform } from "os";
3853
+ import { Command as Command10 } from "commander";
3854
+ import { copyFile, mkdir as mkdir11, readFile as readFile12, writeFile as writeFile10, access as access5 } from "fs/promises";
3855
+ import { homedir as homedir9, platform } from "os";
3586
3856
 
3587
3857
  // src/lib/setup-audio.ts
3588
3858
  async function setupAudio(deps) {
@@ -3677,16 +3947,16 @@ function createDefaultSetupAudioDeps() {
3677
3947
  const exec = createExecutor();
3678
3948
  return {
3679
3949
  platform: platform(),
3680
- homeDir: homedir8(),
3950
+ homeDir: homedir9(),
3681
3951
  execute: exec,
3682
- readFile: (path, encoding) => readFile11(path, encoding),
3683
- writeFile: (path, content, encoding) => writeFile9(path, content, encoding),
3952
+ readFile: (path, encoding) => readFile12(path, encoding),
3953
+ writeFile: (path, content, encoding) => writeFile10(path, content, encoding),
3684
3954
  copyFile,
3685
- mkdir: (path, opts) => mkdir10(path, opts),
3955
+ mkdir: (path, opts) => mkdir11(path, opts),
3686
3956
  access: (path) => access5(path)
3687
3957
  };
3688
3958
  }
3689
- var setupAudioCommand = new Command9("setup-audio").description("Configure macOS PulseAudio for audio passthrough to containers").action(async () => {
3959
+ var setupAudioCommand = new Command10("setup-audio").description("Configure macOS PulseAudio for audio passthrough to containers").action(async () => {
3690
3960
  const deps = createDefaultSetupAudioDeps();
3691
3961
  const result = await setupAudio(deps);
3692
3962
  if (!result.ok) {
@@ -3705,13 +3975,227 @@ var setupAudioCommand = new Command9("setup-audio").description("Configure macOS
3705
3975
  );
3706
3976
  });
3707
3977
 
3978
+ // src/commands/tmux-restore.ts
3979
+ import { Command as Command11 } from "commander";
3980
+ import { execSync } from "child_process";
3981
+ import { join as join12 } from "path";
3982
+
3983
+ // src/lib/tmux-session.ts
3984
+ import { readFile as readFile13, writeFile as writeFile11, rename as rename8, mkdir as mkdir12 } from "fs/promises";
3985
+ import { dirname as dirname3, join as join11 } from "path";
3986
+ async function readPanesState(path) {
3987
+ try {
3988
+ const content = await readFile13(path, "utf-8");
3989
+ const parsed = JSON.parse(content);
3990
+ if (typeof parsed === "object" && parsed !== null && parsed.version === 1) {
3991
+ return parsed;
3992
+ }
3993
+ return { version: 1 };
3994
+ } catch {
3995
+ return { version: 1 };
3996
+ }
3997
+ }
3998
+ async function writePanesState(path, state) {
3999
+ await mkdir12(dirname3(path), { recursive: true });
4000
+ const tmpPath = path + ".tmp";
4001
+ await writeFile11(tmpPath, JSON.stringify(state), "utf-8");
4002
+ await rename8(tmpPath, path);
4003
+ }
4004
+ async function readSessionState(path) {
4005
+ try {
4006
+ const content = await readFile13(path, "utf-8");
4007
+ const parsed = JSON.parse(content);
4008
+ if (typeof parsed === "object" && parsed !== null && parsed.version === 1 && Array.isArray(parsed.windows)) {
4009
+ return parsed;
4010
+ }
4011
+ return null;
4012
+ } catch {
4013
+ return null;
4014
+ }
4015
+ }
4016
+ async function writeSessionState(path, state) {
4017
+ await mkdir12(dirname3(path), { recursive: true });
4018
+ const tmpPath = path + ".tmp";
4019
+ await writeFile11(tmpPath, JSON.stringify(state, null, 2), "utf-8");
4020
+ await rename8(tmpPath, path);
4021
+ }
4022
+ function pruneStaleEntries(state, activePaneIds) {
4023
+ const pruned = { version: 1 };
4024
+ const activeSet = new Set(activePaneIds);
4025
+ for (const [key, value] of Object.entries(state)) {
4026
+ if (key === "version") continue;
4027
+ if (activeSet.has(key)) {
4028
+ pruned[key] = value;
4029
+ }
4030
+ }
4031
+ return pruned;
4032
+ }
4033
+ function resolveTmuxStateDir(agentInstance) {
4034
+ const instance = agentInstance || process.env.AGENT_INSTANCE;
4035
+ if (!instance) return null;
4036
+ return join11("/shared-data/instance", instance, "tmux");
4037
+ }
4038
+
4039
+ // src/commands/tmux-restore.ts
4040
+ function shellQuote(s) {
4041
+ return "'" + s.replace(/'/g, "'\\''") + "'";
4042
+ }
4043
+ function tmuxExec(cmd) {
4044
+ return execSync(cmd, { encoding: "utf-8", timeout: 5e3 });
4045
+ }
4046
+ function tmuxExecSafe(cmd) {
4047
+ try {
4048
+ execSync(cmd, { encoding: "utf-8", timeout: 5e3 });
4049
+ return true;
4050
+ } catch {
4051
+ return false;
4052
+ }
4053
+ }
4054
+ function ensureTmuxSession(savedName) {
4055
+ try {
4056
+ const sessions = tmuxExec('tmux list-sessions -F "#{session_name}"').trim().split("\n").filter(Boolean);
4057
+ if (sessions.includes(savedName)) {
4058
+ return savedName;
4059
+ }
4060
+ if (sessions.length > 0) {
4061
+ return sessions[0];
4062
+ }
4063
+ } catch {
4064
+ }
4065
+ const name = savedName || "agent-env";
4066
+ tmuxExecSafe(`tmux new-session -d -s ${shellQuote(name)}`);
4067
+ return name;
4068
+ }
4069
+ async function executeTmuxRestore() {
4070
+ const stateDir = resolveTmuxStateDir();
4071
+ if (!stateDir) return;
4072
+ const sessionState = await readSessionState(join12(stateDir, "session.json"));
4073
+ if (!sessionState) return;
4074
+ const sessionName = ensureTmuxSession(sessionState.tmux_session);
4075
+ const quotedSession = shellQuote(sessionName);
4076
+ if (sessionState.windows.length === 0) return;
4077
+ for (const win of sessionState.windows) {
4078
+ tmuxExecSafe(
4079
+ `tmux new-window -t ${quotedSession} -n ${shellQuote(win.name)} -c ${shellQuote(win.cwd)}`
4080
+ );
4081
+ }
4082
+ tmuxExecSafe(`tmux kill-window -t ${quotedSession}:1`);
4083
+ for (let i = 0; i < sessionState.windows.length; i++) {
4084
+ const win = sessionState.windows[i];
4085
+ if (win.program === "claude" && win.claude_session_id) {
4086
+ const windowIndex = i + 1;
4087
+ tmuxExecSafe(
4088
+ `tmux send-keys -t ${quotedSession}:${windowIndex} ${shellQuote(`claude --resume ${win.claude_session_id} || claude`)} Enter`
4089
+ );
4090
+ }
4091
+ }
4092
+ if (sessionState.active_window) {
4093
+ const activeIdx = sessionState.windows.findIndex((w) => w.index === sessionState.active_window);
4094
+ if (activeIdx >= 0) {
4095
+ tmuxExecSafe(`tmux select-window -t ${quotedSession}:${activeIdx + 1}`);
4096
+ }
4097
+ }
4098
+ }
4099
+ var tmuxRestoreCommand = new Command11("tmux-restore").description("Restore tmux session state from saved state (container only)").action(async () => {
4100
+ try {
4101
+ await executeTmuxRestore();
4102
+ } catch {
4103
+ }
4104
+ });
4105
+
4106
+ // src/commands/tmux-save.ts
4107
+ import { Command as Command12 } from "commander";
4108
+ import { execSync as execSync2 } from "child_process";
4109
+ import { unlink as unlink2 } from "fs/promises";
4110
+ import { join as join13 } from "path";
4111
+ async function executeTmuxSave() {
4112
+ const stateDir = resolveTmuxStateDir();
4113
+ if (!stateDir) return;
4114
+ const sessionPath = join13(stateDir, "session.json");
4115
+ let tmuxOutput;
4116
+ try {
4117
+ tmuxOutput = execSync2(
4118
+ 'tmux list-panes -a -F "#{pane_id} #{window_index} #{window_name} #{pane_current_path} #{pane_current_command} #{session_name}"',
4119
+ { encoding: "utf-8", timeout: 5e3 }
4120
+ );
4121
+ } catch {
4122
+ await unlink2(sessionPath).catch(() => {
4123
+ });
4124
+ return;
4125
+ }
4126
+ const panes = tmuxOutput.trim().split("\n").filter((line) => line.trim()).map((line) => {
4127
+ const [paneId, indexStr, windowName, cwd, command, sessionName2] = line.split(" ");
4128
+ return {
4129
+ paneId,
4130
+ windowIndex: parseInt(indexStr, 10),
4131
+ windowName,
4132
+ cwd,
4133
+ command,
4134
+ sessionName: sessionName2
4135
+ };
4136
+ });
4137
+ if (panes.length === 0) {
4138
+ await unlink2(sessionPath).catch(() => {
4139
+ });
4140
+ return;
4141
+ }
4142
+ const panesPath = join13(stateDir, "claude-sessions.json");
4143
+ const panesState = await readPanesState(panesPath);
4144
+ let activeWindow = 1;
4145
+ try {
4146
+ const activeOutput = execSync2('tmux display-message -p "#{window_index}"', {
4147
+ encoding: "utf-8",
4148
+ timeout: 5e3
4149
+ });
4150
+ activeWindow = parseInt(activeOutput.trim(), 10) || 1;
4151
+ } catch {
4152
+ }
4153
+ const sessionName = panes[0].sessionName;
4154
+ const seenWindows = /* @__PURE__ */ new Set();
4155
+ const windows = [];
4156
+ for (const pane of panes) {
4157
+ if (seenWindows.has(pane.windowIndex)) continue;
4158
+ seenWindows.add(pane.windowIndex);
4159
+ const paneEntry = panesState[pane.paneId];
4160
+ const hasClaudeEntry = typeof paneEntry === "object" && paneEntry !== null && "session_id" in paneEntry;
4161
+ const isClaudeRunning = pane.command === "claude";
4162
+ const window = {
4163
+ index: pane.windowIndex,
4164
+ name: pane.windowName,
4165
+ cwd: pane.cwd,
4166
+ program: isClaudeRunning ? "claude" : null
4167
+ };
4168
+ if (isClaudeRunning && hasClaudeEntry) {
4169
+ window.claude_session_id = paneEntry.session_id;
4170
+ }
4171
+ windows.push(window);
4172
+ }
4173
+ const sessionState = {
4174
+ version: 1,
4175
+ saved_at: (/* @__PURE__ */ new Date()).toISOString(),
4176
+ tmux_session: sessionName,
4177
+ active_window: activeWindow,
4178
+ windows
4179
+ };
4180
+ await writeSessionState(sessionPath, sessionState);
4181
+ const activePaneIds = panes.map((p) => p.paneId);
4182
+ const pruned = pruneStaleEntries(panesState, activePaneIds);
4183
+ await writePanesState(panesPath, pruned);
4184
+ }
4185
+ var tmuxSaveCommand = new Command12("tmux-save").description("Save current tmux session state for persistence across rebuilds (container only)").action(async () => {
4186
+ try {
4187
+ await executeTmuxSave();
4188
+ } catch {
4189
+ }
4190
+ });
4191
+
3708
4192
  // src/commands/tmux-status.ts
3709
- import { Command as Command10 } from "commander";
4193
+ import { Command as Command13 } from "commander";
3710
4194
 
3711
4195
  // src/lib/tmux-status.ts
3712
- import { readFile as readFile12 } from "fs/promises";
4196
+ import { readFile as readFile14 } from "fs/promises";
3713
4197
  var MAX_PURPOSE_DISPLAY_LEN = 40;
3714
- var defaultDeps2 = { readFile: readFile12 };
4198
+ var defaultDeps2 = { readFile: readFile14 };
3715
4199
  function formatTmuxStatus(instance, purpose) {
3716
4200
  if (!instance) return "?";
3717
4201
  if (!purpose) return instance;
@@ -3747,7 +4231,7 @@ var defaultDeps3 = {
3747
4231
  statePath: CONTAINER_STATE_PATH
3748
4232
  };
3749
4233
  function createTmuxStatusCommand(deps = defaultDeps3) {
3750
- return new Command10("tmux-status").description("Output formatted instance status for tmux status bar (container only)").action(async () => {
4234
+ return new Command13("tmux-status").description("Output formatted instance status for tmux status bar (container only)").action(async () => {
3751
4235
  if (!deps.isInsideContainer()) {
3752
4236
  console.log("?");
3753
4237
  return;
@@ -3930,18 +4414,22 @@ Purpose for ${name}:`);
3930
4414
  }
3931
4415
 
3932
4416
  // src/cli.ts
3933
- var __dirname = dirname3(fileURLToPath2(import.meta.url));
4417
+ var __dirname = dirname4(fileURLToPath2(import.meta.url));
3934
4418
  var isLinked = existsSync(resolve(__dirname, "..", "..", "..", "pnpm-workspace.yaml"));
3935
- var version = package_default.version + (isLinked ? "+local" : "");
4419
+ var isBakedDev = resolve(__dirname, "..").startsWith("/opt/agent-env-dev");
4420
+ var version = package_default.version + (isLinked ? "+local" : isBakedDev ? "+dev" : "");
3936
4421
  program.name("agent-env").description("CLI for creating isolated, AI-ready development environments").version(version).allowExcessArguments(true);
3937
4422
  program.addCommand(createCommand);
3938
4423
  program.addCommand(listCommand);
3939
4424
  program.addCommand(attachCommand);
4425
+ program.addCommand(codeCommand);
3940
4426
  program.addCommand(rebuildCommand);
3941
4427
  program.addCommand(removeCommand);
3942
4428
  program.addCommand(purposeCommand);
3943
4429
  program.addCommand(reposCommand);
3944
4430
  program.addCommand(tmuxStatusCommand);
4431
+ program.addCommand(tmuxSaveCommand);
4432
+ program.addCommand(tmuxRestoreCommand);
3945
4433
  program.addCommand(completionCommand);
3946
4434
  program.addCommand(setupAudioCommand);
3947
4435
  program.action(async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zookanalytics/agent-env",
3
- "version": "0.8.0",
3
+ "version": "0.9.1",
4
4
  "description": "CLI for creating isolated, AI-ready development environments",
5
5
  "type": "module",
6
6
  "bin": {