@zookanalytics/agent-env 0.3.1 → 0.5.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.
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.3.1",
45
+ version: "0.5.0",
46
46
  description: "CLI for creating isolated, AI-ready development environments",
47
47
  type: "module",
48
48
  bin: {
@@ -103,9 +103,9 @@ var package_default = {
103
103
  import { Command } from "commander";
104
104
 
105
105
  // src/lib/attach-instance.ts
106
- import { appendFile as appendFile3, mkdir as mkdir5, readdir as readdir4, readFile as readFile4, rename as rename3, stat as stat4, writeFile as writeFile4 } from "fs/promises";
107
- import { homedir as homedir3 } from "os";
108
- import { join as join5 } from "path";
106
+ import { appendFile as appendFile4, mkdir as mkdir6, readdir as readdir5, readFile as readFile7, rename as rename4, stat as stat5, writeFile as writeFile6 } from "fs/promises";
107
+ import { homedir as homedir4 } from "os";
108
+ import { join as join6 } from "path";
109
109
 
110
110
  // src/lib/container.ts
111
111
  var DEVCONTAINER_UP_TIMEOUT = 3e5;
@@ -189,7 +189,8 @@ function createContainerLifecycle(executor = createExecutor()) {
189
189
  ok: true,
190
190
  status: "not-found",
191
191
  containerId: null,
192
- ports: {}
192
+ ports: {},
193
+ labels: {}
193
194
  };
194
195
  }
195
196
  return {
@@ -209,7 +210,8 @@ function createContainerLifecycle(executor = createExecutor()) {
209
210
  ok: true,
210
211
  status: "not-found",
211
212
  containerId: null,
212
- ports: {}
213
+ ports: {},
214
+ labels: {}
213
215
  };
214
216
  }
215
217
  const container = inspectData[0];
@@ -222,14 +224,18 @@ function createContainerLifecycle(executor = createExecutor()) {
222
224
  for (const [key, mappings] of Object.entries(dockerPorts)) {
223
225
  if (mappings && mappings.length > 0) {
224
226
  ports[key] = mappings[0].HostPort;
227
+ } else {
228
+ ports[key] = "";
225
229
  }
226
230
  }
227
231
  }
232
+ const labels = container.Config?.Labels ?? {};
228
233
  return {
229
234
  ok: true,
230
235
  status,
231
236
  containerId,
232
- ports
237
+ ports,
238
+ labels
233
239
  };
234
240
  } catch (e) {
235
241
  const errorMessage = e instanceof Error ? e.message : String(e);
@@ -329,7 +335,8 @@ function createContainerLifecycle(executor = createExecutor()) {
329
335
  ok: true,
330
336
  status: "running",
331
337
  containerId,
332
- ports: {}
338
+ ports: {},
339
+ labels: {}
333
340
  };
334
341
  }
335
342
  async function containerStop(containerName) {
@@ -399,18 +406,18 @@ function createContainerLifecycle(executor = createExecutor()) {
399
406
 
400
407
  // src/lib/create-instance.ts
401
408
  import {
402
- appendFile as appendFile2,
409
+ appendFile as appendFile3,
403
410
  cp as cp2,
404
- mkdir as mkdir4,
405
- readdir as readdir3,
406
- readFile as readFile3,
407
- rename as rename2,
411
+ mkdir as mkdir5,
412
+ readdir as readdir4,
413
+ readFile as readFile6,
414
+ rename as rename3,
408
415
  rm as rm2,
409
- stat as stat3,
410
- writeFile as writeFile3
416
+ stat as stat4,
417
+ writeFile as writeFile5
411
418
  } from "fs/promises";
412
- import { homedir as homedir2 } from "os";
413
- import { dirname as dirname2, join as join4 } from "path";
419
+ import { homedir as homedir3 } from "os";
420
+ import { dirname as dirname2, join as join5 } from "path";
414
421
 
415
422
  // src/lib/devcontainer.ts
416
423
  import { parse as parseJsonc } from "jsonc-parser";
@@ -418,16 +425,35 @@ import { access, cp, mkdir, readdir, readFile, stat, writeFile } from "fs/promis
418
425
  import { dirname, join } from "path";
419
426
  import { fileURLToPath } from "url";
420
427
 
428
+ // src/lib/container-env.ts
429
+ var CONTAINER_STATE_PATH = "/etc/agent-env/state.json";
430
+ var CONTAINER_AGENT_ENV_DIR = "/etc/agent-env";
431
+ var defaultContainerEnvDeps = {
432
+ getEnv: (key) => process.env[key]
433
+ };
434
+ function isInsideContainer(deps = defaultContainerEnvDeps) {
435
+ return deps.getEnv("AGENT_ENV_CONTAINER") === "true";
436
+ }
437
+
421
438
  // src/lib/types.ts
422
439
  var AGENT_ENV_DIR = ".agent-env";
423
440
  var WORKSPACES_DIR = "workspaces";
424
441
  var STATE_FILE = "state.json";
425
442
  var STATE_FILE_TMP = "state.json.tmp";
426
443
  var CONTAINER_PREFIX = "ae-";
444
+ var MAX_INSTANCE_NAME_LENGTH = 20;
445
+ var MAX_REPO_SLUG_LENGTH = 39;
446
+ var MAX_CONTAINER_NAME_LENGTH = 63;
447
+ if (CONTAINER_PREFIX.length + MAX_REPO_SLUG_LENGTH + 1 + MAX_INSTANCE_NAME_LENGTH !== MAX_CONTAINER_NAME_LENGTH) {
448
+ throw new Error(
449
+ "BUG: MAX_CONTAINER_NAME_LENGTH does not equal CONTAINER_PREFIX + MAX_REPO_SLUG_LENGTH + 1 + MAX_INSTANCE_NAME_LENGTH"
450
+ );
451
+ }
427
452
  function createFallbackState(workspaceName) {
428
453
  return {
429
- name: workspaceName,
430
- repo: "unknown",
454
+ instance: workspaceName,
455
+ repoSlug: "unknown",
456
+ repoUrl: "unknown",
431
457
  createdAt: "unknown",
432
458
  lastAttached: "unknown",
433
459
  purpose: null,
@@ -445,6 +471,11 @@ function getBaselineConfigPath() {
445
471
  const packageRoot = dirname(dirname(dirname(currentFile)));
446
472
  return join(packageRoot, "config", "baseline");
447
473
  }
474
+ function getTemplatesPath() {
475
+ const currentFile = fileURLToPath(import.meta.url);
476
+ const packageRoot = dirname(dirname(dirname(currentFile)));
477
+ return join(packageRoot, "config", "templates");
478
+ }
448
479
  async function hasDevcontainerConfig(workspacePath, deps = defaultFsDeps) {
449
480
  try {
450
481
  const dirStats = await deps.stat(join(workspacePath, DEVCONTAINER_DIR));
@@ -480,13 +511,70 @@ async function copyBaselineConfig(workspacePath, deps = defaultFsDeps) {
480
511
  await deps.mkdir(targetDir, { recursive: true });
481
512
  await deps.cp(baselinePath, targetDir, { recursive: true });
482
513
  }
483
- async function patchContainerName(workspacePath, containerName, deps = defaultFsDeps, configDir = DEVCONTAINER_DIR) {
484
- const configPath = join(workspacePath, configDir, DEVCONTAINER_JSON);
485
- const content = await deps.readFile(configPath, "utf-8");
486
- const config = JSON.parse(content);
514
+ async function copyStatusBarTemplate(workspacePath, deps = defaultFsDeps) {
515
+ const templatesPath = getTemplatesPath();
516
+ const srcFile = join(templatesPath, "statusBar.template.json");
517
+ try {
518
+ await deps.stat(srcFile);
519
+ } catch (err) {
520
+ if (err.code === "ENOENT") return;
521
+ throw err;
522
+ }
523
+ const targetDir = join(workspacePath, AGENT_ENV_DIR);
524
+ await deps.mkdir(targetDir, { recursive: true });
525
+ await deps.cp(srcFile, join(targetDir, "statusBar.template.json"));
526
+ }
527
+ var STATUS_BAR_JSON_FILENAME = "statusBar.json";
528
+ function applyContainerNamePatch(config, containerName) {
487
529
  const existing = Array.isArray(config.runArgs) ? config.runArgs : [];
488
530
  const filtered = existing.filter((arg) => !arg.startsWith("--name="));
489
531
  config.runArgs = [...filtered, `--name=${containerName}`];
532
+ return config;
533
+ }
534
+ function applyContainerEnvPatch(config, envVars) {
535
+ const existing = typeof config.containerEnv === "object" && config.containerEnv !== null ? config.containerEnv : {};
536
+ config.containerEnv = { ...existing, ...envVars };
537
+ return config;
538
+ }
539
+ function applyVscodeSettingsPatch(config) {
540
+ if (typeof config.customizations !== "object" || config.customizations === null) {
541
+ config.customizations = {};
542
+ }
543
+ const customizations = config.customizations;
544
+ if (typeof customizations.vscode !== "object" || customizations.vscode === null) {
545
+ customizations.vscode = {};
546
+ }
547
+ const vscode = customizations.vscode;
548
+ if (typeof vscode.settings !== "object" || vscode.settings === null) {
549
+ vscode.settings = {};
550
+ }
551
+ const settings = vscode.settings;
552
+ const existingFilewatcherCommands = Array.isArray(settings["filewatcher.commands"]) ? settings["filewatcher.commands"] : [];
553
+ const statusBarWatcher = {
554
+ match: `${STATUS_BAR_JSON_FILENAME}$`,
555
+ event: "onFolderChange",
556
+ vscodeTask: "betterStatusBar.refreshButtons"
557
+ };
558
+ const hasStatusBarWatcher = existingFilewatcherCommands.some((cmd) => {
559
+ if (typeof cmd !== "object" || cmd === null) return false;
560
+ const c = cmd;
561
+ return c.match === statusBarWatcher.match && c.event === statusBarWatcher.event && c.vscodeTask === statusBarWatcher.vscodeTask;
562
+ });
563
+ const mergedFilewatcherCommands = hasStatusBarWatcher ? existingFilewatcherCommands : [...existingFilewatcherCommands, statusBarWatcher];
564
+ vscode.settings = {
565
+ ...settings,
566
+ "betterStatusBar.configurationFile": `${CONTAINER_AGENT_ENV_DIR}/${STATUS_BAR_JSON_FILENAME}`,
567
+ "filewatcher.commands": mergedFilewatcherCommands
568
+ };
569
+ return config;
570
+ }
571
+ async function applyBaselinePatches(workspacePath, containerName, envVars, deps, configDir) {
572
+ const configPath = join(workspacePath, configDir, "devcontainer.json");
573
+ const content = await deps.readFile(configPath, "utf-8");
574
+ let config = JSON.parse(content);
575
+ config = applyContainerNamePatch(config, containerName);
576
+ config = applyContainerEnvPatch(config, envVars);
577
+ config = applyVscodeSettingsPatch(config);
490
578
  await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
491
579
  }
492
580
  async function resolveDockerfilePath(workspacePath, deps) {
@@ -559,6 +647,10 @@ function parseDockerfileImages(content, logger) {
559
647
  return [...images];
560
648
  }
561
649
 
650
+ // src/lib/purpose-instance.ts
651
+ import { appendFile as appendFile2, mkdir as mkdir4, readdir as readdir3, readFile as readFile5, rename as rename2, stat as stat3, writeFile as writeFile4 } from "fs/promises";
652
+ import { homedir as homedir2 } from "os";
653
+
562
654
  // src/lib/state.ts
563
655
  import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
564
656
  import { join as join2 } from "path";
@@ -568,7 +660,7 @@ async function readState(wsPath, deps = defaultStateFsDeps) {
568
660
  const content = await deps.readFile(wsPath.stateFile, "utf-8");
569
661
  const parsed = JSON.parse(content);
570
662
  if (!isValidState(parsed)) {
571
- return createFallbackState(wsPath.name);
663
+ return migrateOldState(parsed, wsPath.name) ?? createFallbackState(wsPath.name);
572
664
  }
573
665
  return parsed;
574
666
  } catch (err) {
@@ -585,36 +677,71 @@ async function writeStateAtomic(wsPath, state, deps = defaultStateFsDeps) {
585
677
  await deps.writeFile(tmpPath, content, "utf-8");
586
678
  await deps.rename(tmpPath, wsPath.stateFile);
587
679
  }
588
- function createInitialState(name, repo, options) {
589
- const { containerName, configSource } = options ?? {};
680
+ function createInitialState(instance, repoSlug, repoUrl, options) {
681
+ const { containerName, configSource, purpose } = options ?? {};
590
682
  const now = (/* @__PURE__ */ new Date()).toISOString();
683
+ const workspaceName = `${repoSlug}-${instance}`;
591
684
  return {
592
- name,
593
- repo,
685
+ instance,
686
+ repoSlug,
687
+ repoUrl,
594
688
  createdAt: now,
595
689
  lastAttached: now,
596
- purpose: null,
597
- containerName: containerName ?? `${CONTAINER_PREFIX}${name}`,
690
+ purpose: purpose ?? null,
691
+ containerName: containerName ?? `${CONTAINER_PREFIX}${workspaceName}`,
598
692
  configSource: configSource ?? "baseline"
599
693
  };
600
694
  }
695
+ function extractRepoName(url) {
696
+ const cleaned = url.replace(/\/+$/, "").replace(/\.git$/, "");
697
+ const lastSep = Math.max(cleaned.lastIndexOf("/"), cleaned.lastIndexOf(":"));
698
+ const name = lastSep >= 0 ? cleaned.slice(lastSep + 1) : cleaned;
699
+ return name.toLowerCase() || "unknown";
700
+ }
701
+ function migrateOldState(parsed, workspaceName) {
702
+ if (typeof parsed !== "object" || parsed === null) return null;
703
+ const obj = parsed;
704
+ if (typeof obj.name !== "string" || typeof obj.repo !== "string") return null;
705
+ const repoSlug = extractRepoName(obj.repo);
706
+ const lowerName = obj.name.toLowerCase();
707
+ const prefix = `${repoSlug}-`;
708
+ const instance = lowerName.startsWith(prefix) && obj.name.length > prefix.length ? obj.name.slice(prefix.length) : obj.name;
709
+ const configSource = obj.configSource === "baseline" || obj.configSource === "repo" ? obj.configSource : void 0;
710
+ const state = {
711
+ instance,
712
+ repoSlug,
713
+ repoUrl: obj.repo,
714
+ createdAt: typeof obj.createdAt === "string" ? obj.createdAt : "unknown",
715
+ lastAttached: typeof obj.lastAttached === "string" ? obj.lastAttached : "unknown",
716
+ purpose: typeof obj.purpose === "string" ? obj.purpose : null,
717
+ containerName: typeof obj.containerName === "string" ? obj.containerName : `${CONTAINER_PREFIX}${workspaceName}`
718
+ };
719
+ if (configSource) {
720
+ state.configSource = configSource;
721
+ }
722
+ return state;
723
+ }
601
724
  function isValidState(value) {
602
725
  if (typeof value !== "object" || value === null) return false;
603
726
  const obj = value;
604
- 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";
727
+ return typeof obj.instance === "string" && typeof obj.repoSlug === "string" && typeof obj.repoUrl === "string" && typeof obj.createdAt === "string" && typeof obj.lastAttached === "string" && (obj.purpose === void 0 || obj.purpose === null || typeof obj.purpose === "string") && typeof obj.containerName === "string";
605
728
  }
606
- var GIT_EXCLUDE_PATTERN = `${AGENT_ENV_DIR}/`;
729
+ var GIT_EXCLUDE_PATTERNS = [`${AGENT_ENV_DIR}/`];
607
730
  async function ensureGitExclude(workspaceRoot, deps = defaultStateFsDeps) {
608
731
  const excludePath = join2(workspaceRoot, ".git", "info", "exclude");
609
732
  try {
610
733
  const content = await deps.readFile(excludePath, "utf-8");
611
734
  const lines = content.split("\n");
612
- if (lines.some((line) => line.trim() === GIT_EXCLUDE_PATTERN)) {
735
+ const missing = GIT_EXCLUDE_PATTERNS.filter(
736
+ (pattern) => !lines.some((line) => line.trim() === pattern)
737
+ );
738
+ if (missing.length === 0) {
613
739
  return;
614
740
  }
615
741
  const prefix = content.endsWith("\n") ? "" : "\n";
616
- await deps.appendFile(excludePath, `${prefix}${GIT_EXCLUDE_PATTERN}
617
- `, "utf-8");
742
+ const toAppend = missing.map((p) => `${p}
743
+ `).join("");
744
+ await deps.appendFile(excludePath, `${prefix}${toAppend}`, "utf-8");
618
745
  } catch (err) {
619
746
  if (err.code === "ENOENT") {
620
747
  return;
@@ -623,10 +750,54 @@ async function ensureGitExclude(workspaceRoot, deps = defaultStateFsDeps) {
623
750
  }
624
751
  }
625
752
 
753
+ // src/lib/status-bar.ts
754
+ import { readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
755
+ import { join as join3 } from "path";
756
+ var STATUS_BAR_TEMPLATE_JSON = "statusBar.template.json";
757
+ var STATUS_BAR_JSON = "statusBar.json";
758
+ var PURPOSE_PLACEHOLDER = "{{PURPOSE}}";
759
+ var NO_PURPOSE_TEXT = "(no purpose set)";
760
+ var defaultDeps = { readFile: readFile3, writeFile: writeFile3 };
761
+ async function regenerateStatusBar(workspaceRoot, agentEnvDir, purpose, deps = defaultDeps) {
762
+ const vscodeTemplatePath = join3(workspaceRoot, ".vscode", STATUS_BAR_TEMPLATE_JSON);
763
+ let templateContent = null;
764
+ try {
765
+ templateContent = await deps.readFile(vscodeTemplatePath, "utf-8");
766
+ } catch (err) {
767
+ if (err.code !== "ENOENT") {
768
+ throw err;
769
+ }
770
+ }
771
+ const agentEnvTemplatePath = join3(agentEnvDir, STATUS_BAR_TEMPLATE_JSON);
772
+ if (templateContent === null) {
773
+ try {
774
+ templateContent = await deps.readFile(agentEnvTemplatePath, "utf-8");
775
+ } catch (err) {
776
+ if (err.code !== "ENOENT") {
777
+ throw err;
778
+ }
779
+ }
780
+ }
781
+ if (templateContent === null) {
782
+ throw Object.assign(
783
+ new Error(
784
+ `No status bar template found. Checked ${vscodeTemplatePath} and ${agentEnvTemplatePath}. Create a template manually or use \`agent-env init-template\` when available.`
785
+ ),
786
+ { code: "TEMPLATE_NOT_FOUND" }
787
+ );
788
+ }
789
+ const rawText = purpose ?? NO_PURPOSE_TEXT;
790
+ const replacementText = JSON.stringify(rawText).slice(1, -1);
791
+ const output = templateContent.replaceAll(PURPOSE_PLACEHOLDER, replacementText);
792
+ const outputPath = join3(agentEnvDir, STATUS_BAR_JSON);
793
+ await deps.writeFile(outputPath, output, "utf-8");
794
+ }
795
+
626
796
  // src/lib/workspace.ts
627
- import { mkdir as mkdir3, readdir as readdir2, rm, stat as stat2 } from "fs/promises";
797
+ import { createHash } from "crypto";
798
+ import { mkdir as mkdir3, readdir as readdir2, readFile as readFile4, rm, stat as stat2 } from "fs/promises";
628
799
  import { homedir } from "os";
629
- import { join as join3 } from "path";
800
+ import { join as join4 } from "path";
630
801
  var defaultFsDeps2 = { mkdir: mkdir3, readdir: readdir2, stat: stat2, homedir };
631
802
  var VALID_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
632
803
  function validateNameSegment(value, label) {
@@ -639,8 +810,38 @@ function validateNameSegment(value, label) {
639
810
  );
640
811
  }
641
812
  }
813
+ function deriveRepoSlug(url) {
814
+ const cleaned = url.replace(/\/+$/, "").replace(/\.git$/, "");
815
+ const lastSlash = cleaned.lastIndexOf("/");
816
+ const lastColon = cleaned.lastIndexOf(":");
817
+ const lastSeparator = Math.max(lastSlash, lastColon);
818
+ if (lastSeparator === -1) {
819
+ if (!cleaned) {
820
+ throw new Error(`Cannot derive repo slug from URL: ${url}`);
821
+ }
822
+ return compressSlug(cleaned.toLowerCase());
823
+ }
824
+ const repoName = cleaned.slice(lastSeparator + 1);
825
+ if (!repoName) {
826
+ throw new Error(`Cannot derive repo slug from URL: ${url}`);
827
+ }
828
+ return compressSlug(repoName.toLowerCase());
829
+ }
830
+ function compressSlug(slug, maxLength = MAX_REPO_SLUG_LENGTH) {
831
+ if (slug.length <= maxLength) {
832
+ return slug;
833
+ }
834
+ const hash = createHash("sha256").update(slug).digest("hex").slice(0, 6);
835
+ const overhead = 8;
836
+ const available = Math.max(0, maxLength - overhead);
837
+ const prefixLen = Math.ceil(available / 2);
838
+ const suffixLen = available - prefixLen;
839
+ const prefix = slug.slice(0, prefixLen);
840
+ const suffix = slug.slice(slug.length - suffixLen);
841
+ return `${prefix}_${hash}_${suffix}`;
842
+ }
642
843
  function getWorkspacesBaseDir(deps = defaultFsDeps2) {
643
- return join3(deps.homedir(), AGENT_ENV_DIR, WORKSPACES_DIR);
844
+ return join4(deps.homedir(), AGENT_ENV_DIR, WORKSPACES_DIR);
644
845
  }
645
846
  function deriveWorkspaceName(repo, instance) {
646
847
  validateNameSegment(repo, "repo");
@@ -652,15 +853,15 @@ function deriveContainerName(workspaceName) {
652
853
  }
653
854
  function getWorkspacePath(repo, instance, deps = defaultFsDeps2) {
654
855
  const name = deriveWorkspaceName(repo, instance);
655
- const root = join3(getWorkspacesBaseDir(deps), name);
656
- const agentEnvDir = join3(root, AGENT_ENV_DIR);
657
- const stateFile = join3(agentEnvDir, STATE_FILE);
856
+ const root = join4(getWorkspacesBaseDir(deps), name);
857
+ const agentEnvDir = join4(root, AGENT_ENV_DIR);
858
+ const stateFile = join4(agentEnvDir, STATE_FILE);
658
859
  return { root, name, agentEnvDir, stateFile };
659
860
  }
660
861
  function getWorkspacePathByName(workspaceName, deps = defaultFsDeps2) {
661
- const root = join3(getWorkspacesBaseDir(deps), workspaceName);
662
- const agentEnvDir = join3(root, AGENT_ENV_DIR);
663
- const stateFile = join3(agentEnvDir, STATE_FILE);
862
+ const root = join4(getWorkspacesBaseDir(deps), workspaceName);
863
+ const agentEnvDir = join4(root, AGENT_ENV_DIR);
864
+ const stateFile = join4(agentEnvDir, STATE_FILE);
664
865
  return { root, name: workspaceName, agentEnvDir, stateFile };
665
866
  }
666
867
  async function workspaceExists(repo, instance, deps = defaultFsDeps2) {
@@ -687,30 +888,312 @@ async function scanWorkspaces(deps = defaultFsDeps2) {
687
888
  throw err;
688
889
  }
689
890
  }
891
+ function looksLikeUrl(value) {
892
+ return value.includes("/") || value.includes(":");
893
+ }
894
+ async function resolveRepo(opts, executor) {
895
+ const repoFlag = opts.repo?.trim();
896
+ if (repoFlag !== void 0 && repoFlag !== "") {
897
+ if (looksLikeUrl(repoFlag)) {
898
+ try {
899
+ const slug2 = deriveRepoSlug(repoFlag);
900
+ return { resolved: true, repoSlug: slug2 };
901
+ } catch {
902
+ return {
903
+ resolved: false,
904
+ error: {
905
+ code: "INVALID_REPO",
906
+ message: `Cannot derive repo slug from: ${repoFlag}`,
907
+ suggestion: "Provide a valid git URL or repo slug."
908
+ }
909
+ };
910
+ }
911
+ }
912
+ const slug = repoFlag.toLowerCase();
913
+ if (!VALID_NAME_PATTERN.test(slug)) {
914
+ return {
915
+ resolved: false,
916
+ error: {
917
+ code: "INVALID_REPO",
918
+ message: `Invalid repo slug: "${repoFlag}". Only alphanumeric, dash, dot, and underscore allowed (must start with alphanumeric).`,
919
+ suggestion: "Provide a valid repo slug or git URL."
920
+ }
921
+ };
922
+ }
923
+ return { resolved: true, repoSlug: slug };
924
+ }
925
+ if (opts.cwd) {
926
+ const result = await executor("git", ["remote", "get-url", "origin"], {
927
+ cwd: opts.cwd
928
+ });
929
+ if (result.ok && result.stdout.trim()) {
930
+ try {
931
+ const slug = deriveRepoSlug(result.stdout.trim());
932
+ return { resolved: true, repoSlug: slug };
933
+ } catch {
934
+ }
935
+ }
936
+ }
937
+ return { resolved: false };
938
+ }
939
+ var defaultResolveInstanceDeps = {
940
+ fsDeps: defaultFsDeps2,
941
+ readFile: readFile4
942
+ };
943
+ async function resolveInstance(instanceName, repoSlug, deps = defaultResolveInstanceDeps) {
944
+ const workspaces = await scanWorkspaces(deps.fsDeps);
945
+ if (workspaces.includes(instanceName)) {
946
+ return { found: true, workspaceName: instanceName };
947
+ }
948
+ if (repoSlug) {
949
+ const expectedName = `${repoSlug}-${instanceName}`;
950
+ if (workspaces.includes(expectedName)) {
951
+ return { found: true, workspaceName: expectedName };
952
+ }
953
+ }
954
+ const matches = [];
955
+ for (const wsName of workspaces) {
956
+ const wsPath = getWorkspacePathByName(wsName, deps.fsDeps);
957
+ try {
958
+ const content = await deps.readFile(wsPath.stateFile, "utf-8");
959
+ const state = JSON.parse(content);
960
+ if (typeof state === "object" && state !== null && state.instance === instanceName) {
961
+ matches.push(wsName);
962
+ if (matches.length > 1) break;
963
+ }
964
+ } catch {
965
+ }
966
+ }
967
+ if (matches.length === 1) {
968
+ return { found: true, workspaceName: matches[0] };
969
+ }
970
+ if (matches.length > 1) {
971
+ const repoSlugs = matches.map((ws) => {
972
+ const idx = ws.lastIndexOf(`-${instanceName}`);
973
+ return idx > 0 ? ws.slice(0, idx) : ws;
974
+ });
975
+ return {
976
+ found: false,
977
+ error: {
978
+ code: "AMBIGUOUS_INSTANCE",
979
+ message: `Multiple instances named '${instanceName}' exist across repos: ${repoSlugs.join(", ")}`,
980
+ suggestion: "Use --repo <slug> to specify which repo."
981
+ }
982
+ };
983
+ }
984
+ return {
985
+ found: false,
986
+ error: {
987
+ code: "WORKSPACE_NOT_FOUND",
988
+ message: `Instance '${instanceName}' not found`,
989
+ suggestion: "Use `agent-env list` to see available instances."
990
+ }
991
+ };
992
+ }
690
993
  var defaultDeleteFsDeps = { rm };
691
994
  async function deleteWorkspace(wsPath, deps = defaultDeleteFsDeps) {
692
995
  await deps.rm(wsPath.root, { recursive: true, force: true });
693
996
  }
694
997
 
695
- // src/lib/create-instance.ts
696
- var GIT_CLONE_TIMEOUT = 12e4;
697
- function extractRepoName(url) {
698
- const cleaned = url.replace(/\/+$/, "").replace(/\.git$/, "");
699
- const lastSlash = cleaned.lastIndexOf("/");
700
- const lastColon = cleaned.lastIndexOf(":");
701
- const lastSeparator = Math.max(lastSlash, lastColon);
702
- if (lastSeparator === -1) {
703
- if (!cleaned) {
704
- throw new Error(`Cannot extract repository name from URL: ${url}`);
998
+ // src/lib/purpose-instance.ts
999
+ var MAX_PURPOSE_LENGTH = 200;
1000
+ function createPurposeDefaultDeps() {
1001
+ return {
1002
+ workspaceFsDeps: { mkdir: mkdir4, readdir: readdir3, stat: stat3, homedir: homedir2 },
1003
+ stateFsDeps: { readFile: readFile5, writeFile: writeFile4, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
1004
+ statusBarDeps: { readFile: readFile5, writeFile: writeFile4 }
1005
+ };
1006
+ }
1007
+ function validatePurposeLength(value) {
1008
+ if (value.length > MAX_PURPOSE_LENGTH) {
1009
+ return {
1010
+ ok: false,
1011
+ error: {
1012
+ code: "PURPOSE_TOO_LONG",
1013
+ message: `Purpose must be ${MAX_PURPOSE_LENGTH} characters or fewer (got ${value.length})`
1014
+ }
1015
+ };
1016
+ }
1017
+ return null;
1018
+ }
1019
+ async function getPurpose(instanceName, deps, repoSlug) {
1020
+ const lookup = await resolveInstance(instanceName, repoSlug, {
1021
+ fsDeps: deps.workspaceFsDeps,
1022
+ readFile: deps.stateFsDeps.readFile
1023
+ });
1024
+ if (!lookup.found) {
1025
+ return { ok: false, error: lookup.error };
1026
+ }
1027
+ const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1028
+ const state = await readState(wsPath, deps.stateFsDeps);
1029
+ return { ok: true, purpose: state.purpose };
1030
+ }
1031
+ async function setPurpose(instanceName, value, deps, repoSlug) {
1032
+ const lengthError = validatePurposeLength(value);
1033
+ if (lengthError) return lengthError;
1034
+ const lookup = await resolveInstance(instanceName, repoSlug, {
1035
+ fsDeps: deps.workspaceFsDeps,
1036
+ readFile: deps.stateFsDeps.readFile
1037
+ });
1038
+ if (!lookup.found) {
1039
+ return { ok: false, error: lookup.error };
1040
+ }
1041
+ const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1042
+ const state = await readState(wsPath, deps.stateFsDeps);
1043
+ const cleared = value === "";
1044
+ const newPurpose = cleared ? null : value;
1045
+ const updatedState = {
1046
+ ...state,
1047
+ purpose: newPurpose
1048
+ };
1049
+ await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
1050
+ try {
1051
+ await regenerateStatusBar(wsPath.root, wsPath.agentEnvDir, newPurpose, deps.statusBarDeps);
1052
+ } catch (err) {
1053
+ if (err.code === "TEMPLATE_NOT_FOUND") {
1054
+ return {
1055
+ ok: false,
1056
+ error: {
1057
+ code: "TEMPLATE_NOT_FOUND",
1058
+ message: err.message,
1059
+ suggestion: "Create a status bar template at .vscode/statusBar.template.json or .agent-env/statusBar.template.json."
1060
+ }
1061
+ };
705
1062
  }
706
- return cleaned;
1063
+ throw err;
707
1064
  }
708
- const repoName = cleaned.slice(lastSeparator + 1);
709
- if (!repoName) {
710
- throw new Error(`Cannot extract repository name from URL: ${url}`);
1065
+ return { ok: true, cleared };
1066
+ }
1067
+ function createContainerPurposeDefaultDeps() {
1068
+ return {
1069
+ stateFsDeps: { readFile: readFile5, writeFile: writeFile4, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
1070
+ containerEnvDeps: { getEnv: (key) => process.env[key] },
1071
+ statusBarDeps: { readFile: readFile5, writeFile: writeFile4 },
1072
+ statePath: CONTAINER_STATE_PATH,
1073
+ agentEnvDir: CONTAINER_AGENT_ENV_DIR,
1074
+ workspaceRoot: process.cwd()
1075
+ };
1076
+ }
1077
+ async function readContainerState(deps) {
1078
+ try {
1079
+ const content = await deps.stateFsDeps.readFile(deps.statePath, "utf-8");
1080
+ const parsed = JSON.parse(content);
1081
+ if (!isValidState(parsed)) {
1082
+ return {
1083
+ ok: false,
1084
+ error: {
1085
+ code: "STATE_CORRUPT",
1086
+ message: `State file at ${deps.statePath} contains invalid or incomplete state data`
1087
+ }
1088
+ };
1089
+ }
1090
+ return { ok: true, state: parsed };
1091
+ } catch (err) {
1092
+ if (err.code === "ENOENT") {
1093
+ return {
1094
+ ok: false,
1095
+ error: {
1096
+ code: "STATE_NOT_FOUND",
1097
+ message: `State file not found at ${deps.statePath}`,
1098
+ suggestion: "This container may not have been created by agent-env."
1099
+ }
1100
+ };
1101
+ }
1102
+ if (err instanceof SyntaxError) {
1103
+ return {
1104
+ ok: false,
1105
+ error: {
1106
+ code: "STATE_CORRUPT",
1107
+ message: `State file at ${deps.statePath} contains invalid JSON`
1108
+ }
1109
+ };
1110
+ }
1111
+ throw err;
1112
+ }
1113
+ }
1114
+ async function getContainerPurpose(deps) {
1115
+ const read = await readContainerState(deps);
1116
+ if (!read.ok) return read;
1117
+ return { ok: true, purpose: read.state.purpose ?? null };
1118
+ }
1119
+ async function setContainerPurpose(value, deps) {
1120
+ const lengthError = validatePurposeLength(value);
1121
+ if (lengthError) return lengthError;
1122
+ const read = await readContainerState(deps);
1123
+ if (!read.ok) return read;
1124
+ const cleared = value === "";
1125
+ const newPurpose = cleared ? null : value;
1126
+ const updatedState = {
1127
+ ...read.state,
1128
+ purpose: newPurpose
1129
+ };
1130
+ const wsPath = {
1131
+ root: deps.agentEnvDir,
1132
+ name: `${read.state.repoSlug}-${read.state.instance}`,
1133
+ agentEnvDir: deps.agentEnvDir,
1134
+ stateFile: deps.statePath
1135
+ };
1136
+ await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
1137
+ try {
1138
+ await regenerateStatusBar(deps.workspaceRoot, deps.agentEnvDir, newPurpose, deps.statusBarDeps);
1139
+ } catch (err) {
1140
+ if (err.code === "TEMPLATE_NOT_FOUND") {
1141
+ return {
1142
+ ok: false,
1143
+ error: {
1144
+ code: "TEMPLATE_NOT_FOUND",
1145
+ message: err.message,
1146
+ suggestion: "Create a status bar template at .vscode/statusBar.template.json or .agent-env/statusBar.template.json."
1147
+ }
1148
+ };
1149
+ }
1150
+ throw err;
711
1151
  }
712
- return repoName;
1152
+ return { ok: true, cleared };
713
1153
  }
1154
+
1155
+ // src/lib/create-instance.ts
1156
+ var VALID_INSTANCE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
1157
+ function validateCreateInputs(instanceName, purposeText) {
1158
+ if (!instanceName) {
1159
+ return {
1160
+ ok: false,
1161
+ error: {
1162
+ code: "INVALID_INSTANCE_NAME",
1163
+ message: "Instance name must not be empty."
1164
+ }
1165
+ };
1166
+ }
1167
+ if (!VALID_INSTANCE_NAME_PATTERN.test(instanceName)) {
1168
+ return {
1169
+ ok: false,
1170
+ error: {
1171
+ code: "INVALID_INSTANCE_NAME",
1172
+ message: `Invalid instance name: "${instanceName}". Only alphanumeric, dash, dot, and underscore allowed (must start with alphanumeric).`
1173
+ }
1174
+ };
1175
+ }
1176
+ if (instanceName.length > MAX_INSTANCE_NAME_LENGTH) {
1177
+ return {
1178
+ ok: false,
1179
+ error: {
1180
+ code: "INSTANCE_NAME_TOO_LONG",
1181
+ message: `Instance name must be ${MAX_INSTANCE_NAME_LENGTH} characters or fewer (got ${instanceName.length})`
1182
+ }
1183
+ };
1184
+ }
1185
+ if (purposeText.length > MAX_PURPOSE_LENGTH) {
1186
+ return {
1187
+ ok: false,
1188
+ error: {
1189
+ code: "PURPOSE_TOO_LONG",
1190
+ message: `Purpose must be ${MAX_PURPOSE_LENGTH} characters or fewer (got ${purposeText.length})`
1191
+ }
1192
+ };
1193
+ }
1194
+ return null;
1195
+ }
1196
+ var GIT_CLONE_TIMEOUT = 12e4;
714
1197
  async function resolveRepoUrl(repoArg, executor) {
715
1198
  if (repoArg !== ".") {
716
1199
  return { ok: true, url: repoArg };
@@ -761,9 +1244,9 @@ function createDefaultDeps() {
761
1244
  return {
762
1245
  executor,
763
1246
  container: createContainerLifecycle(executor),
764
- workspaceFsDeps: { mkdir: mkdir4, readdir: readdir3, stat: stat3, homedir: homedir2 },
765
- stateFsDeps: { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
766
- devcontainerFsDeps: { cp: cp2, mkdir: mkdir4, readFile: readFile3, stat: stat3, writeFile: writeFile3 },
1247
+ workspaceFsDeps: { mkdir: mkdir5, readdir: readdir4, stat: stat4, homedir: homedir3 },
1248
+ stateFsDeps: { readFile: readFile6, writeFile: writeFile5, rename: rename3, mkdir: mkdir5, appendFile: appendFile3 },
1249
+ devcontainerFsDeps: { cp: cp2, mkdir: mkdir5, readFile: readFile6, stat: stat4, writeFile: writeFile5 },
767
1250
  rm: rm2,
768
1251
  logger: {
769
1252
  warn: (msg) => console.warn(msg),
@@ -771,33 +1254,70 @@ function createDefaultDeps() {
771
1254
  }
772
1255
  };
773
1256
  }
774
- async function createInstance(instanceName, repoUrl, deps) {
775
- let repoName;
1257
+ async function resolveConfigChoice(hasConfig, baselineChoice, askUser) {
1258
+ if (!hasConfig) {
1259
+ return "baseline";
1260
+ }
1261
+ if (baselineChoice === "force-baseline") {
1262
+ return "baseline";
1263
+ }
1264
+ if (baselineChoice === "force-repo-config") {
1265
+ return "repo";
1266
+ }
1267
+ if (askUser) {
1268
+ return askUser();
1269
+ }
1270
+ return "repo";
1271
+ }
1272
+ function deriveBaselineChoice(baseline) {
1273
+ if (baseline === true) return "force-baseline";
1274
+ if (baseline === false) return "force-repo-config";
1275
+ return "ask-user";
1276
+ }
1277
+ async function setupDevcontainerConfig(wsPath, containerName, repoName, purposeText, deps, baselineChoice = "ask-user", askUser) {
1278
+ const hasConfig = await hasDevcontainerConfig(wsPath.root, deps.devcontainerFsDeps);
1279
+ const choice = await resolveConfigChoice(hasConfig, baselineChoice, askUser);
1280
+ if (choice === "repo") {
1281
+ return { ok: true, configSource: "repo" };
1282
+ }
776
1283
  try {
777
- repoName = extractRepoName(repoUrl);
778
- } catch {
1284
+ await copyBaselineConfig(wsPath.root, deps.devcontainerFsDeps);
1285
+ await copyStatusBarTemplate(wsPath.root, deps.devcontainerFsDeps);
1286
+ } catch (err) {
1287
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
779
1288
  return {
780
1289
  ok: false,
781
1290
  error: {
782
- code: "GIT_ERROR",
783
- message: `Invalid repository URL: ${repoUrl}`,
784
- suggestion: "Provide a valid HTTPS or SSH git URL."
1291
+ code: "CONTAINER_ERROR",
1292
+ message: `Failed to copy baseline devcontainer config: ${err instanceof Error ? err.message : String(err)}`
785
1293
  }
786
1294
  };
787
1295
  }
788
- const wsPath = getWorkspacePath(repoName, instanceName, deps.workspaceFsDeps);
789
- const containerName = deriveContainerName(wsPath.name);
790
- const exists = await workspaceExists(repoName, instanceName, deps.workspaceFsDeps);
791
- if (exists) {
1296
+ try {
1297
+ await applyBaselinePatches(
1298
+ wsPath.root,
1299
+ containerName,
1300
+ {
1301
+ AGENT_ENV_INSTANCE: wsPath.name,
1302
+ AGENT_ENV_REPO: repoName,
1303
+ AGENT_ENV_PURPOSE: purposeText
1304
+ },
1305
+ deps.devcontainerFsDeps,
1306
+ AGENT_ENV_DIR
1307
+ );
1308
+ } catch (err) {
1309
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
792
1310
  return {
793
1311
  ok: false,
794
1312
  error: {
795
- code: "INSTANCE_EXISTS",
796
- message: `Instance '${instanceName}' already exists for repo '${repoName}'`,
797
- suggestion: `Choose a different instance name or remove the existing one first.`
1313
+ code: "CONTAINER_ERROR",
1314
+ message: `Failed to patch baseline devcontainer.json: ${err instanceof Error ? err.message : String(err)}`
798
1315
  }
799
1316
  };
800
1317
  }
1318
+ return { ok: true, configSource: "baseline" };
1319
+ }
1320
+ async function cloneAndPrepareWorkspace(repoUrl, wsPath, deps) {
801
1321
  try {
802
1322
  await deps.workspaceFsDeps.mkdir(dirname2(wsPath.root), { recursive: true });
803
1323
  } catch (err) {
@@ -837,36 +1357,68 @@ async function createInstance(instanceName, repoUrl, deps) {
837
1357
  }
838
1358
  };
839
1359
  }
840
- const hasConfig = await hasDevcontainerConfig(wsPath.root, deps.devcontainerFsDeps);
841
- let configSource = "baseline";
842
- if (!hasConfig) {
843
- try {
844
- await copyBaselineConfig(wsPath.root, deps.devcontainerFsDeps);
845
- } catch (err) {
846
- await safeRollback(wsPath.root, deps.rm, deps.logger);
847
- return {
848
- ok: false,
849
- error: {
850
- code: "CONTAINER_ERROR",
851
- message: `Failed to copy baseline devcontainer config: ${err instanceof Error ? err.message : String(err)}`
852
- }
853
- };
854
- }
855
- try {
856
- await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps, AGENT_ENV_DIR);
857
- } catch (err) {
858
- await safeRollback(wsPath.root, deps.rm, deps.logger);
859
- return {
860
- ok: false,
861
- error: {
862
- code: "CONTAINER_ERROR",
863
- message: `Failed to patch devcontainer.json with container name: ${err instanceof Error ? err.message : String(err)}`
864
- }
865
- };
1360
+ return { ok: true };
1361
+ }
1362
+ async function discoverContainerName(containerName, containerId, deps) {
1363
+ if (containerId) {
1364
+ const discovered = await deps.container.getContainerNameById(containerId);
1365
+ if (discovered) {
1366
+ return discovered;
866
1367
  }
867
1368
  } else {
868
- configSource = "repo";
1369
+ deps.logger?.warn(
1370
+ `Warning: devcontainer started successfully but no containerId returned. Using derived name '${containerName}'.`
1371
+ );
1372
+ }
1373
+ return containerName;
1374
+ }
1375
+ async function createInstance(instanceName, repoUrl, deps, options) {
1376
+ const purposeText = options?.purpose ?? "";
1377
+ const purposeState = options?.purpose ?? null;
1378
+ const validationError = validateCreateInputs(instanceName, purposeText);
1379
+ if (validationError) return validationError;
1380
+ let repoName;
1381
+ try {
1382
+ repoName = deriveRepoSlug(repoUrl);
1383
+ } catch {
1384
+ return {
1385
+ ok: false,
1386
+ error: {
1387
+ code: "GIT_ERROR",
1388
+ message: `Invalid repository URL: ${repoUrl}`,
1389
+ suggestion: "Provide a valid HTTPS or SSH git URL."
1390
+ }
1391
+ };
1392
+ }
1393
+ const wsPath = getWorkspacePath(repoName, instanceName, deps.workspaceFsDeps);
1394
+ const containerName = deriveContainerName(wsPath.name);
1395
+ const exists = await workspaceExists(repoName, instanceName, deps.workspaceFsDeps);
1396
+ if (exists) {
1397
+ return {
1398
+ ok: false,
1399
+ error: {
1400
+ code: "INSTANCE_EXISTS",
1401
+ message: `Instance '${instanceName}' already exists for repo '${repoName}'`,
1402
+ suggestion: `Choose a different instance name or remove the existing one first.`
1403
+ }
1404
+ };
1405
+ }
1406
+ const prepResult = await cloneAndPrepareWorkspace(repoUrl, wsPath, deps);
1407
+ if (!prepResult.ok) return prepResult;
1408
+ const baselineChoice = deriveBaselineChoice(options?.baseline);
1409
+ const configResult = await setupDevcontainerConfig(
1410
+ wsPath,
1411
+ containerName,
1412
+ repoName,
1413
+ purposeText,
1414
+ deps,
1415
+ baselineChoice,
1416
+ options?.askUser
1417
+ );
1418
+ if (!configResult.ok) {
1419
+ return configResult;
869
1420
  }
1421
+ const { configSource } = configResult;
870
1422
  const existingContainer = await deps.container.findContainerByWorkspaceLabel(wsPath.root);
871
1423
  if (existingContainer) {
872
1424
  await safeRollback(wsPath.root, deps.rm, deps.logger);
@@ -879,28 +1431,26 @@ async function createInstance(instanceName, repoUrl, deps) {
879
1431
  }
880
1432
  };
881
1433
  }
882
- const baselineConfigPath = configSource === "baseline" ? join4(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1434
+ const baselineConfigPath = configSource === "baseline" ? join5(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
883
1435
  const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
884
- remoteEnv: { AGENT_INSTANCE: wsPath.name },
1436
+ remoteEnv: {
1437
+ AGENT_INSTANCE: wsPath.name,
1438
+ AGENT_ENV_PURPOSE: purposeText
1439
+ },
885
1440
  configPath: baselineConfigPath
886
1441
  });
887
1442
  if (!containerResult.ok) {
888
1443
  return rollbackContainerFailure(containerName, wsPath, containerResult, deps);
889
1444
  }
890
- let actualContainerName = containerName;
891
- if (containerResult.containerId) {
892
- const discovered = await deps.container.getContainerNameById(containerResult.containerId);
893
- if (discovered) {
894
- actualContainerName = discovered;
895
- }
896
- } else {
897
- deps.logger?.warn(
898
- `Warning: devcontainer started successfully but no containerId returned. Using derived name '${containerName}'.`
899
- );
900
- }
901
- const state = createInitialState(wsPath.name, repoUrl, {
1445
+ const actualContainerName = await discoverContainerName(
1446
+ containerName,
1447
+ containerResult.containerId ?? void 0,
1448
+ deps
1449
+ );
1450
+ const state = createInitialState(instanceName, repoName, repoUrl, {
902
1451
  containerName: actualContainerName,
903
- configSource
1452
+ configSource,
1453
+ purpose: purposeState
904
1454
  });
905
1455
  await writeStateAtomic(wsPath, state, deps.stateFsDeps);
906
1456
  await ensureGitExclude(wsPath.root, deps.stateFsDeps);
@@ -976,45 +1526,17 @@ function createAttachDefaultDeps() {
976
1526
  return {
977
1527
  executor,
978
1528
  container: createContainerLifecycle(executor),
979
- workspaceFsDeps: { mkdir: mkdir5, readdir: readdir4, stat: stat4, homedir: homedir3 },
980
- stateFsDeps: { readFile: readFile4, writeFile: writeFile4, rename: rename3, mkdir: mkdir5, appendFile: appendFile3 }
1529
+ workspaceFsDeps: { mkdir: mkdir6, readdir: readdir5, stat: stat5, homedir: homedir4 },
1530
+ stateFsDeps: { readFile: readFile7, writeFile: writeFile6, rename: rename4, mkdir: mkdir6, appendFile: appendFile4 }
981
1531
  };
982
1532
  }
983
- async function findWorkspaceByName(instanceName, deps) {
984
- const workspaces = await scanWorkspaces(deps);
985
- if (workspaces.includes(instanceName)) {
986
- return { found: true, workspaceName: instanceName };
987
- }
988
- const suffixMatches = workspaces.filter((ws) => ws.endsWith(`-${instanceName}`));
989
- if (suffixMatches.length === 1) {
990
- return { found: true, workspaceName: suffixMatches[0] };
991
- }
992
- if (suffixMatches.length > 1) {
993
- return { found: false, reason: "ambiguous", matches: suffixMatches };
994
- }
995
- return { found: false, reason: "not-found" };
996
- }
997
- async function attachInstance(instanceName, deps, onContainerStarting, onAttaching) {
998
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1533
+ async function attachInstance(instanceName, deps, onContainerStarting, onAttaching, repoSlug) {
1534
+ const lookup = await resolveInstance(instanceName, repoSlug, {
1535
+ fsDeps: deps.workspaceFsDeps,
1536
+ readFile: deps.stateFsDeps.readFile
1537
+ });
999
1538
  if (!lookup.found) {
1000
- if (lookup.reason === "ambiguous") {
1001
- return {
1002
- ok: false,
1003
- error: {
1004
- code: "AMBIGUOUS_MATCH",
1005
- message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
1006
- suggestion: "Use the full workspace name to specify which instance."
1007
- }
1008
- };
1009
- }
1010
- return {
1011
- ok: false,
1012
- error: {
1013
- code: "WORKSPACE_NOT_FOUND",
1014
- message: `Instance '${instanceName}' not found`,
1015
- suggestion: "Use `agent-env list` to see available instances."
1016
- }
1017
- };
1539
+ return { ok: false, error: lookup.error };
1018
1540
  }
1019
1541
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1020
1542
  const state = await readState(wsPath, deps.stateFsDeps);
@@ -1043,7 +1565,7 @@ async function attachInstance(instanceName, deps, onContainerStarting, onAttachi
1043
1565
  if (statusResult.status === "stopped" || statusResult.status === "not-found") {
1044
1566
  onContainerStarting?.();
1045
1567
  const configSource = state.configSource ?? "baseline";
1046
- const baselineConfigPath = configSource === "baseline" ? join5(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1568
+ const baselineConfigPath = configSource === "baseline" ? join6(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1047
1569
  const startResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
1048
1570
  remoteEnv: { AGENT_INSTANCE: wsPath.name },
1049
1571
  configPath: baselineConfigPath
@@ -1064,17 +1586,36 @@ async function attachInstance(instanceName, deps, onContainerStarting, onAttachi
1064
1586
  if (!attachResult.ok) {
1065
1587
  return attachResult;
1066
1588
  }
1067
- const updatedState = {
1068
- ...state,
1069
- lastAttached: (/* @__PURE__ */ new Date()).toISOString()
1070
- };
1071
- await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
1072
- return { ok: true };
1589
+ const updatedState = {
1590
+ ...state,
1591
+ lastAttached: (/* @__PURE__ */ new Date()).toISOString()
1592
+ };
1593
+ await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
1594
+ return { ok: true };
1595
+ }
1596
+
1597
+ // src/lib/command-helpers.ts
1598
+ async function resolveRepoOrExit(opts) {
1599
+ const executor = createExecutor();
1600
+ const repoResult = await resolveRepo(opts, executor);
1601
+ if (repoResult.resolved) {
1602
+ return repoResult.repoSlug;
1603
+ }
1604
+ if ("error" in repoResult && repoResult.error) {
1605
+ console.error(
1606
+ formatError(
1607
+ createError(repoResult.error.code, repoResult.error.message, repoResult.error.suggestion)
1608
+ )
1609
+ );
1610
+ process.exit(1);
1611
+ }
1612
+ return void 0;
1073
1613
  }
1074
1614
 
1075
1615
  // src/commands/attach.ts
1076
- var attachCommand = new Command("attach").description("Attach to an instance's tmux session").argument("<name>", "Instance name to attach to").action(async (name) => {
1616
+ var attachCommand = new Command("attach").description("Attach to an instance's tmux session").argument("<name>", "Instance name to attach to").option("--repo <slug>", "Repo slug or URL to scope instance lookup").action(async (name, options) => {
1077
1617
  const deps = createAttachDefaultDeps();
1618
+ const repoSlug = await resolveRepoOrExit({ repo: options.repo, cwd: process.cwd() });
1078
1619
  const result = await attachInstance(
1079
1620
  name,
1080
1621
  deps,
@@ -1084,7 +1625,8 @@ var attachCommand = new Command("attach").description("Attach to an instance's t
1084
1625
  () => {
1085
1626
  console.log();
1086
1627
  console.log("Attaching to tmux session...");
1087
- }
1628
+ },
1629
+ repoSlug
1088
1630
  );
1089
1631
  if (!result.ok) {
1090
1632
  const { code, message, suggestion } = result.error;
@@ -1272,21 +1814,144 @@ ${getInstallInstructions()}`).argument("<shell>", "Shell type (bash or zsh)").ac
1272
1814
 
1273
1815
  // src/commands/create.ts
1274
1816
  import { Command as Command3 } from "commander";
1275
- 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) => {
1817
+ import { createInterface } from "readline";
1818
+
1819
+ // src/lib/list-repos.ts
1820
+ async function listRepos(deps) {
1821
+ try {
1822
+ const wsFsDeps = deps?.workspaceFsDeps;
1823
+ const stateFsDeps = deps?.stateFsDeps;
1824
+ const workspaceNames = (await scanWorkspaces(wsFsDeps)).sort();
1825
+ if (workspaceNames.length === 0) {
1826
+ return { ok: true, repos: [] };
1827
+ }
1828
+ const repoMap = /* @__PURE__ */ new Map();
1829
+ for (const wsName of workspaceNames) {
1830
+ const wsPath = getWorkspacePathByName(wsName, wsFsDeps);
1831
+ const state = await readState(wsPath, stateFsDeps);
1832
+ if (state.repoSlug === "unknown") {
1833
+ continue;
1834
+ }
1835
+ const existing = repoMap.get(state.repoSlug);
1836
+ if (existing) {
1837
+ existing.count += 1;
1838
+ } else {
1839
+ repoMap.set(state.repoSlug, { url: state.repoUrl, count: 1 });
1840
+ }
1841
+ }
1842
+ const repos = Array.from(repoMap.entries()).map(([slug, { url, count }]) => ({
1843
+ slug,
1844
+ url,
1845
+ instanceCount: count
1846
+ })).sort((a, b) => a.slug.localeCompare(b.slug));
1847
+ return { ok: true, repos };
1848
+ } catch (err) {
1849
+ const message = err instanceof Error ? err.message : String(err);
1850
+ return {
1851
+ ok: false,
1852
+ repos: null,
1853
+ error: { code: "LIST_REPOS_ERROR", message: `Failed to list repos: ${message}` }
1854
+ };
1855
+ }
1856
+ }
1857
+
1858
+ // src/lib/resolve-repo-arg.ts
1859
+ function isRepoUrl(value) {
1860
+ return value.includes("://") || value.startsWith("git@");
1861
+ }
1862
+ async function resolveRepoArg(repoArg, deps) {
1863
+ if (repoArg === ".") {
1864
+ return { ok: true, url: ".", resolvedFromSlug: false };
1865
+ }
1866
+ if (isRepoUrl(repoArg)) {
1867
+ return { ok: true, url: repoArg, resolvedFromSlug: false };
1868
+ }
1869
+ const listFn = deps?.listRepos ?? listRepos;
1870
+ const result = await listFn();
1871
+ if (!result.ok) {
1872
+ return {
1873
+ ok: false,
1874
+ error: {
1875
+ code: "REPO_LOOKUP_ERROR",
1876
+ message: `Failed to look up repo registry: ${result.error.message}`,
1877
+ suggestion: "Check filesystem permissions for the ~/.agent-env directory."
1878
+ }
1879
+ };
1880
+ }
1881
+ const slugArg = repoArg.toLowerCase();
1882
+ const match = result.repos.find((r) => r.slug === slugArg);
1883
+ if (!match) {
1884
+ return {
1885
+ ok: false,
1886
+ error: {
1887
+ code: "REPO_NOT_FOUND",
1888
+ message: `Repository '${repoArg}' not found.`,
1889
+ suggestion: "Use a full URL or run `agent-env repos` to see tracked repos."
1890
+ }
1891
+ };
1892
+ }
1893
+ return { ok: true, url: match.url, resolvedFromSlug: true };
1894
+ }
1895
+
1896
+ // src/commands/create.ts
1897
+ function createBaselinePrompt() {
1898
+ return async () => {
1899
+ if (!process.stdin.isTTY) {
1900
+ return "repo";
1901
+ }
1902
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1903
+ return new Promise((resolve2) => {
1904
+ console.log();
1905
+ console.log("This repo has a .devcontainer/ config.");
1906
+ console.log(" [1] Use repo config (default)");
1907
+ console.log(" [2] Use agent-env baseline");
1908
+ rl.question("Choose [1/2]: ", (answer) => {
1909
+ rl.close();
1910
+ resolve2(answer.trim() === "2" ? "baseline" : "repo");
1911
+ });
1912
+ });
1913
+ };
1914
+ }
1915
+ 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", "Force agent-env baseline config (ignore repo .devcontainer/)").option("--no-baseline", "Force repo config (skip baseline prompt)").action(async (name, options) => {
1276
1916
  if (!options.repo) {
1277
1917
  console.error(
1278
1918
  formatError(
1279
1919
  createError(
1280
1920
  "MISSING_OPTION",
1281
1921
  "The --repo flag is required.",
1282
- "Usage: agent-env create <name> --repo <url>"
1922
+ "Usage: agent-env create <name> --repo <url|slug>"
1923
+ )
1924
+ )
1925
+ );
1926
+ process.exit(1);
1927
+ }
1928
+ const argv = process.argv;
1929
+ const hasBaselineFlag = argv.includes("--baseline");
1930
+ const hasNoBaselineFlag = argv.includes("--no-baseline");
1931
+ if (hasBaselineFlag && hasNoBaselineFlag) {
1932
+ console.error(
1933
+ formatError(
1934
+ createError(
1935
+ "INVALID_OPTIONS",
1936
+ "Cannot specify both --baseline and --no-baseline",
1937
+ "Use --baseline to force agent-env baseline, or --no-baseline to use repo config."
1283
1938
  )
1284
1939
  )
1285
1940
  );
1286
1941
  process.exit(1);
1287
1942
  }
1288
1943
  const deps = createDefaultDeps();
1289
- const resolved = await resolveRepoUrl(options.repo, deps.executor);
1944
+ const slugResult = await resolveRepoArg(options.repo);
1945
+ if (!slugResult.ok) {
1946
+ const { code, message, suggestion } = slugResult.error;
1947
+ console.error(formatError(createError(code, message, suggestion)));
1948
+ process.exit(1);
1949
+ }
1950
+ const repoInput = slugResult.url;
1951
+ if (slugResult.resolvedFromSlug) {
1952
+ console.log(`Resolved repo '${options.repo}' \u2192 ${repoInput}`);
1953
+ }
1954
+ const resolved = await resolveRepoUrl(repoInput, deps.executor);
1290
1955
  if (!resolved.ok) {
1291
1956
  const { code, message, suggestion } = resolved.error;
1292
1957
  console.error(formatError(createError(code, message, suggestion)));
@@ -1294,7 +1959,12 @@ var createCommand = new Command3("create").description("Create a new isolated de
1294
1959
  }
1295
1960
  const repoUrl = resolved.url;
1296
1961
  console.log(`Creating instance '${name}' from ${repoUrl}...`);
1297
- const result = await createInstance(name, repoUrl, deps);
1962
+ const baselineOption = hasBaselineFlag ? true : hasNoBaselineFlag ? false : void 0;
1963
+ const result = await createInstance(name, repoUrl, deps, {
1964
+ purpose: options.purpose,
1965
+ baseline: baselineOption,
1966
+ askUser: createBaselinePrompt()
1967
+ });
1298
1968
  if (!result.ok) {
1299
1969
  const { code, message, suggestion } = result.error;
1300
1970
  console.error(formatError(createError(code, message, suggestion)));
@@ -1420,6 +2090,7 @@ function InstanceList({
1420
2090
  return { ...instance, indicators, indicatorText };
1421
2091
  });
1422
2092
  const nameWidth = Math.max(4, ...augmentedInstances.map((i) => i.name.length)) + 2;
2093
+ const repoWidth = Math.max(4, ...augmentedInstances.map((i) => i.repoSlug.length)) + 2;
1423
2094
  const statusWidth = Math.max(6, ...augmentedInstances.map((i) => statusLabel(i.status, dockerAvailable).length)) + 2;
1424
2095
  const gitWidth = Math.max(3, ...augmentedInstances.map((i) => i.indicatorText.length)) + 2;
1425
2096
  const lastAttachedWidth = Math.max(13, ...augmentedInstances.map((i) => formatLastAttached(i.lastAttached).length)) + 2;
@@ -1427,6 +2098,7 @@ function InstanceList({
1427
2098
  return /* @__PURE__ */ jsxs2(Box, { flexDirection: "column", children: [
1428
2099
  /* @__PURE__ */ jsxs2(Box, { children: [
1429
2100
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("NAME", nameWidth) }),
2101
+ /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("REPO", repoWidth) }),
1430
2102
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("STATUS", statusWidth) }),
1431
2103
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("GIT", gitWidth) }),
1432
2104
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("LAST ATTACHED", lastAttachedWidth) }),
@@ -1435,6 +2107,7 @@ function InstanceList({
1435
2107
  ] }),
1436
2108
  augmentedInstances.map((instance) => /* @__PURE__ */ jsxs2(Box, { children: [
1437
2109
  /* @__PURE__ */ jsx2(Text2, { children: pad(instance.name, nameWidth) }),
2110
+ /* @__PURE__ */ jsx2(Text2, { color: "blue", children: pad(instance.repoSlug, repoWidth) }),
1438
2111
  /* @__PURE__ */ jsx2(Text2, { color: statusColor(instance.status), children: pad(statusLabel(instance.status, dockerAvailable), statusWidth) }),
1439
2112
  /* @__PURE__ */ jsx2(Box, { width: gitWidth, children: instance.indicators.map((ind, idx) => /* @__PURE__ */ jsxs2(Text2, { color: ind.color, children: [
1440
2113
  idx > 0 ? " " : "",
@@ -1587,7 +2260,7 @@ function parseBranches(result) {
1587
2260
  }
1588
2261
 
1589
2262
  // src/lib/list-instances.ts
1590
- async function listInstances(deps) {
2263
+ async function listInstances(deps, opts) {
1591
2264
  try {
1592
2265
  const container = deps?.container ?? createContainerLifecycle();
1593
2266
  const gitDetector = deps?.gitDetector ?? createGitStateDetector();
@@ -1598,41 +2271,55 @@ async function listInstances(deps) {
1598
2271
  return { ok: true, instances: [], dockerAvailable: true };
1599
2272
  }
1600
2273
  const dockerAvailable = await container.isDockerAvailable();
1601
- const instancePromises = workspaceNames.map(async (wsName) => {
2274
+ const repoFilter = opts?.repoFilter?.toLowerCase();
2275
+ const filteredWorkspaces = [];
2276
+ for (const wsName of workspaceNames) {
1602
2277
  const wsPath = getWorkspacePathByName(wsName, wsFsDeps);
1603
2278
  const state = await readState(wsPath, stateFsDeps);
1604
- const containerPromise = dockerAvailable ? container.containerStatus(state.containerName) : Promise.resolve(null);
1605
- const gitPromise = gitDetector.getGitState(wsPath.root);
1606
- const [containerResult, gitState] = await Promise.all([containerPromise, gitPromise]);
1607
- let status;
1608
- if (!dockerAvailable || containerResult === null) {
1609
- status = "unknown";
1610
- } else if (!containerResult.ok) {
1611
- status = "unknown";
1612
- } else if (containerResult.status === "not-found") {
1613
- status = "orphaned";
1614
- } else {
1615
- status = containerResult.status;
2279
+ if (repoFilter && state.repoSlug.toLowerCase() !== repoFilter) {
2280
+ continue;
1616
2281
  }
1617
- let sshConnection = null;
1618
- if (status === "running" && containerResult && containerResult.ok) {
1619
- const sshPort = containerResult.ports["22/tcp"];
1620
- if (sshPort) {
1621
- sshConnection = `node@${state.containerName}.orb.local`;
1622
- if (sshPort !== "22") {
1623
- sshConnection += ` (localhost:${sshPort})`;
2282
+ filteredWorkspaces.push({ wsName, wsPath, state });
2283
+ }
2284
+ const instancePromises = filteredWorkspaces.map(
2285
+ async ({ wsName, wsPath, state }) => {
2286
+ const containerPromise = dockerAvailable ? container.containerStatus(state.containerName) : Promise.resolve(null);
2287
+ const gitPromise = gitDetector.getGitState(wsPath.root);
2288
+ const [containerResult, gitState] = await Promise.all([containerPromise, gitPromise]);
2289
+ let status;
2290
+ if (!dockerAvailable || containerResult === null) {
2291
+ status = "unknown";
2292
+ } else if (!containerResult.ok) {
2293
+ status = "unknown";
2294
+ } else if (containerResult.status === "not-found") {
2295
+ status = "orphaned";
2296
+ } else {
2297
+ status = containerResult.status;
2298
+ }
2299
+ let sshConnection = null;
2300
+ if (status === "running" && containerResult && containerResult.ok) {
2301
+ if ("22/tcp" in containerResult.ports) {
2302
+ const orbDomains = containerResult.labels["dev.orbstack.domains"];
2303
+ const hostname = orbDomains?.split(",")[0]?.trim() || `${state.containerName}.orb.local`;
2304
+ sshConnection = `node@${hostname}`;
2305
+ const hostPort = containerResult.ports["22/tcp"];
2306
+ if (hostPort && hostPort !== "22") {
2307
+ sshConnection += ` (localhost:${hostPort})`;
2308
+ }
1624
2309
  }
1625
2310
  }
2311
+ return {
2312
+ name: wsName,
2313
+ repoSlug: state.repoSlug,
2314
+ repoUrl: state.repoUrl,
2315
+ status,
2316
+ lastAttached: state.lastAttached !== "unknown" ? state.lastAttached : null,
2317
+ purpose: state.purpose,
2318
+ gitState,
2319
+ sshConnection
2320
+ };
1626
2321
  }
1627
- return {
1628
- name: wsName,
1629
- status,
1630
- lastAttached: state.lastAttached !== "unknown" ? state.lastAttached : null,
1631
- purpose: state.purpose,
1632
- gitState,
1633
- sshConnection
1634
- };
1635
- });
2322
+ );
1636
2323
  const instances = await Promise.all(instancePromises);
1637
2324
  return { ok: true, instances, dockerAvailable };
1638
2325
  } catch (err) {
@@ -1647,8 +2334,10 @@ async function listInstances(deps) {
1647
2334
  }
1648
2335
 
1649
2336
  // src/commands/list.ts
1650
- var listCommand = new Command4("list").alias("ps").description("List all instances with status").option("--json", "Output in JSON format").action(async (options) => {
1651
- const result = await listInstances();
2337
+ 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) => {
2338
+ const result = await listInstances(void 0, {
2339
+ repoFilter: options.repo
2340
+ });
1652
2341
  if (!result.ok) {
1653
2342
  const error = createError(
1654
2343
  result.error.code,
@@ -1673,6 +2362,8 @@ var listCommand = new Command4("list").alias("ps").description("List all instanc
1673
2362
  ok: true,
1674
2363
  data: result.instances.map((i) => ({
1675
2364
  name: i.name,
2365
+ repoSlug: i.repoSlug,
2366
+ repoUrl: i.repoUrl,
1676
2367
  status: i.status,
1677
2368
  lastAttached: i.lastAttached,
1678
2369
  purpose: i.purpose,
@@ -1696,132 +2387,134 @@ var listCommand = new Command4("list").alias("ps").description("List all instanc
1696
2387
 
1697
2388
  // src/commands/purpose.ts
1698
2389
  import { Command as Command5 } from "commander";
1699
-
1700
- // src/lib/purpose-instance.ts
1701
- 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";
1702
- import { homedir as homedir4 } from "os";
1703
- function createPurposeDefaultDeps() {
1704
- return {
1705
- workspaceFsDeps: { mkdir: mkdir6, readdir: readdir5, stat: stat5, homedir: homedir4 },
1706
- stateFsDeps: { readFile: readFile5, writeFile: writeFile5, rename: rename4, mkdir: mkdir6, appendFile: appendFile4 }
1707
- };
1708
- }
1709
- function mapLookupError(lookup, instanceName) {
1710
- if (lookup.reason === "ambiguous") {
1711
- return {
1712
- ok: false,
1713
- error: {
1714
- code: "AMBIGUOUS_MATCH",
1715
- message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
1716
- suggestion: "Use the full workspace name to specify which instance."
1717
- }
1718
- };
1719
- }
1720
- return {
1721
- ok: false,
1722
- error: {
1723
- code: "WORKSPACE_NOT_FOUND",
1724
- message: `Instance '${instanceName}' not found`,
1725
- suggestion: "Use `agent-env list` to see available instances."
2390
+ var defaultPurposeCommandDeps = {
2391
+ isInsideContainer
2392
+ };
2393
+ function createPurposeCommand(deps = defaultPurposeCommandDeps) {
2394
+ return new Command5("purpose").description(
2395
+ "Get or set the purpose/label for an instance. Inside a container: no instance name needed (agent-env purpose [value])"
2396
+ ).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) => {
2397
+ if (deps.isInsideContainer()) {
2398
+ await handleContainerMode(nameOrValue);
2399
+ } else {
2400
+ await handleHostMode(nameOrValue, value, options?.repo);
1726
2401
  }
1727
- };
2402
+ });
1728
2403
  }
1729
- async function getPurpose(instanceName, deps) {
1730
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1731
- if (!lookup.found) {
1732
- return mapLookupError(lookup, instanceName);
2404
+ var purposeCommand = createPurposeCommand();
2405
+ async function handleContainerMode(purposeValue) {
2406
+ const deps = createContainerPurposeDefaultDeps();
2407
+ if (purposeValue === void 0) {
2408
+ const result = await getContainerPurpose(deps);
2409
+ handleGetResult(result);
2410
+ } else {
2411
+ const result = await setContainerPurpose(purposeValue, deps);
2412
+ handleSetResult(result);
1733
2413
  }
1734
- const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1735
- const state = await readState(wsPath, deps.stateFsDeps);
1736
- return { ok: true, purpose: state.purpose };
1737
2414
  }
1738
- async function setPurpose(instanceName, value, deps) {
1739
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1740
- if (!lookup.found) {
1741
- return mapLookupError(lookup, instanceName);
2415
+ async function handleHostMode(name, value, repo) {
2416
+ if (!name) {
2417
+ console.error(
2418
+ formatError(
2419
+ createError(
2420
+ "MISSING_ARGUMENT",
2421
+ "Instance name is required when running on the host",
2422
+ "Usage: agent-env purpose <name> [value]"
2423
+ )
2424
+ )
2425
+ );
2426
+ process.exit(1);
2427
+ return;
1742
2428
  }
1743
- const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1744
- const state = await readState(wsPath, deps.stateFsDeps);
1745
- const cleared = value === "";
1746
- const updatedState = {
1747
- ...state,
1748
- purpose: cleared ? null : value
1749
- };
1750
- await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
1751
- return { ok: true, cleared };
1752
- }
1753
-
1754
- // src/commands/purpose.ts
1755
- 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) => {
2429
+ const repoSlug = await resolveRepoOrExit({ repo, cwd: process.cwd() });
1756
2430
  const deps = createPurposeDefaultDeps();
1757
2431
  if (value === void 0) {
1758
- const result = await getPurpose(name, deps);
1759
- if (!result.ok) {
1760
- const { code, message, suggestion } = result.error;
1761
- console.error(formatError(createError(code, message, suggestion)));
1762
- process.exit(1);
1763
- }
1764
- if (result.purpose === null) {
1765
- console.log("(no purpose set)");
1766
- } else {
1767
- console.log(result.purpose);
1768
- }
2432
+ const result = await getPurpose(name, deps, repoSlug);
2433
+ handleGetResult(result);
1769
2434
  } else {
1770
- const result = await setPurpose(name, value, deps);
1771
- if (!result.ok) {
1772
- const { code, message, suggestion } = result.error;
1773
- console.error(formatError(createError(code, message, suggestion)));
1774
- process.exit(1);
1775
- }
1776
- if (result.cleared) {
1777
- console.log("Purpose cleared");
1778
- } else {
1779
- console.log("Purpose updated");
1780
- }
2435
+ const result = await setPurpose(name, value, deps, repoSlug);
2436
+ handleSetResult(result);
1781
2437
  }
1782
- });
2438
+ }
2439
+ function handleGetResult(result) {
2440
+ if (!result.ok) {
2441
+ const { code, message, suggestion } = result.error;
2442
+ console.error(formatError(createError(code, message, suggestion)));
2443
+ process.exit(1);
2444
+ }
2445
+ if (result.purpose === null) {
2446
+ console.log("(no purpose set)");
2447
+ } else {
2448
+ console.log(result.purpose);
2449
+ }
2450
+ }
2451
+ function handleSetResult(result) {
2452
+ if (!result.ok) {
2453
+ const { code, message, suggestion } = result.error;
2454
+ console.error(formatError(createError(code, message, suggestion)));
2455
+ process.exit(1);
2456
+ }
2457
+ if (result.cleared) {
2458
+ console.log("Purpose cleared");
2459
+ } else {
2460
+ console.log("Purpose updated");
2461
+ }
2462
+ }
1783
2463
 
1784
2464
  // src/commands/rebuild.ts
1785
2465
  import chalk from "chalk";
1786
2466
  import { Command as Command6 } from "commander";
1787
- import { createInterface } from "readline";
2467
+ import { createInterface as createInterface2 } from "readline";
1788
2468
 
1789
2469
  // src/lib/rebuild-instance.ts
1790
2470
  import {
1791
2471
  cp as cp3,
1792
2472
  mkdir as mkdir7,
1793
2473
  readdir as readdir6,
1794
- readFile as readFile6,
2474
+ readFile as readFile8,
1795
2475
  rename as rename5,
1796
2476
  rm as rm3,
1797
2477
  stat as stat6,
1798
- writeFile as writeFile6,
2478
+ writeFile as writeFile7,
1799
2479
  appendFile as appendFile5
1800
2480
  } from "fs/promises";
1801
2481
  import { homedir as homedir5 } from "os";
1802
- import { join as join6 } from "path";
2482
+ import { join as join7 } from "path";
1803
2483
  function createRebuildDefaultDeps() {
1804
2484
  const executor = createExecutor();
1805
2485
  return {
1806
2486
  executor,
1807
2487
  container: createContainerLifecycle(executor),
1808
2488
  workspaceFsDeps: { mkdir: mkdir7, readdir: readdir6, stat: stat6, homedir: homedir5 },
1809
- stateFsDeps: { readFile: readFile6, writeFile: writeFile6, rename: rename5, mkdir: mkdir7, appendFile: appendFile5 },
1810
- devcontainerFsDeps: { cp: cp3, mkdir: mkdir7, readdir: readdir6, readFile: readFile6, stat: stat6, writeFile: writeFile6 },
2489
+ stateFsDeps: { readFile: readFile8, writeFile: writeFile7, rename: rename5, mkdir: mkdir7, appendFile: appendFile5 },
2490
+ devcontainerFsDeps: { cp: cp3, mkdir: mkdir7, readdir: readdir6, readFile: readFile8, stat: stat6, writeFile: writeFile7 },
1811
2491
  rm: rm3,
1812
2492
  rename: rename5,
1813
2493
  logger: { warn: (msg) => console.warn(msg), info: (msg) => console.info(msg) }
1814
2494
  };
1815
2495
  }
1816
- async function refreshConfig(wsRoot, containerName, configSource, deps) {
2496
+ async function refreshConfig(wsRoot, containerName, configSource, envVars, deps) {
1817
2497
  if (configSource === "baseline") {
1818
- const agentEnvDir = join6(wsRoot, AGENT_ENV_DIR);
2498
+ const agentEnvDir = join7(wsRoot, AGENT_ENV_DIR);
1819
2499
  try {
1820
2500
  await deps.devcontainerFsDeps.mkdir(agentEnvDir, { recursive: true });
1821
2501
  await deps.devcontainerFsDeps.cp(getBaselineConfigPath(), agentEnvDir, {
1822
2502
  recursive: true
1823
2503
  });
1824
- await patchContainerName(wsRoot, containerName, deps.devcontainerFsDeps, AGENT_ENV_DIR);
2504
+ const templatePath = join7(agentEnvDir, "statusBar.template.json");
2505
+ try {
2506
+ await deps.devcontainerFsDeps.stat(templatePath);
2507
+ } catch (err) {
2508
+ if (err.code !== "ENOENT") throw err;
2509
+ await copyStatusBarTemplate(wsRoot, deps.devcontainerFsDeps);
2510
+ }
2511
+ await applyBaselinePatches(
2512
+ wsRoot,
2513
+ containerName,
2514
+ envVars,
2515
+ deps.devcontainerFsDeps,
2516
+ AGENT_ENV_DIR
2517
+ );
1825
2518
  } catch (err) {
1826
2519
  return {
1827
2520
  ok: false,
@@ -1844,10 +2537,10 @@ async function refreshConfig(wsRoot, containerName, configSource, deps) {
1844
2537
  }
1845
2538
  };
1846
2539
  }
1847
- const devcontainerDir = join6(wsRoot, ".devcontainer");
2540
+ const devcontainerDir = join7(wsRoot, ".devcontainer");
1848
2541
  const dirExists = await deps.devcontainerFsDeps.stat(devcontainerDir).catch(() => null);
1849
2542
  if (dirExists) {
1850
- const jsonExists = await deps.devcontainerFsDeps.stat(join6(devcontainerDir, "devcontainer.json")).catch(() => null);
2543
+ const jsonExists = await deps.devcontainerFsDeps.stat(join7(devcontainerDir, "devcontainer.json")).catch(() => null);
1851
2544
  if (!jsonExists) {
1852
2545
  return {
1853
2546
  ok: false,
@@ -1862,27 +2555,13 @@ async function refreshConfig(wsRoot, containerName, configSource, deps) {
1862
2555
  }
1863
2556
  return { ok: true };
1864
2557
  }
1865
- async function lookupWorkspace(instanceName, deps) {
1866
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
2558
+ async function lookupWorkspace(instanceName, deps, repoSlug) {
2559
+ const lookup = await resolveInstance(instanceName, repoSlug, {
2560
+ fsDeps: deps.workspaceFsDeps,
2561
+ readFile: deps.stateFsDeps.readFile
2562
+ });
1867
2563
  if (!lookup.found) {
1868
- if (lookup.reason === "ambiguous") {
1869
- return {
1870
- ok: false,
1871
- error: {
1872
- code: "AMBIGUOUS_MATCH",
1873
- message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
1874
- suggestion: "Use the full workspace name to specify which instance."
1875
- }
1876
- };
1877
- }
1878
- return {
1879
- ok: false,
1880
- error: {
1881
- code: "WORKSPACE_NOT_FOUND",
1882
- message: `Instance '${instanceName}' not found`,
1883
- suggestion: "Use `agent-env list` to see available instances."
1884
- }
1885
- };
2564
+ return { ok: false, error: lookup.error };
1886
2565
  }
1887
2566
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1888
2567
  const state = await readState(wsPath, deps.stateFsDeps);
@@ -1961,14 +2640,33 @@ async function teardownContainer(containerName, container, statusResult) {
1961
2640
  }
1962
2641
  return { ok: true };
1963
2642
  }
1964
- async function rebuildInstance(instanceName, deps, options) {
2643
+ async function startAndDiscoverContainer(wsPath, containerName, configSource, purpose, buildNoCache, container) {
2644
+ const baselineConfigPath = configSource === "baseline" ? join7(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
2645
+ const containerResult = await container.devcontainerUp(wsPath.root, containerName, {
2646
+ buildNoCache,
2647
+ remoteEnv: { AGENT_INSTANCE: wsPath.name, AGENT_ENV_PURPOSE: purpose },
2648
+ configPath: baselineConfigPath
2649
+ });
2650
+ if (!containerResult.ok) {
2651
+ return { ok: false, error: containerResult.error };
2652
+ }
2653
+ let actualName = containerName;
2654
+ if (containerResult.containerId) {
2655
+ const discovered = await container.getContainerNameById(containerResult.containerId);
2656
+ if (discovered) {
2657
+ actualName = discovered;
2658
+ }
2659
+ }
2660
+ return { ok: true, containerName: actualName };
2661
+ }
2662
+ async function rebuildInstance(instanceName, deps, options, repoSlug) {
1965
2663
  const {
1966
2664
  force = false,
1967
2665
  configSource: overrideConfigSource,
1968
2666
  pull = true,
1969
2667
  noCache = true
1970
2668
  } = options ?? {};
1971
- const wsLookup = await lookupWorkspace(instanceName, deps);
2669
+ const wsLookup = await lookupWorkspace(instanceName, deps, repoSlug);
1972
2670
  if (!wsLookup.ok) {
1973
2671
  return { ok: false, error: wsLookup.error };
1974
2672
  }
@@ -1996,7 +2694,12 @@ async function rebuildInstance(instanceName, deps, options) {
1996
2694
  }
1997
2695
  };
1998
2696
  }
1999
- const configResult = await refreshConfig(wsPath.root, containerName, configSource, deps);
2697
+ const envVars = {
2698
+ AGENT_ENV_INSTANCE: wsPath.name,
2699
+ AGENT_ENV_REPO: state.repoSlug ?? "",
2700
+ AGENT_ENV_PURPOSE: state.purpose ?? ""
2701
+ };
2702
+ const configResult = await refreshConfig(wsPath.root, containerName, configSource, envVars, deps);
2000
2703
  if (!configResult.ok) {
2001
2704
  return { ok: false, error: configResult.error };
2002
2705
  }
@@ -2022,36 +2725,26 @@ async function rebuildInstance(instanceName, deps, options) {
2022
2725
  if (!teardownResult.ok) {
2023
2726
  return { ok: false, error: teardownResult.error, wasRunning };
2024
2727
  }
2025
- const buildNoCache = noCache && hasDockerfile;
2026
- const baselineConfigPath = configSource === "baseline" ? join6(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
2027
- const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
2028
- buildNoCache,
2029
- remoteEnv: { AGENT_INSTANCE: wsPath.name },
2030
- configPath: baselineConfigPath
2031
- });
2032
- if (!containerResult.ok) {
2033
- return {
2034
- ok: false,
2035
- error: containerResult.error,
2036
- wasRunning
2037
- };
2038
- }
2039
- let actualContainerName = containerName;
2040
- if (containerResult.containerId) {
2041
- const discovered = await deps.container.getContainerNameById(containerResult.containerId);
2042
- if (discovered) {
2043
- actualContainerName = discovered;
2044
- }
2728
+ const startResult = await startAndDiscoverContainer(
2729
+ wsPath,
2730
+ containerName,
2731
+ configSource,
2732
+ state.purpose ?? "",
2733
+ noCache && hasDockerfile,
2734
+ deps.container
2735
+ );
2736
+ if (!startResult.ok) {
2737
+ return { ok: false, error: startResult.error, wasRunning };
2045
2738
  }
2046
2739
  const updatedState = {
2047
2740
  ...state,
2048
- containerName: actualContainerName,
2741
+ containerName: startResult.containerName,
2049
2742
  lastRebuilt: (/* @__PURE__ */ new Date()).toISOString()
2050
2743
  };
2051
2744
  await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
2052
2745
  return {
2053
2746
  ok: true,
2054
- containerName: actualContainerName,
2747
+ containerName: startResult.containerName,
2055
2748
  wasRunning
2056
2749
  };
2057
2750
  }
@@ -2059,7 +2752,7 @@ async function rebuildInstance(instanceName, deps, options) {
2059
2752
  // src/commands/rebuild.ts
2060
2753
  function promptForConfirmation(instanceName) {
2061
2754
  return new Promise((resolve2) => {
2062
- const rl = createInterface({
2755
+ const rl = createInterface2({
2063
2756
  input: process.stdin,
2064
2757
  output: process.stderr
2065
2758
  });
@@ -2078,9 +2771,10 @@ Any active sessions will be lost. Continue? (y/N) `,
2078
2771
  });
2079
2772
  });
2080
2773
  }
2081
- var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by recreating its container").argument("<name>", "Instance name to rebuild").option("--force", "Rebuild even if the container is currently running").option("--yes", "Skip confirmation prompt").option("--no-pull", "Skip pulling fresh base images").option("--use-cache", "Allow Docker build layer cache reuse").action(
2774
+ 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(
2082
2775
  async (name, options) => {
2083
2776
  const deps = createRebuildDefaultDeps();
2777
+ const repoSlug = await resolveRepoOrExit({ repo: options.repo, cwd: process.cwd() });
2084
2778
  let confirmed = false;
2085
2779
  if (!options.yes && !options.force && process.stdin.isTTY) {
2086
2780
  confirmed = await promptForConfirmation(name);
@@ -2100,7 +2794,7 @@ var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by
2100
2794
  } else {
2101
2795
  console.log(`Rebuilding instance '${name}'...`);
2102
2796
  }
2103
- const result = await rebuildInstance(name, deps, rebuildOptions);
2797
+ const result = await rebuildInstance(name, deps, rebuildOptions, repoSlug);
2104
2798
  if (!result.ok) {
2105
2799
  if (result.error.code === "CONTAINER_RUNNING") {
2106
2800
  console.error("");
@@ -2124,21 +2818,21 @@ var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by
2124
2818
  // src/commands/remove.ts
2125
2819
  import chalk3 from "chalk";
2126
2820
  import { Command as Command7 } from "commander";
2127
- import { createInterface as createInterface2 } from "readline";
2821
+ import { createInterface as createInterface3 } from "readline";
2128
2822
 
2129
2823
  // src/lib/audit-log.ts
2130
2824
  import { appendFile as appendFile6, mkdir as mkdir8 } from "fs/promises";
2131
2825
  import { homedir as homedir6 } from "os";
2132
- import { join as join7 } from "path";
2826
+ import { join as join8 } from "path";
2133
2827
  function createAuditLogDefaultDeps() {
2134
2828
  return { appendFile: appendFile6, mkdir: mkdir8, homedir: homedir6 };
2135
2829
  }
2136
2830
  function getAuditLogPath(deps) {
2137
- return join7(deps.homedir(), AGENT_ENV_DIR, "audit.log");
2831
+ return join8(deps.homedir(), AGENT_ENV_DIR, "audit.log");
2138
2832
  }
2139
2833
  async function writeAuditLogEntry(entry, deps = createAuditLogDefaultDeps()) {
2140
2834
  const logPath = getAuditLogPath(deps);
2141
- await deps.mkdir(join7(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
2835
+ await deps.mkdir(join8(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
2142
2836
  const line = JSON.stringify(entry) + "\n";
2143
2837
  await deps.appendFile(logPath, line, "utf-8");
2144
2838
  }
@@ -2153,7 +2847,7 @@ function createAuditEntry(instanceName, gitState, confirmationMethod) {
2153
2847
  }
2154
2848
 
2155
2849
  // src/lib/remove-instance.ts
2156
- import { mkdir as mkdir9, readdir as readdir7, readFile as readFile7, rm as rm4, stat as stat7 } from "fs/promises";
2850
+ import { mkdir as mkdir9, readdir as readdir7, readFile as readFile9, rm as rm4, stat as stat7 } from "fs/promises";
2157
2851
  import { homedir as homedir7 } from "os";
2158
2852
  function createRemoveDefaultDeps() {
2159
2853
  const executor = createExecutor();
@@ -2162,7 +2856,7 @@ function createRemoveDefaultDeps() {
2162
2856
  container: createContainerLifecycle(executor),
2163
2857
  gitDetector: createGitStateDetector(executor),
2164
2858
  workspaceFsDeps: { mkdir: mkdir9, readdir: readdir7, stat: stat7, homedir: homedir7 },
2165
- stateFsDeps: { readFile: readFile7 },
2859
+ stateFsDeps: { readFile: readFile9 },
2166
2860
  deleteFsDeps: { rm: rm4 }
2167
2861
  };
2168
2862
  }
@@ -2200,27 +2894,13 @@ function evaluateSafetyChecks(gitState) {
2200
2894
  }
2201
2895
  return blockers;
2202
2896
  }
2203
- async function removeInstance(instanceName, deps, force = false) {
2204
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
2897
+ async function removeInstance(instanceName, deps, force = false, repoSlug) {
2898
+ const lookup = await resolveInstance(instanceName, repoSlug, {
2899
+ fsDeps: deps.workspaceFsDeps,
2900
+ readFile: deps.stateFsDeps.readFile
2901
+ });
2205
2902
  if (!lookup.found) {
2206
- if (lookup.reason === "ambiguous") {
2207
- return {
2208
- ok: false,
2209
- error: {
2210
- code: "AMBIGUOUS_MATCH",
2211
- message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
2212
- suggestion: "Use the full workspace name to specify which instance."
2213
- }
2214
- };
2215
- }
2216
- return {
2217
- ok: false,
2218
- error: {
2219
- code: "WORKSPACE_NOT_FOUND",
2220
- message: `Instance '${instanceName}' not found`,
2221
- suggestion: "Use `agent-env list` to see available instances."
2222
- }
2223
- };
2903
+ return { ok: false, error: lookup.error };
2224
2904
  }
2225
2905
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
2226
2906
  const state = await readState(wsPath, deps.stateFsDeps);
@@ -2396,7 +3076,7 @@ function formatSafetyReport(instanceName, blockers, gitState) {
2396
3076
  function promptForConfirmation2(instanceName) {
2397
3077
  return new Promise((resolve2) => {
2398
3078
  let resolved = false;
2399
- const rl = createInterface2({
3079
+ const rl = createInterface3({
2400
3080
  input: process.stdin,
2401
3081
  output: process.stderr
2402
3082
  });
@@ -2456,7 +3136,7 @@ async function resolveConfirmation(name, options) {
2456
3136
  }
2457
3137
  return "typed-name";
2458
3138
  }
2459
- var removeCommand = new Command7("remove").description("Remove an instance with safety checks").argument("<name>", "Instance name to remove").option("--force", "Force removal, bypassing safety checks").option(
3139
+ 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(
2460
3140
  "--yes",
2461
3141
  "Skip confirmation prompt for --force (DANGEROUS: skips all safety prompts, for scripts only)"
2462
3142
  ).action(async (name, options) => {
@@ -2473,8 +3153,9 @@ var removeCommand = new Command7("remove").description("Remove an instance with
2473
3153
  process.exit(1);
2474
3154
  return;
2475
3155
  }
3156
+ const repoSlug = await resolveRepoOrExit({ repo: options.repo, cwd: process.cwd() });
2476
3157
  const deps = createRemoveDefaultDeps();
2477
- const checkResult = await removeInstance(name, deps, false);
3158
+ const checkResult = await removeInstance(name, deps, false, repoSlug);
2478
3159
  if (checkResult.ok) {
2479
3160
  if (options.force) {
2480
3161
  console.log(`Instance '${name}' force-removed. Data permanently deleted.`);
@@ -2506,7 +3187,7 @@ var removeCommand = new Command7("remove").description("Remove an instance with
2506
3187
  process.exit(1);
2507
3188
  return;
2508
3189
  }
2509
- const forceResult = await removeInstance(name, deps, true);
3190
+ const forceResult = await removeInstance(name, deps, true, repoSlug);
2510
3191
  if (!forceResult.ok) {
2511
3192
  const { code, message, suggestion } = forceResult.error;
2512
3193
  console.error(formatError(createError(code, message, suggestion)));
@@ -2517,6 +3198,58 @@ var removeCommand = new Command7("remove").description("Remove an instance with
2517
3198
  await writeAuditLog(name, gitState ?? null, confirmationMethod);
2518
3199
  });
2519
3200
 
3201
+ // src/commands/repos.ts
3202
+ import { Command as Command8 } from "commander";
3203
+ var reposCommand = new Command8("repos").description("List tracked repositories").option("--json", "Output in JSON format").action(async (options) => {
3204
+ const result = await listRepos();
3205
+ if (!result.ok) {
3206
+ const error = createError(
3207
+ result.error.code,
3208
+ result.error.message,
3209
+ "Check if ~/.agent-env/workspaces/ is accessible."
3210
+ );
3211
+ if (options.json) {
3212
+ const output = {
3213
+ ok: false,
3214
+ data: null,
3215
+ error: { code: error.code, message: error.message, suggestion: error.suggestion }
3216
+ };
3217
+ console.log(JSON.stringify(output, null, 2));
3218
+ } else {
3219
+ console.error(formatError(error));
3220
+ }
3221
+ process.exitCode = 1;
3222
+ return;
3223
+ }
3224
+ if (options.json) {
3225
+ const output = {
3226
+ ok: true,
3227
+ data: result.repos.map((r) => ({
3228
+ slug: r.slug,
3229
+ url: r.url,
3230
+ instanceCount: r.instanceCount
3231
+ })),
3232
+ error: null
3233
+ };
3234
+ console.log(JSON.stringify(output, null, 2));
3235
+ return;
3236
+ }
3237
+ if (result.repos.length === 0) {
3238
+ console.log(
3239
+ "No repositories tracked. Create an instance with: agent-env create <name> --repo <url|slug>"
3240
+ );
3241
+ return;
3242
+ }
3243
+ const slugWidth = Math.max(4, ...result.repos.map((r) => r.slug.length));
3244
+ const countWidth = 10;
3245
+ const header = `${"REPO".padEnd(slugWidth)} ${"INSTANCES".padEnd(countWidth)} URL`;
3246
+ console.log(header);
3247
+ for (const repo of result.repos) {
3248
+ const line = `${repo.slug.padEnd(slugWidth)} ${String(repo.instanceCount).padEnd(countWidth)} ${repo.url}`;
3249
+ console.log(line);
3250
+ }
3251
+ });
3252
+
2520
3253
  // src/components/InteractiveMenu.tsx
2521
3254
  import { Select } from "@inkjs/ui";
2522
3255
  import { Box as Box2, Text as Text3 } from "ink";
@@ -2699,6 +3432,7 @@ program.addCommand(attachCommand);
2699
3432
  program.addCommand(rebuildCommand);
2700
3433
  program.addCommand(removeCommand);
2701
3434
  program.addCommand(purposeCommand);
3435
+ program.addCommand(reposCommand);
2702
3436
  program.addCommand(completionCommand);
2703
3437
  program.action(async () => {
2704
3438
  if (!process.stdin.isTTY) {