@zookanalytics/agent-env 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli.js +255 -70
  2. package/package.json +2 -1
package/dist/cli.js CHANGED
@@ -42,7 +42,7 @@ import React3 from "react";
42
42
  // package.json
43
43
  var package_default = {
44
44
  name: "@zookanalytics/agent-env",
45
- version: "0.1.3",
45
+ version: "0.2.0",
46
46
  description: "CLI for creating isolated, AI-ready development environments",
47
47
  type: "module",
48
48
  bin: {
@@ -85,6 +85,7 @@ var package_default = {
85
85
  commander: "^14.0.2",
86
86
  execa: "^9.6.1",
87
87
  ink: "^6.6.0",
88
+ "jsonc-parser": "^3.3.1",
88
89
  react: "^19.2.3",
89
90
  "timeago.js": "^4.0.2"
90
91
  },
@@ -107,10 +108,26 @@ import { homedir as homedir3 } from "os";
107
108
 
108
109
  // src/lib/container.ts
109
110
  var DEVCONTAINER_UP_TIMEOUT = 12e4;
111
+ var DEVCONTAINER_UP_NO_CACHE_TIMEOUT = 3e5;
112
+ var DOCKER_PULL_TIMEOUT = 3e5;
110
113
  var DOCKER_INSPECT_TIMEOUT = 1e4;
111
114
  var DOCKER_INFO_TIMEOUT = 5e3;
112
115
  var DOCKER_STOP_TIMEOUT = 3e4;
113
116
  var DOCKER_RM_TIMEOUT = 1e4;
117
+ function parseDevcontainerOutput(stdout) {
118
+ try {
119
+ return JSON.parse(stdout);
120
+ } catch {
121
+ const lines = stdout.trim().split("\n");
122
+ for (let i = lines.length - 1; i >= 0; i--) {
123
+ try {
124
+ return JSON.parse(lines[i]);
125
+ } catch {
126
+ }
127
+ }
128
+ }
129
+ return null;
130
+ }
114
131
  function createContainerLifecycle(executor = createExecutor()) {
115
132
  async function isDockerAvailable() {
116
133
  const result = await executor("docker", ["info"], { timeout: DOCKER_INFO_TIMEOUT });
@@ -199,7 +216,7 @@ function createContainerLifecycle(executor = createExecutor()) {
199
216
  const name = result.stdout.trim().split("\n")[0]?.trim();
200
217
  return name || null;
201
218
  }
202
- async function devcontainerUp(workspacePath, containerName) {
219
+ async function devcontainerUp(workspacePath, containerName, options) {
203
220
  const dockerOk = await isDockerAvailable();
204
221
  if (!dockerOk) {
205
222
  return {
@@ -213,22 +230,17 @@ function createContainerLifecycle(executor = createExecutor()) {
213
230
  }
214
231
  };
215
232
  }
216
- const result = await executor("devcontainer", ["up", "--workspace-folder", workspacePath], {
217
- timeout: DEVCONTAINER_UP_TIMEOUT
233
+ const buildNoCache = options?.buildNoCache === true;
234
+ const args = [
235
+ "up",
236
+ "--workspace-folder",
237
+ workspacePath,
238
+ ...buildNoCache ? ["--build-no-cache"] : []
239
+ ];
240
+ const result = await executor("devcontainer", args, {
241
+ timeout: buildNoCache ? DEVCONTAINER_UP_NO_CACHE_TIMEOUT : DEVCONTAINER_UP_TIMEOUT
218
242
  });
219
- let parsedOutput = null;
220
- try {
221
- parsedOutput = JSON.parse(result.stdout);
222
- } catch {
223
- const lines = result.stdout.trim().split("\n");
224
- for (let i = lines.length - 1; i >= 0; i--) {
225
- try {
226
- parsedOutput = JSON.parse(lines[i]);
227
- break;
228
- } catch {
229
- }
230
- }
231
- }
243
+ const parsedOutput = parseDevcontainerOutput(result.stdout);
232
244
  if (!result.ok) {
233
245
  const parts = [];
234
246
  if (parsedOutput?.message) parts.push(parsedOutput.message);
@@ -294,12 +306,29 @@ function createContainerLifecycle(executor = createExecutor()) {
294
306
  }
295
307
  };
296
308
  }
309
+ async function dockerPull(image) {
310
+ const result = await executor("docker", ["pull", image], {
311
+ timeout: DOCKER_PULL_TIMEOUT
312
+ });
313
+ if (result.ok) {
314
+ return { ok: true };
315
+ }
316
+ return {
317
+ ok: false,
318
+ error: {
319
+ code: "IMAGE_PULL_FAILED",
320
+ message: `Failed to pull '${image}': ${result.stderr}`,
321
+ suggestion: "Check network connectivity and image name. Use --no-pull to skip pulling and use cached images."
322
+ }
323
+ };
324
+ }
297
325
  return {
298
326
  isDockerAvailable,
299
327
  containerStatus,
300
328
  getContainerNameById,
301
329
  findContainerByWorkspaceLabel,
302
330
  devcontainerUp,
331
+ dockerPull,
303
332
  containerStop,
304
333
  containerRemove
305
334
  };
@@ -321,6 +350,7 @@ import { homedir as homedir2 } from "os";
321
350
  import { dirname as dirname2 } from "path";
322
351
 
323
352
  // src/lib/devcontainer.ts
353
+ import { parse as parseJsonc } from "jsonc-parser";
324
354
  import { access, cp, mkdir, readdir, readFile, stat, writeFile } from "fs/promises";
325
355
  import { dirname, join } from "path";
326
356
  import { fileURLToPath } from "url";
@@ -382,6 +412,75 @@ async function listBaselineFiles(deps = defaultFsDeps) {
382
412
  const entries = await deps.readdir(baselinePath);
383
413
  return entries.sort();
384
414
  }
415
+ async function resolveDockerfilePath(workspacePath, deps) {
416
+ const candidates = [
417
+ join(workspacePath, DEVCONTAINER_DIR, DEVCONTAINER_JSON),
418
+ join(workspacePath, DEVCONTAINER_JSON),
419
+ join(workspacePath, DOT_DEVCONTAINER_JSON)
420
+ ];
421
+ let configPath = null;
422
+ for (const candidate of candidates) {
423
+ try {
424
+ await deps.stat(candidate);
425
+ configPath = candidate;
426
+ break;
427
+ } catch {
428
+ }
429
+ }
430
+ if (!configPath) {
431
+ return null;
432
+ }
433
+ const content = await deps.readFile(configPath, "utf-8");
434
+ const errors = [];
435
+ const config = parseJsonc(content, errors, { allowTrailingComma: true });
436
+ if (errors.length > 0) {
437
+ throw new Error(`Failed to parse devcontainer config at ${configPath}: Invalid JSONC`);
438
+ }
439
+ const configDir = dirname(configPath);
440
+ if (config?.build?.dockerfile) {
441
+ return join(configDir, config.build.dockerfile);
442
+ }
443
+ if (config?.dockerfile) {
444
+ return join(configDir, config.dockerfile);
445
+ }
446
+ try {
447
+ await deps.stat(join(configDir, "Dockerfile"));
448
+ return join(configDir, "Dockerfile");
449
+ } catch {
450
+ return null;
451
+ }
452
+ }
453
+ function parseDockerfileImages(content, logger) {
454
+ const fromRegex = /^\s*FROM\s+(?:--\S+\s+)*(\S+)(?:\s+[Aa][Ss]\s+(\S+))?/i;
455
+ const stageNames = /* @__PURE__ */ new Set();
456
+ const images = /* @__PURE__ */ new Set();
457
+ for (const line of content.split("\n")) {
458
+ if (line.trim().startsWith("#")) continue;
459
+ const match = fromRegex.exec(line);
460
+ if (match?.[2]) {
461
+ stageNames.add(match[2].toLowerCase());
462
+ }
463
+ }
464
+ for (const line of content.split("\n")) {
465
+ const trimmed = line.trim();
466
+ if (trimmed.startsWith("#")) continue;
467
+ const match = fromRegex.exec(line);
468
+ if (!match) continue;
469
+ const image = match[1];
470
+ if (image.includes("$")) {
471
+ logger?.warn(`Skipping parameterized FROM: ${image}`);
472
+ continue;
473
+ }
474
+ if (image.toLowerCase() === "scratch") {
475
+ continue;
476
+ }
477
+ if (stageNames.has(image.toLowerCase())) {
478
+ continue;
479
+ }
480
+ images.add(image);
481
+ }
482
+ return [...images];
483
+ }
385
484
 
386
485
  // src/lib/state.ts
387
486
  import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
@@ -1644,7 +1743,7 @@ async function refreshConfig(wsRoot, containerName, configSource, deps) {
1644
1743
  }
1645
1744
  return { ok: true };
1646
1745
  }
1647
- async function rebuildInstance(instanceName, deps, force = false, overrideConfigSource) {
1746
+ async function lookupWorkspace(instanceName, deps) {
1648
1747
  const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1649
1748
  if (!lookup.found) {
1650
1749
  if (lookup.reason === "ambiguous") {
@@ -1668,6 +1767,93 @@ async function rebuildInstance(instanceName, deps, force = false, overrideConfig
1668
1767
  }
1669
1768
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1670
1769
  const state = await readState(wsPath, deps.stateFsDeps);
1770
+ return { ok: true, wsPath, state };
1771
+ }
1772
+ async function executePullStep(wsRoot, pull, deps) {
1773
+ let dockerfilePath;
1774
+ try {
1775
+ dockerfilePath = await resolveDockerfilePath(wsRoot, deps.devcontainerFsDeps);
1776
+ } catch (err) {
1777
+ return {
1778
+ ok: false,
1779
+ error: {
1780
+ code: "CONFIG_PARSE_FAILED",
1781
+ message: err instanceof Error ? err.message : String(err),
1782
+ suggestion: "Check that your devcontainer.json is valid JSON or JSONC."
1783
+ }
1784
+ };
1785
+ }
1786
+ const hasDockerfile = dockerfilePath !== null;
1787
+ if (!pull) {
1788
+ return { ok: true, hasDockerfile };
1789
+ }
1790
+ if (dockerfilePath === null) {
1791
+ deps.logger?.info("No Dockerfile found \u2014 skipping image pull.");
1792
+ return { ok: true, hasDockerfile: false };
1793
+ }
1794
+ let dockerfileContent;
1795
+ try {
1796
+ dockerfileContent = await deps.devcontainerFsDeps.readFile(dockerfilePath, "utf-8");
1797
+ } catch {
1798
+ return {
1799
+ ok: false,
1800
+ error: {
1801
+ code: "DOCKERFILE_MISSING",
1802
+ message: `Dockerfile not found at ${dockerfilePath}`,
1803
+ suggestion: "Ensure the Dockerfile exists at the configured path, or use --no-pull to skip."
1804
+ }
1805
+ };
1806
+ }
1807
+ const images = parseDockerfileImages(dockerfileContent, deps.logger);
1808
+ if (images.length === 0) {
1809
+ deps.logger?.info("No pullable FROM images found.");
1810
+ return { ok: true, hasDockerfile };
1811
+ }
1812
+ const results = await Promise.allSettled(
1813
+ images.map(async (image) => {
1814
+ deps.logger?.info(`Pulling ${image}...`);
1815
+ const pullResult = await deps.container.dockerPull(image);
1816
+ if (!pullResult.ok) {
1817
+ throw pullResult.error;
1818
+ }
1819
+ deps.logger?.info(`Pulled ${image}`);
1820
+ })
1821
+ );
1822
+ const firstFailure = results.find((r) => r.status === "rejected");
1823
+ if (firstFailure) {
1824
+ return {
1825
+ ok: false,
1826
+ error: firstFailure.reason
1827
+ };
1828
+ }
1829
+ return { ok: true, hasDockerfile };
1830
+ }
1831
+ async function teardownContainer(containerName, container, statusResult) {
1832
+ if (!statusResult.ok || statusResult.status === "not-found") {
1833
+ return { ok: true };
1834
+ }
1835
+ const stopResult = await container.containerStop(containerName);
1836
+ if (!stopResult.ok) {
1837
+ return { ok: false, error: stopResult.error };
1838
+ }
1839
+ const removeResult = await container.containerRemove(containerName);
1840
+ if (!removeResult.ok) {
1841
+ return { ok: false, error: removeResult.error };
1842
+ }
1843
+ return { ok: true };
1844
+ }
1845
+ async function rebuildInstance(instanceName, deps, options) {
1846
+ const {
1847
+ force = false,
1848
+ configSource: overrideConfigSource,
1849
+ pull = true,
1850
+ noCache = true
1851
+ } = options ?? {};
1852
+ const wsLookup = await lookupWorkspace(instanceName, deps);
1853
+ if (!wsLookup.ok) {
1854
+ return { ok: false, error: wsLookup.error };
1855
+ }
1856
+ const { wsPath, state } = wsLookup;
1671
1857
  const containerName = state.containerName;
1672
1858
  const dockerAvailable = await deps.container.isDockerAvailable();
1673
1859
  if (!dockerAvailable) {
@@ -1695,6 +1881,11 @@ async function rebuildInstance(instanceName, deps, force = false, overrideConfig
1695
1881
  if (!configResult.ok) {
1696
1882
  return { ok: false, error: configResult.error };
1697
1883
  }
1884
+ const pullStepResult = await executePullStep(wsPath.root, pull, deps);
1885
+ if (!pullStepResult.ok) {
1886
+ return { ok: false, error: pullStepResult.error };
1887
+ }
1888
+ const { hasDockerfile } = pullStepResult;
1698
1889
  const statusResult = await deps.container.containerStatus(containerName);
1699
1890
  const wasRunning = statusResult.ok && statusResult.status === "running";
1700
1891
  if (wasRunning && !force) {
@@ -1708,27 +1899,14 @@ async function rebuildInstance(instanceName, deps, force = false, overrideConfig
1708
1899
  wasRunning: true
1709
1900
  };
1710
1901
  }
1711
- if (statusResult.ok && statusResult.status !== "not-found") {
1712
- const stopResult = await deps.container.containerStop(containerName);
1713
- if (!stopResult.ok) {
1714
- return {
1715
- ok: false,
1716
- error: stopResult.error,
1717
- wasRunning
1718
- };
1719
- }
1902
+ const teardownResult = await teardownContainer(containerName, deps.container, statusResult);
1903
+ if (!teardownResult.ok) {
1904
+ return { ok: false, error: teardownResult.error, wasRunning };
1720
1905
  }
1721
- if (statusResult.ok && statusResult.status !== "not-found") {
1722
- const removeResult = await deps.container.containerRemove(containerName);
1723
- if (!removeResult.ok) {
1724
- return {
1725
- ok: false,
1726
- error: removeResult.error,
1727
- wasRunning
1728
- };
1729
- }
1730
- }
1731
- const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName);
1906
+ const buildNoCache = noCache && hasDockerfile;
1907
+ const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
1908
+ buildNoCache
1909
+ });
1732
1910
  if (!containerResult.ok) {
1733
1911
  return {
1734
1912
  ok: false,
@@ -1778,41 +1956,48 @@ Any active sessions will be lost. Continue? (y/N) `,
1778
1956
  });
1779
1957
  });
1780
1958
  }
1781
- var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by recreating its container").argument("<name>", "Instance name to rebuild").option("--force", "Rebuild even if the container is currently running").option("--yes", "Skip confirmation prompt").action(async (name, options) => {
1782
- const deps = createRebuildDefaultDeps();
1783
- let confirmed = false;
1784
- if (!options.yes && !options.force && process.stdin.isTTY) {
1785
- confirmed = await promptForConfirmation(name);
1786
- if (!confirmed) {
1787
- console.log("Rebuild cancelled");
1788
- return;
1959
+ var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by recreating its container").argument("<name>", "Instance name to rebuild").option("--force", "Rebuild even if the container is currently running").option("--yes", "Skip confirmation prompt").option("--no-pull", "Skip pulling fresh base images").option("--use-cache", "Allow Docker build layer cache reuse").action(
1960
+ async (name, options) => {
1961
+ const deps = createRebuildDefaultDeps();
1962
+ let confirmed = false;
1963
+ if (!options.yes && !options.force && process.stdin.isTTY) {
1964
+ confirmed = await promptForConfirmation(name);
1965
+ if (!confirmed) {
1966
+ console.log("Rebuild cancelled");
1967
+ return;
1968
+ }
1789
1969
  }
1790
- }
1791
- const force = options.force || options.yes || confirmed;
1792
- if (force) {
1793
- console.log(`Force-rebuilding instance '${name}'...`);
1794
- } else {
1795
- console.log(`Rebuilding instance '${name}'...`);
1796
- }
1797
- const result = await rebuildInstance(name, deps, force);
1798
- if (!result.ok) {
1799
- if (result.error.code === "CONTAINER_RUNNING") {
1800
- console.error("");
1801
- console.error(
1802
- chalk.yellow("Container is currently running.") + " Active sessions will be terminated during rebuild."
1803
- );
1804
- console.error("");
1805
- console.error(`Use ${chalk.bold("--force")} to rebuild anyway.`);
1970
+ const force = options.force || options.yes || confirmed;
1971
+ const rebuildOptions = {
1972
+ force,
1973
+ pull: options.pull,
1974
+ noCache: !options.useCache
1975
+ };
1976
+ if (force) {
1977
+ console.log(`Force-rebuilding instance '${name}'...`);
1806
1978
  } else {
1807
- const { code, message, suggestion } = result.error;
1808
- console.error(formatError(createError(code, message, suggestion)));
1979
+ console.log(`Rebuilding instance '${name}'...`);
1809
1980
  }
1810
- process.exit(1);
1811
- return;
1981
+ const result = await rebuildInstance(name, deps, rebuildOptions);
1982
+ if (!result.ok) {
1983
+ if (result.error.code === "CONTAINER_RUNNING") {
1984
+ console.error("");
1985
+ console.error(
1986
+ chalk.yellow("Container is currently running.") + " Active sessions will be terminated during rebuild."
1987
+ );
1988
+ console.error("");
1989
+ console.error(`Use ${chalk.bold("--force")} to rebuild anyway.`);
1990
+ } else {
1991
+ const { code, message, suggestion } = result.error;
1992
+ console.error(formatError(createError(code, message, suggestion)));
1993
+ }
1994
+ process.exit(1);
1995
+ return;
1996
+ }
1997
+ console.log(`\x1B[32m\u2713\x1B[0m Instance '${name}' rebuilt successfully`);
1998
+ console.log(` Container: ${result.containerName}`);
1812
1999
  }
1813
- console.log(`\x1B[32m\u2713\x1B[0m Instance '${name}' rebuilt successfully`);
1814
- console.log(` Container: ${result.containerName}`);
1815
- });
2000
+ );
1816
2001
 
1817
2002
  // src/commands/remove.ts
1818
2003
  import chalk3 from "chalk";
@@ -2359,7 +2544,7 @@ async function launchInteractiveMenu(deps) {
2359
2544
  }
2360
2545
  case "rebuild": {
2361
2546
  const rebuildDeps = deps.createRebuildDeps();
2362
- const rebuildResult = await deps.rebuildInstance(name, rebuildDeps, true);
2547
+ const rebuildResult = await deps.rebuildInstance(name, rebuildDeps, { force: true });
2363
2548
  if (!rebuildResult.ok) return { ok: false, error: rebuildResult.error };
2364
2549
  return { ok: true, action: "rebuilt", instanceName: name };
2365
2550
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zookanalytics/agent-env",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
4
  "description": "CLI for creating isolated, AI-ready development environments",
5
5
  "type": "module",
6
6
  "bin": {
@@ -33,6 +33,7 @@
33
33
  "commander": "^14.0.2",
34
34
  "execa": "^9.6.1",
35
35
  "ink": "^6.6.0",
36
+ "jsonc-parser": "^3.3.1",
36
37
  "react": "^19.2.3",
37
38
  "timeago.js": "^4.0.2"
38
39
  },