|
| 1 | +import Foundation |
| 2 | + |
| 3 | +public extension CodexThread { |
| 4 | + /// Request used to list one directory under this thread's workspace root. |
| 5 | + struct WorkspaceFileListRequest: Sendable, Equatable { |
| 6 | + public var includeHidden: Bool |
| 7 | + public var path: String? |
| 8 | + |
| 9 | + /// Creates a workspace file-list request. |
| 10 | + /// |
| 11 | + /// Nil or empty `path` lists the workspace root. Relative paths are |
| 12 | + /// resolved under ``CodexThread/currentDirectoryPath``. Absolute paths |
| 13 | + /// are accepted only when they stay inside the same resolved workspace. |
| 14 | + public init(path: String? = nil, includeHidden: Bool = false) { |
| 15 | + self.includeHidden = includeHidden |
| 16 | + self.path = path |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + /// Request used to read one UTF-8 text file under this thread's workspace root. |
| 21 | + struct WorkspaceFileReadRequest: Sendable, Equatable { |
| 22 | + public var maximumBytes: Int |
| 23 | + public var path: String |
| 24 | + |
| 25 | + /// Creates a workspace file-read request. |
| 26 | + /// |
| 27 | + /// `maximumBytes` is normalized to at least 1 byte. SwiftASB rejects |
| 28 | + /// larger files instead of truncating them so callers do not render |
| 29 | + /// incomplete source text as if it were complete. |
| 30 | + public init(path: String, maximumBytes: Int = 1_048_576) { |
| 31 | + self.maximumBytes = max(1, maximumBytes) |
| 32 | + self.path = path |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + /// Directory listing rooted in this thread's workspace. |
| 37 | + struct WorkspaceFileList: Sendable, Equatable { |
| 38 | + public let directoryRelativePath: String |
| 39 | + public let entries: [WorkspaceFileEntry] |
| 40 | + public let workspacePath: String |
| 41 | + } |
| 42 | + |
| 43 | + /// One visible filesystem entry under this thread's workspace. |
| 44 | + struct WorkspaceFileEntry: Sendable, Equatable, Identifiable { |
| 45 | + /// Basic filesystem kind for a listed workspace entry. |
| 46 | + public enum Kind: String, Sendable, Equatable { |
| 47 | + case directory |
| 48 | + case file |
| 49 | + case other |
| 50 | + case symbolicLink |
| 51 | + } |
| 52 | + |
| 53 | + public var id: String { relativePath } |
| 54 | + |
| 55 | + public let byteCount: Int64? |
| 56 | + public let isHidden: Bool |
| 57 | + public let kind: Kind |
| 58 | + public let modifiedAt: Date? |
| 59 | + public let name: String |
| 60 | + public let relativePath: String |
| 61 | + } |
| 62 | + |
| 63 | + /// UTF-8 text contents read from a file under this thread's workspace. |
| 64 | + struct WorkspaceFileContents: Sendable, Equatable { |
| 65 | + public let byteCount: Int |
| 66 | + public let contents: String |
| 67 | + public let relativePath: String |
| 68 | + public let workspacePath: String |
| 69 | + } |
| 70 | + |
| 71 | + /// Error raised while resolving, listing, or reading workspace files. |
| 72 | + enum WorkspaceFileError: Error, Sendable, LocalizedError, Equatable { |
| 73 | + case fileSystemFailure(operation: String, path: String, reason: String) |
| 74 | + case fileTooLarge(path: String, byteCount: Int64, maximumBytes: Int) |
| 75 | + case missingPath(path: String) |
| 76 | + case missingWorkspaceRoot(path: String) |
| 77 | + case notDirectory(path: String) |
| 78 | + case notFile(path: String) |
| 79 | + case outsideWorkspace(path: String, workspacePath: String) |
| 80 | + case unsupportedTextEncoding(path: String) |
| 81 | + |
| 82 | + public var errorDescription: String? { |
| 83 | + switch self { |
| 84 | + case let .fileSystemFailure(operation, path, reason): |
| 85 | + return "Workspace file \(operation) failed for \(path): \(reason)" |
| 86 | + case let .fileTooLarge(path, byteCount, maximumBytes): |
| 87 | + return "Workspace file read rejected \(path) because it is \(byteCount) bytes, which exceeds the configured \(maximumBytes)-byte limit." |
| 88 | + case let .missingPath(path): |
| 89 | + return "Workspace file path does not exist: \(path)." |
| 90 | + case let .missingWorkspaceRoot(path): |
| 91 | + return "Workspace root does not exist or is not a directory: \(path)." |
| 92 | + case let .notDirectory(path): |
| 93 | + return "Workspace file listing requires a directory, but \(path) is not a directory." |
| 94 | + case let .notFile(path): |
| 95 | + return "Workspace file read requires a regular file, but \(path) is not a file." |
| 96 | + case let .outsideWorkspace(path, workspacePath): |
| 97 | + return "Workspace file path \(path) resolves outside the thread workspace root \(workspacePath)." |
| 98 | + case let .unsupportedTextEncoding(path): |
| 99 | + return "Workspace file read supports UTF-8 text files, but \(path) could not be decoded as UTF-8." |
| 100 | + } |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + /// Lists one workspace directory without asking the app-server to run a command. |
| 105 | + func listWorkspaceFiles(_ request: WorkspaceFileListRequest = .init()) throws -> WorkspaceFileList { |
| 106 | + let root = try resolvedWorkspaceRoot() |
| 107 | + let directory = try resolveWorkspacePath(request.path, root: root) |
| 108 | + |
| 109 | + guard FileManager.default.fileExists(atPath: directory.url.path) else { |
| 110 | + throw WorkspaceFileError.missingPath(path: directory.url.path) |
| 111 | + } |
| 112 | + |
| 113 | + var isDirectory: ObjCBool = false |
| 114 | + guard FileManager.default.fileExists(atPath: directory.url.path, isDirectory: &isDirectory), isDirectory.boolValue else { |
| 115 | + throw WorkspaceFileError.notDirectory(path: directory.url.path) |
| 116 | + } |
| 117 | + |
| 118 | + let properties: Set<URLResourceKey> = [ |
| 119 | + .contentModificationDateKey, |
| 120 | + .fileSizeKey, |
| 121 | + .isDirectoryKey, |
| 122 | + .isRegularFileKey, |
| 123 | + .isSymbolicLinkKey, |
| 124 | + ] |
| 125 | + let options: FileManager.DirectoryEnumerationOptions = request.includeHidden ? [] : [.skipsHiddenFiles] |
| 126 | + let urls: [URL] |
| 127 | + do { |
| 128 | + urls = try FileManager.default.contentsOfDirectory( |
| 129 | + at: directory.url, |
| 130 | + includingPropertiesForKeys: Array(properties), |
| 131 | + options: options |
| 132 | + ) |
| 133 | + } catch { |
| 134 | + throw WorkspaceFileError.fileSystemFailure( |
| 135 | + operation: "listing", |
| 136 | + path: directory.url.path, |
| 137 | + reason: error.localizedDescription |
| 138 | + ) |
| 139 | + } |
| 140 | + |
| 141 | + let entries: [WorkspaceFileEntry] |
| 142 | + do { |
| 143 | + entries = try urls.map { url in |
| 144 | + try WorkspaceFileEntry(url: url, root: root) |
| 145 | + } |
| 146 | + .sorted() |
| 147 | + } catch let workspaceError as WorkspaceFileError { |
| 148 | + throw workspaceError |
| 149 | + } catch { |
| 150 | + throw WorkspaceFileError.fileSystemFailure( |
| 151 | + operation: "reading listed entry metadata", |
| 152 | + path: directory.url.path, |
| 153 | + reason: error.localizedDescription |
| 154 | + ) |
| 155 | + } |
| 156 | + |
| 157 | + return .init( |
| 158 | + directoryRelativePath: directory.relativePath, |
| 159 | + entries: entries, |
| 160 | + workspacePath: root.url.path |
| 161 | + ) |
| 162 | + } |
| 163 | + |
| 164 | + /// Reads one UTF-8 workspace file without asking the app-server to run a command. |
| 165 | + func readWorkspaceFile(_ request: WorkspaceFileReadRequest) throws -> WorkspaceFileContents { |
| 166 | + let root = try resolvedWorkspaceRoot() |
| 167 | + let file = try resolveWorkspacePath(request.path, root: root) |
| 168 | + |
| 169 | + guard FileManager.default.fileExists(atPath: file.url.path) else { |
| 170 | + throw WorkspaceFileError.missingPath(path: file.url.path) |
| 171 | + } |
| 172 | + |
| 173 | + let values: URLResourceValues |
| 174 | + do { |
| 175 | + values = try file.url.resourceValues(forKeys: [.fileSizeKey, .isRegularFileKey]) |
| 176 | + } catch { |
| 177 | + throw WorkspaceFileError.fileSystemFailure( |
| 178 | + operation: "reading metadata", |
| 179 | + path: file.url.path, |
| 180 | + reason: error.localizedDescription |
| 181 | + ) |
| 182 | + } |
| 183 | + guard values.isRegularFile == true else { |
| 184 | + throw WorkspaceFileError.notFile(path: file.url.path) |
| 185 | + } |
| 186 | + |
| 187 | + let byteCount = Int64(values.fileSize ?? 0) |
| 188 | + guard byteCount <= Int64(request.maximumBytes) else { |
| 189 | + throw WorkspaceFileError.fileTooLarge( |
| 190 | + path: file.url.path, |
| 191 | + byteCount: byteCount, |
| 192 | + maximumBytes: request.maximumBytes |
| 193 | + ) |
| 194 | + } |
| 195 | + |
| 196 | + let data: Data |
| 197 | + do { |
| 198 | + data = try Data(contentsOf: file.url) |
| 199 | + } catch { |
| 200 | + throw WorkspaceFileError.fileSystemFailure( |
| 201 | + operation: "reading contents", |
| 202 | + path: file.url.path, |
| 203 | + reason: error.localizedDescription |
| 204 | + ) |
| 205 | + } |
| 206 | + guard let contents = String(data: data, encoding: .utf8) else { |
| 207 | + throw WorkspaceFileError.unsupportedTextEncoding(path: file.url.path) |
| 208 | + } |
| 209 | + |
| 210 | + return .init( |
| 211 | + byteCount: data.count, |
| 212 | + contents: contents, |
| 213 | + relativePath: file.relativePath, |
| 214 | + workspacePath: root.url.path |
| 215 | + ) |
| 216 | + } |
| 217 | +} |
| 218 | + |
| 219 | +private struct ResolvedWorkspacePath { |
| 220 | + let relativePath: String |
| 221 | + let url: URL |
| 222 | +} |
| 223 | + |
| 224 | +private extension CodexThread { |
| 225 | + func resolvedWorkspaceRoot() throws -> ResolvedWorkspacePath { |
| 226 | + let rootURL = URL(fileURLWithPath: currentDirectoryPath, isDirectory: true) |
| 227 | + .standardizedFileURL |
| 228 | + .resolvingSymlinksInPath() |
| 229 | + |
| 230 | + var isDirectory: ObjCBool = false |
| 231 | + guard FileManager.default.fileExists(atPath: rootURL.path, isDirectory: &isDirectory), isDirectory.boolValue else { |
| 232 | + throw WorkspaceFileError.missingWorkspaceRoot(path: currentDirectoryPath) |
| 233 | + } |
| 234 | + |
| 235 | + return .init(relativePath: ".", url: rootURL) |
| 236 | + } |
| 237 | + |
| 238 | + func resolveWorkspacePath(_ path: String?, root: ResolvedWorkspacePath) throws -> ResolvedWorkspacePath { |
| 239 | + let requestedPath = normalizedRequestedPath(path) |
| 240 | + let rawURL: URL |
| 241 | + if requestedPath.hasPrefix("/") { |
| 242 | + rawURL = URL(fileURLWithPath: requestedPath) |
| 243 | + } else { |
| 244 | + rawURL = root.url.appendingPathComponent(requestedPath) |
| 245 | + } |
| 246 | + |
| 247 | + let resolvedURL = rawURL |
| 248 | + .standardizedFileURL |
| 249 | + .resolvingSymlinksInPath() |
| 250 | + guard resolvedURL.isContained(in: root.url) else { |
| 251 | + throw WorkspaceFileError.outsideWorkspace( |
| 252 | + path: rawURL.standardizedFileURL.path, |
| 253 | + workspacePath: root.url.path |
| 254 | + ) |
| 255 | + } |
| 256 | + |
| 257 | + return .init( |
| 258 | + relativePath: resolvedURL.workspaceRelativePath(from: root.url), |
| 259 | + url: resolvedURL |
| 260 | + ) |
| 261 | + } |
| 262 | + |
| 263 | + func normalizedRequestedPath(_ path: String?) -> String { |
| 264 | + guard let path else { return "." } |
| 265 | + let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) |
| 266 | + return trimmed.isEmpty ? "." : trimmed |
| 267 | + } |
| 268 | +} |
| 269 | + |
| 270 | +private extension CodexThread.WorkspaceFileEntry { |
| 271 | + init(url: URL, root: ResolvedWorkspacePath) throws { |
| 272 | + let values = try url.resourceValues(forKeys: [ |
| 273 | + .contentModificationDateKey, |
| 274 | + .fileSizeKey, |
| 275 | + .isDirectoryKey, |
| 276 | + .isRegularFileKey, |
| 277 | + .isSymbolicLinkKey, |
| 278 | + ]) |
| 279 | + let kind: Kind |
| 280 | + if values.isSymbolicLink == true { |
| 281 | + kind = .symbolicLink |
| 282 | + } else if values.isDirectory == true { |
| 283 | + kind = .directory |
| 284 | + } else if values.isRegularFile == true { |
| 285 | + kind = .file |
| 286 | + } else { |
| 287 | + kind = .other |
| 288 | + } |
| 289 | + |
| 290 | + self.init( |
| 291 | + byteCount: kind == .file ? Int64(values.fileSize ?? 0) : nil, |
| 292 | + isHidden: url.lastPathComponent.hasPrefix("."), |
| 293 | + kind: kind, |
| 294 | + modifiedAt: values.contentModificationDate, |
| 295 | + name: url.lastPathComponent, |
| 296 | + relativePath: url.standardizedFileURL.workspaceRelativePath(from: root.url) |
| 297 | + ) |
| 298 | + } |
| 299 | +} |
| 300 | + |
| 301 | +private extension Array where Element == CodexThread.WorkspaceFileEntry { |
| 302 | + func sorted() -> Self { |
| 303 | + sorted { lhs, rhs in |
| 304 | + if lhs.kind == .directory, rhs.kind != .directory { |
| 305 | + return true |
| 306 | + } |
| 307 | + if lhs.kind != .directory, rhs.kind == .directory { |
| 308 | + return false |
| 309 | + } |
| 310 | + return lhs.name.localizedStandardCompare(rhs.name) == .orderedAscending |
| 311 | + } |
| 312 | + } |
| 313 | +} |
| 314 | + |
| 315 | +private extension URL { |
| 316 | + func isContained(in root: URL) -> Bool { |
| 317 | + let path = path |
| 318 | + let rootPath = root.path |
| 319 | + return path == rootPath || path.hasPrefix(rootPath + "/") |
| 320 | + } |
| 321 | + |
| 322 | + func workspaceRelativePath(from root: URL) -> String { |
| 323 | + let path = path |
| 324 | + let rootPath = root.path |
| 325 | + guard path != rootPath else { return "." } |
| 326 | + return String(path.dropFirst(rootPath.count + 1)) |
| 327 | + } |
| 328 | +} |
0 commit comments