@zookanalytics/agent-env 0.3.0 → 0.4.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/README.md CHANGED
@@ -13,6 +13,133 @@ npm install -g @zookanalytics/agent-env
13
13
  - Node.js >= 20
14
14
  - Docker (OrbStack recommended on macOS)
15
15
 
16
+ ## Workspace Structure
17
+
18
+ Each agent environment creates a `.agent-env/` directory inside the workspace to store instance-specific data:
19
+
20
+ ```
21
+ <workspace>/
22
+ ├── .agent-env/ # Instance data (git-ignored)
23
+ │ ├── state.json # Instance metadata (repo URL, container name, config source)
24
+ │ ├── ssh/ # SSH host keys (container identity)
25
+ │ │ ├── ssh_host_ed25519_key
26
+ │ │ ├── ssh_host_ed25519_key.pub
27
+ │ │ ├── ssh_host_rsa_key
28
+ │ │ └── ssh_host_rsa_key.pub
29
+ │ ├── devcontainer.json # Baseline config (only if using baseline)
30
+ │ └── init-host.sh # Baseline init script (only if using baseline)
31
+ ├── .devcontainer/ # Project's devcontainer config (if present)
32
+ └── <your code>
33
+ ```
34
+
35
+ **What's in `.agent-env/`:**
36
+
37
+ - **`state.json`** - Instance metadata including repository URL, container name, and configuration source
38
+ - **`ssh/`** - SSH host keys that persist across container restarts, preventing "host identification changed" warnings
39
+ - **`devcontainer.json`** - Copied from baseline config when creating instances without their own `.devcontainer/`
40
+ - **`init-host.sh`** - Host-side initialization script (baseline configs only)
41
+
42
+ **Git exclusion:**
43
+
44
+ The `.agent-env/` directory is automatically added to `.git/info/exclude` so instance state doesn't appear as untracked files in your git status.
45
+
46
+ ## SSH Access
47
+
48
+ Each agent environment runs an SSH server, allowing you to connect directly:
49
+
50
+ ```bash
51
+ # On OrbStack (recommended)
52
+ ssh node@ae-<instance-name>.orb.local
53
+
54
+ # Via port forwarding (automatic fallback)
55
+ ssh -p <port> node@localhost
56
+
57
+ # Find connection details
58
+ agent-env list # Shows SSH connection strings
59
+ ```
60
+
61
+ ### How It Works
62
+
63
+ **Host Keys (Container Identity)**
64
+
65
+ Each container generates unique SSH host keys on first creation, stored in `.agent-env/ssh/` inside the workspace:
66
+ - `ssh_host_ed25519_key` / `ssh_host_ed25519_key.pub`
67
+ - `ssh_host_rsa_key` / `ssh_host_rsa_key.pub`
68
+
69
+ These persist across container stops/starts/rebuilds, ensuring you don't get "host identification changed" warnings. They identify the SSH **server** (the container's sshd).
70
+
71
+ **User Keys (Your Identity)**
72
+
73
+ Your public SSH keys from `~/.ssh/*.pub` are automatically staged into the container's `authorized_keys`. The private keys remain on your host - containers only see your public keys.
74
+
75
+ **Why separate host and user keys?**
76
+ - **Host keys**: Container proves "I'm the legitimate ae-my-project server"
77
+ - **User keys**: You prove "I'm authorized to access this container"
78
+
79
+ This is standard SSH architecture - the same pattern used by any SSH server.
80
+
81
+ ## Commit Signing Setup
82
+
83
+ Agent environments support commit signing via **SSH signing** (recommended) or GPG signing.
84
+
85
+ ### SSH Signing (Recommended)
86
+
87
+ SSH signing is recommended because:
88
+ - SSH agent forwarding is built into Docker Desktop
89
+ - No additional background processes needed
90
+ - Works reliably on macOS with Docker Desktop
91
+ - Supported by GitHub, GitLab, and Gitea
92
+
93
+ **Setup:**
94
+
95
+ 1. **Configure git to use the public key content directly:**
96
+
97
+ ```bash
98
+ # Configure git to use SSH signing with the actual key content
99
+ git config --global gpg.format ssh
100
+ git config --global user.signingkey "$(cat ~/.ssh/id_ed25519.pub)"
101
+ git config --global commit.gpgsign true
102
+ ```
103
+
104
+ This embeds the public key content in your `.gitconfig`:
105
+ ```ini
106
+ [gpg]
107
+ format = ssh
108
+ [user]
109
+ signingkey = ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... user@host
110
+ [commit]
111
+ gpgsign = true
112
+ ```
113
+
114
+ **Why use the key content instead of a file path?**
115
+
116
+ Your `.gitconfig` is mounted from the host into containers, but SSH keys are NOT copied in. Instead, the SSH agent socket is forwarded. The public key content acts as an identifier telling git which key pair to use - the actual signing happens via the forwarded SSH agent using your private key.
117
+
118
+ File paths like `~/.ssh/id_ed25519.pub` won't work because:
119
+ - Host path: `/Users/you/.ssh/id_ed25519.pub`
120
+ - Container path: `/home/node/.ssh/id_ed25519.pub` (doesn't exist - keys aren't copied)
121
+
122
+ Using the key content directly avoids this path mismatch entirely.
123
+
124
+ 2. **Verify SSH agent has your key:**
125
+
126
+ ```bash
127
+ ssh-add -l # Should list your SSH key
128
+ ```
129
+
130
+ Commit signing will now work in all containers automatically.
131
+
132
+ ### GPG Signing
133
+
134
+ GPG signing has limitations on macOS with Docker Desktop:
135
+ - Unix domain sockets cannot be bind-mounted from macOS to Linux containers
136
+ - Requires SSH tunneling or relay processes per container
137
+ - Complex lifecycle management
138
+
139
+ **If you must use GPG:**
140
+ - GPG signing works when opening containers in VS Code (built-in forwarding)
141
+ - For CLI-based workflows, consider SSH signing instead
142
+
16
143
  ## Usage
17
144
 
18
145
  ```bash
@@ -1,4 +1,10 @@
1
1
  {
2
2
  "image": "ghcr.io/zookanalytics/bmad-orchestrator/devcontainer:latest",
3
- "initializeCommand": "bash .agent-env/init-host.sh"
3
+ "initializeCommand": "bash .agent-env/init-host.sh",
4
+ "mounts": [
5
+ "source=${localWorkspaceFolder}/.agent-env,target=/etc/agent-env,type=bind"
6
+ ],
7
+ "containerEnv": {
8
+ "AGENT_ENV_CONTAINER": "true"
9
+ }
4
10
  }
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.0",
45
+ version: "0.4.0",
46
46
  description: "CLI for creating isolated, AI-ready development environments",
47
47
  type: "module",
48
48
  bin: {
@@ -103,8 +103,8 @@ 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";
106
+ 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";
107
+ import { homedir as homedir4 } from "os";
108
108
  import { join as join5 } from "path";
109
109
 
110
110
  // src/lib/container.ts
@@ -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,17 +406,17 @@ 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 readFile4,
414
+ rename as rename3,
408
415
  rm as rm2,
409
- stat as stat3,
410
- writeFile as writeFile3
416
+ stat as stat4,
417
+ writeFile as writeFile4
411
418
  } from "fs/promises";
412
- import { homedir as homedir2 } from "os";
419
+ import { homedir as homedir3 } from "os";
413
420
  import { dirname as dirname2, join as join4 } from "path";
414
421
 
415
422
  // src/lib/devcontainer.ts
@@ -489,6 +496,14 @@ async function patchContainerName(workspacePath, containerName, deps = defaultFs
489
496
  config.runArgs = [...filtered, `--name=${containerName}`];
490
497
  await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
491
498
  }
499
+ async function patchContainerEnv(workspacePath, envVars, deps = defaultFsDeps, configDir = DEVCONTAINER_DIR) {
500
+ const configPath = join(workspacePath, configDir, DEVCONTAINER_JSON);
501
+ const content = await deps.readFile(configPath, "utf-8");
502
+ const config = JSON.parse(content);
503
+ const existing = typeof config.containerEnv === "object" && config.containerEnv !== null ? config.containerEnv : {};
504
+ config.containerEnv = { ...existing, ...envVars };
505
+ await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
506
+ }
492
507
  async function resolveDockerfilePath(workspacePath, deps) {
493
508
  const candidates = [
494
509
  join(workspacePath, DEVCONTAINER_DIR, DEVCONTAINER_JSON),
@@ -559,6 +574,20 @@ function parseDockerfileImages(content, logger) {
559
574
  return [...images];
560
575
  }
561
576
 
577
+ // src/lib/purpose-instance.ts
578
+ import { appendFile as appendFile2, mkdir as mkdir4, readdir as readdir3, readFile as readFile3, rename as rename2, stat as stat3, writeFile as writeFile3 } from "fs/promises";
579
+ import { homedir as homedir2 } from "os";
580
+
581
+ // src/lib/container-env.ts
582
+ var CONTAINER_STATE_PATH = "/etc/agent-env/state.json";
583
+ var CONTAINER_AGENT_ENV_DIR = "/etc/agent-env";
584
+ var defaultContainerEnvDeps = {
585
+ getEnv: (key) => process.env[key]
586
+ };
587
+ function isInsideContainer(deps = defaultContainerEnvDeps) {
588
+ return deps.getEnv("AGENT_ENV_CONTAINER") === "true";
589
+ }
590
+
562
591
  // src/lib/state.ts
563
592
  import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
564
593
  import { join as join2 } from "path";
@@ -586,14 +615,14 @@ async function writeStateAtomic(wsPath, state, deps = defaultStateFsDeps) {
586
615
  await deps.rename(tmpPath, wsPath.stateFile);
587
616
  }
588
617
  function createInitialState(name, repo, options) {
589
- const { containerName, configSource } = options ?? {};
618
+ const { containerName, configSource, purpose } = options ?? {};
590
619
  const now = (/* @__PURE__ */ new Date()).toISOString();
591
620
  return {
592
621
  name,
593
622
  repo,
594
623
  createdAt: now,
595
624
  lastAttached: now,
596
- purpose: null,
625
+ purpose: purpose ?? null,
597
626
  containerName: containerName ?? `${CONTAINER_PREFIX}${name}`,
598
627
  configSource: configSource ?? "baseline"
599
628
  };
@@ -601,7 +630,7 @@ function createInitialState(name, repo, options) {
601
630
  function isValidState(value) {
602
631
  if (typeof value !== "object" || value === null) return false;
603
632
  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";
633
+ return typeof obj.name === "string" && typeof obj.repo === "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
634
  }
606
635
  var GIT_EXCLUDE_PATTERN = `${AGENT_ENV_DIR}/`;
607
636
  async function ensureGitExclude(workspaceRoot, deps = defaultStateFsDeps) {
@@ -692,6 +721,142 @@ async function deleteWorkspace(wsPath, deps = defaultDeleteFsDeps) {
692
721
  await deps.rm(wsPath.root, { recursive: true, force: true });
693
722
  }
694
723
 
724
+ // src/lib/purpose-instance.ts
725
+ var MAX_PURPOSE_LENGTH = 200;
726
+ function createPurposeDefaultDeps() {
727
+ return {
728
+ workspaceFsDeps: { mkdir: mkdir4, readdir: readdir3, stat: stat3, homedir: homedir2 },
729
+ stateFsDeps: { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 }
730
+ };
731
+ }
732
+ function validatePurposeLength(value) {
733
+ if (value.length > MAX_PURPOSE_LENGTH) {
734
+ return {
735
+ ok: false,
736
+ error: {
737
+ code: "PURPOSE_TOO_LONG",
738
+ message: `Purpose must be ${MAX_PURPOSE_LENGTH} characters or fewer (got ${value.length})`
739
+ }
740
+ };
741
+ }
742
+ return null;
743
+ }
744
+ function mapLookupError(lookup, instanceName) {
745
+ if (lookup.reason === "ambiguous") {
746
+ return {
747
+ ok: false,
748
+ error: {
749
+ code: "AMBIGUOUS_MATCH",
750
+ message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
751
+ suggestion: "Use the full workspace name to specify which instance."
752
+ }
753
+ };
754
+ }
755
+ return {
756
+ ok: false,
757
+ error: {
758
+ code: "WORKSPACE_NOT_FOUND",
759
+ message: `Instance '${instanceName}' not found`,
760
+ suggestion: "Use `agent-env list` to see available instances."
761
+ }
762
+ };
763
+ }
764
+ async function getPurpose(instanceName, deps) {
765
+ const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
766
+ if (!lookup.found) {
767
+ return mapLookupError(lookup, instanceName);
768
+ }
769
+ const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
770
+ const state = await readState(wsPath, deps.stateFsDeps);
771
+ return { ok: true, purpose: state.purpose };
772
+ }
773
+ async function setPurpose(instanceName, value, deps) {
774
+ const lengthError = validatePurposeLength(value);
775
+ if (lengthError) return lengthError;
776
+ const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
777
+ if (!lookup.found) {
778
+ return mapLookupError(lookup, instanceName);
779
+ }
780
+ const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
781
+ const state = await readState(wsPath, deps.stateFsDeps);
782
+ const cleared = value === "";
783
+ const updatedState = {
784
+ ...state,
785
+ purpose: cleared ? null : value
786
+ };
787
+ await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
788
+ return { ok: true, cleared };
789
+ }
790
+ function createContainerPurposeDefaultDeps() {
791
+ return {
792
+ stateFsDeps: { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
793
+ containerEnvDeps: { getEnv: (key) => process.env[key] },
794
+ statePath: CONTAINER_STATE_PATH,
795
+ agentEnvDir: CONTAINER_AGENT_ENV_DIR
796
+ };
797
+ }
798
+ async function readContainerState(deps) {
799
+ try {
800
+ const content = await deps.stateFsDeps.readFile(deps.statePath, "utf-8");
801
+ const parsed = JSON.parse(content);
802
+ if (!isValidState(parsed)) {
803
+ return {
804
+ ok: false,
805
+ error: {
806
+ code: "STATE_CORRUPT",
807
+ message: `State file at ${deps.statePath} contains invalid or incomplete state data`
808
+ }
809
+ };
810
+ }
811
+ return { ok: true, state: parsed };
812
+ } catch (err) {
813
+ if (err.code === "ENOENT") {
814
+ return {
815
+ ok: false,
816
+ error: {
817
+ code: "STATE_NOT_FOUND",
818
+ message: `State file not found at ${deps.statePath}`,
819
+ suggestion: "This container may not have been created by agent-env."
820
+ }
821
+ };
822
+ }
823
+ if (err instanceof SyntaxError) {
824
+ return {
825
+ ok: false,
826
+ error: {
827
+ code: "STATE_CORRUPT",
828
+ message: `State file at ${deps.statePath} contains invalid JSON`
829
+ }
830
+ };
831
+ }
832
+ throw err;
833
+ }
834
+ }
835
+ async function getContainerPurpose(deps) {
836
+ const read = await readContainerState(deps);
837
+ if (!read.ok) return read;
838
+ return { ok: true, purpose: read.state.purpose ?? null };
839
+ }
840
+ async function setContainerPurpose(value, deps) {
841
+ const lengthError = validatePurposeLength(value);
842
+ if (lengthError) return lengthError;
843
+ const read = await readContainerState(deps);
844
+ if (!read.ok) return read;
845
+ const cleared = value === "";
846
+ const updatedState = {
847
+ ...read.state,
848
+ purpose: cleared ? null : value
849
+ };
850
+ const wsPath = {
851
+ root: deps.agentEnvDir,
852
+ name: read.state.name,
853
+ agentEnvDir: deps.agentEnvDir,
854
+ stateFile: deps.statePath
855
+ };
856
+ await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
857
+ return { ok: true, cleared };
858
+ }
859
+
695
860
  // src/lib/create-instance.ts
696
861
  var GIT_CLONE_TIMEOUT = 12e4;
697
862
  function extractRepoName(url) {
@@ -761,9 +926,9 @@ function createDefaultDeps() {
761
926
  return {
762
927
  executor,
763
928
  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 },
929
+ workspaceFsDeps: { mkdir: mkdir5, readdir: readdir4, stat: stat4, homedir: homedir3 },
930
+ stateFsDeps: { readFile: readFile4, writeFile: writeFile4, rename: rename3, mkdir: mkdir5, appendFile: appendFile3 },
931
+ devcontainerFsDeps: { cp: cp2, mkdir: mkdir5, readFile: readFile4, stat: stat4, writeFile: writeFile4 },
767
932
  rm: rm2,
768
933
  logger: {
769
934
  warn: (msg) => console.warn(msg),
@@ -771,7 +936,59 @@ function createDefaultDeps() {
771
936
  }
772
937
  };
773
938
  }
774
- async function createInstance(instanceName, repoUrl, deps) {
939
+ async function setupDevcontainerConfig(wsPath, containerName, repoName, purposeText, deps) {
940
+ const hasConfig = await hasDevcontainerConfig(wsPath.root, deps.devcontainerFsDeps);
941
+ if (hasConfig) {
942
+ return { ok: true, configSource: "repo" };
943
+ }
944
+ try {
945
+ await copyBaselineConfig(wsPath.root, deps.devcontainerFsDeps);
946
+ } catch (err) {
947
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
948
+ return {
949
+ ok: false,
950
+ error: {
951
+ code: "CONTAINER_ERROR",
952
+ message: `Failed to copy baseline devcontainer config: ${err instanceof Error ? err.message : String(err)}`
953
+ }
954
+ };
955
+ }
956
+ try {
957
+ await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps, AGENT_ENV_DIR);
958
+ await patchContainerEnv(
959
+ wsPath.root,
960
+ {
961
+ AGENT_ENV_INSTANCE: wsPath.name,
962
+ AGENT_ENV_REPO: repoName,
963
+ AGENT_ENV_PURPOSE: purposeText
964
+ },
965
+ deps.devcontainerFsDeps,
966
+ AGENT_ENV_DIR
967
+ );
968
+ } catch (err) {
969
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
970
+ return {
971
+ ok: false,
972
+ error: {
973
+ code: "CONTAINER_ERROR",
974
+ message: `Failed to patch baseline devcontainer.json: ${err instanceof Error ? err.message : String(err)}`
975
+ }
976
+ };
977
+ }
978
+ return { ok: true, configSource: "baseline" };
979
+ }
980
+ async function createInstance(instanceName, repoUrl, deps, options) {
981
+ const purposeText = options?.purpose ?? "";
982
+ const purposeState = options?.purpose ?? null;
983
+ if (purposeText.length > MAX_PURPOSE_LENGTH) {
984
+ return {
985
+ ok: false,
986
+ error: {
987
+ code: "PURPOSE_TOO_LONG",
988
+ message: `Purpose must be ${MAX_PURPOSE_LENGTH} characters or fewer (got ${purposeText.length})`
989
+ }
990
+ };
991
+ }
775
992
  let repoName;
776
993
  try {
777
994
  repoName = extractRepoName(repoUrl);
@@ -837,36 +1054,17 @@ async function createInstance(instanceName, repoUrl, deps) {
837
1054
  }
838
1055
  };
839
1056
  }
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
- };
866
- }
867
- } else {
868
- configSource = "repo";
1057
+ const configResult = await setupDevcontainerConfig(
1058
+ wsPath,
1059
+ containerName,
1060
+ repoName,
1061
+ purposeText,
1062
+ deps
1063
+ );
1064
+ if (!configResult.ok) {
1065
+ return configResult;
869
1066
  }
1067
+ const { configSource } = configResult;
870
1068
  const existingContainer = await deps.container.findContainerByWorkspaceLabel(wsPath.root);
871
1069
  if (existingContainer) {
872
1070
  await safeRollback(wsPath.root, deps.rm, deps.logger);
@@ -881,7 +1079,10 @@ async function createInstance(instanceName, repoUrl, deps) {
881
1079
  }
882
1080
  const baselineConfigPath = configSource === "baseline" ? join4(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
883
1081
  const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
884
- remoteEnv: { AGENT_INSTANCE: wsPath.name },
1082
+ remoteEnv: {
1083
+ AGENT_INSTANCE: wsPath.name,
1084
+ AGENT_ENV_PURPOSE: purposeText
1085
+ },
885
1086
  configPath: baselineConfigPath
886
1087
  });
887
1088
  if (!containerResult.ok) {
@@ -900,7 +1101,8 @@ async function createInstance(instanceName, repoUrl, deps) {
900
1101
  }
901
1102
  const state = createInitialState(wsPath.name, repoUrl, {
902
1103
  containerName: actualContainerName,
903
- configSource
1104
+ configSource,
1105
+ purpose: purposeState
904
1106
  });
905
1107
  await writeStateAtomic(wsPath, state, deps.stateFsDeps);
906
1108
  await ensureGitExclude(wsPath.root, deps.stateFsDeps);
@@ -976,8 +1178,8 @@ function createAttachDefaultDeps() {
976
1178
  return {
977
1179
  executor,
978
1180
  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 }
1181
+ workspaceFsDeps: { mkdir: mkdir6, readdir: readdir5, stat: stat5, homedir: homedir4 },
1182
+ stateFsDeps: { readFile: readFile5, writeFile: writeFile5, rename: rename4, mkdir: mkdir6, appendFile: appendFile4 }
981
1183
  };
982
1184
  }
983
1185
  async function findWorkspaceByName(instanceName, deps) {
@@ -1272,7 +1474,7 @@ ${getInstallInstructions()}`).argument("<shell>", "Shell type (bash or zsh)").ac
1272
1474
 
1273
1475
  // src/commands/create.ts
1274
1476
  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) => {
1477
+ 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("--purpose <text>", "Set the instance purpose/label at creation time").option("--attach", "Attach immediately after creation").action(async (name, options) => {
1276
1478
  if (!options.repo) {
1277
1479
  console.error(
1278
1480
  formatError(
@@ -1294,7 +1496,7 @@ var createCommand = new Command3("create").description("Create a new isolated de
1294
1496
  }
1295
1497
  const repoUrl = resolved.url;
1296
1498
  console.log(`Creating instance '${name}' from ${repoUrl}...`);
1297
- const result = await createInstance(name, repoUrl, deps);
1499
+ const result = await createInstance(name, repoUrl, deps, { purpose: options.purpose });
1298
1500
  if (!result.ok) {
1299
1501
  const { code, message, suggestion } = result.error;
1300
1502
  console.error(formatError(createError(code, message, suggestion)));
@@ -1616,11 +1818,13 @@ async function listInstances(deps) {
1616
1818
  }
1617
1819
  let sshConnection = null;
1618
1820
  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})`;
1821
+ if ("22/tcp" in containerResult.ports) {
1822
+ const orbDomains = containerResult.labels["dev.orbstack.domains"];
1823
+ const hostname = orbDomains?.split(",")[0]?.trim() || `${state.containerName}.orb.local`;
1824
+ sshConnection = `node@${hostname}`;
1825
+ const hostPort = containerResult.ports["22/tcp"];
1826
+ if (hostPort && hostPort !== "22") {
1827
+ sshConnection += ` (localhost:${hostPort})`;
1624
1828
  }
1625
1829
  }
1626
1830
  }
@@ -1696,90 +1900,77 @@ var listCommand = new Command4("list").alias("ps").description("List all instanc
1696
1900
 
1697
1901
  // src/commands/purpose.ts
1698
1902
  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."
1903
+ var defaultPurposeCommandDeps = {
1904
+ isInsideContainer
1905
+ };
1906
+ function createPurposeCommand(deps = defaultPurposeCommandDeps) {
1907
+ return new Command5("purpose").description(
1908
+ "Get or set the purpose/label for an instance. Inside a container: no instance name needed (agent-env purpose [value])"
1909
+ ).argument("[nameOrValue]", "Instance name (host) or purpose value (container)").argument("[value]", "New purpose value (omit to get current, empty string to clear)").action(async (nameOrValue, value) => {
1910
+ if (deps.isInsideContainer()) {
1911
+ await handleContainerMode(nameOrValue);
1912
+ } else {
1913
+ await handleHostMode(nameOrValue, value);
1726
1914
  }
1727
- };
1915
+ });
1728
1916
  }
1729
- async function getPurpose(instanceName, deps) {
1730
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1731
- if (!lookup.found) {
1732
- return mapLookupError(lookup, instanceName);
1917
+ var purposeCommand = createPurposeCommand();
1918
+ async function handleContainerMode(purposeValue) {
1919
+ const deps = createContainerPurposeDefaultDeps();
1920
+ if (purposeValue === void 0) {
1921
+ const result = await getContainerPurpose(deps);
1922
+ handleGetResult(result);
1923
+ } else {
1924
+ const result = await setContainerPurpose(purposeValue, deps);
1925
+ handleSetResult(result);
1733
1926
  }
1734
- const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1735
- const state = await readState(wsPath, deps.stateFsDeps);
1736
- return { ok: true, purpose: state.purpose };
1737
1927
  }
1738
- async function setPurpose(instanceName, value, deps) {
1739
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1740
- if (!lookup.found) {
1741
- return mapLookupError(lookup, instanceName);
1928
+ async function handleHostMode(name, value) {
1929
+ if (!name) {
1930
+ console.error(
1931
+ formatError(
1932
+ createError(
1933
+ "MISSING_ARGUMENT",
1934
+ "Instance name is required when running on the host",
1935
+ "Usage: agent-env purpose <name> [value]"
1936
+ )
1937
+ )
1938
+ );
1939
+ process.exit(1);
1742
1940
  }
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) => {
1756
1941
  const deps = createPurposeDefaultDeps();
1757
1942
  if (value === void 0) {
1758
1943
  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
- }
1944
+ handleGetResult(result);
1769
1945
  } else {
1770
1946
  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
- }
1947
+ handleSetResult(result);
1781
1948
  }
1782
- });
1949
+ }
1950
+ function handleGetResult(result) {
1951
+ if (!result.ok) {
1952
+ const { code, message, suggestion } = result.error;
1953
+ console.error(formatError(createError(code, message, suggestion)));
1954
+ process.exit(1);
1955
+ }
1956
+ if (result.purpose === null) {
1957
+ console.log("(no purpose set)");
1958
+ } else {
1959
+ console.log(result.purpose);
1960
+ }
1961
+ }
1962
+ function handleSetResult(result) {
1963
+ if (!result.ok) {
1964
+ const { code, message, suggestion } = result.error;
1965
+ console.error(formatError(createError(code, message, suggestion)));
1966
+ process.exit(1);
1967
+ }
1968
+ if (result.cleared) {
1969
+ console.log("Purpose cleared");
1970
+ } else {
1971
+ console.log("Purpose updated");
1972
+ }
1973
+ }
1783
1974
 
1784
1975
  // src/commands/rebuild.ts
1785
1976
  import chalk from "chalk";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zookanalytics/agent-env",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "CLI for creating isolated, AI-ready development environments",
5
5
  "type": "module",
6
6
  "bin": {