/ utils / cwd.ts
cwd.ts
 1  import { AsyncLocalStorage } from 'async_hooks'
 2  import { getCwdState, getOriginalCwd } from '../bootstrap/state.js'
 3  
 4  const cwdOverrideStorage = new AsyncLocalStorage<string>()
 5  
 6  /**
 7   * Run a function with an overridden working directory for the current async context.
 8   * All calls to pwd()/getCwd() within the function (and its async descendants) will
 9   * return the overridden cwd instead of the global one. This enables concurrent
10   * agents to each see their own working directory without affecting each other.
11   */
12  export function runWithCwdOverride<T>(cwd: string, fn: () => T): T {
13    return cwdOverrideStorage.run(cwd, fn)
14  }
15  
16  /**
17   * Get the current working directory
18   */
19  export function pwd(): string {
20    return cwdOverrideStorage.getStore() ?? getCwdState()
21  }
22  
23  /**
24   * Get the current working directory or the original working directory if the current one is not available
25   */
26  export function getCwd(): string {
27    try {
28      return pwd()
29    } catch {
30      return getOriginalCwd()
31    }
32  }