The best way to control Claude Code, Codex and more from any computer or phone

main
ts 265 lines 10.1 KB
Raw
1 import { FILESYSTEM_METADATA_BATCH_LIMIT } from "@t3tools/contracts";
2 import {
3 isAbsolutePath,
4 isWindowsAbsolutePath,
5 resolveWorkspaceFilePath,
6 } from "@t3tools/shared/path";
7
8 export const WORKSPACE_BASENAME_LOOKUP_LIMIT = 25;
9
10 export interface WorkspaceEntryCandidate {
11 readonly path: string;
12 readonly kind: "file" | "directory";
13 }
14
15 function basenameOfPath(path: string): string {
16 const separatorIndex = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
17 return separatorIndex >= 0 ? path.slice(separatorIndex + 1) : path;
18 }
19
20 export function needsWorkspaceBasenameLookup(relativePath: string): boolean {
21 const trimmed = relativePath.trim();
22 return (
23 trimmed !== "." &&
24 trimmed !== ".." &&
25 trimmed.length > 0 &&
26 !trimmed.includes("/") &&
27 !trimmed.includes("\\")
28 );
29 }
30
31 export function pickWorkspaceBasenameMatch(
32 basename: string,
33 entries: ReadonlyArray<WorkspaceEntryCandidate>,
34 ): string | null {
35 const target = basename.trim();
36 if (!target) return null;
37 const files = entries.filter((entry) => entry.kind === "file");
38 const exact = files.find((entry) => basenameOfPath(entry.path) === target);
39 if (exact) return exact.path;
40 const folded = target.toLowerCase();
41 const foldedMatches = files.filter(
42 (entry) => basenameOfPath(entry.path).toLowerCase() === folded,
43 );
44 return foldedMatches.length === 1 ? (foldedMatches[0]?.path ?? null) : null;
45 }
46
47 // Repository-relative paths can repeat the project's suffix in subfolder projects.
48 function stripRepeatedWorkspacePrefix(relativePath: string, cwd: string): string | null {
49 if (isAbsolutePath(relativePath)) return null;
50 const pathSegments = relativePath.split(/[\\/]+/);
51 const cwdSegments = cwd.split(/[\\/]+/).filter(Boolean);
52 const fold = isWindowsAbsolutePath(cwd)
53 ? (segment: string | undefined) => segment?.toLowerCase()
54 : (segment: string | undefined) => segment;
55 for (let count = Math.min(cwdSegments.length, pathSegments.length - 1); count > 0; count--) {
56 const prefix = cwdSegments.slice(-count);
57 if (prefix.every((segment, index) => fold(segment) === fold(pathSegments[index]))) {
58 return pathSegments.slice(count).join("/") || null;
59 }
60 }
61 return null;
62 }
63
64 /**
65 * The project search query that may find a chat file link's real file, or null when the link
66 * names its file exactly. Agents often cite paths relative to a package (`cloud/http.ts`).
67 */
68 export function workspaceLinkLookupQuery(relativePath: string, cwd: string): string | null {
69 const trimmed = relativePath.trim();
70 if (isAbsolutePath(trimmed) || /^(?:\.{1,2}|~)[\\/]/.test(trimmed) || /[\\/]$/.test(trimmed)) {
71 return null;
72 }
73 if (needsWorkspaceBasenameLookup(trimmed)) return trimmed;
74 return stripRepeatedWorkspacePrefix(trimmed, cwd) ?? trimmed;
75 }
76
77 /** The one file a chat link names: its basename, its path past a repeated prefix, or its suffix. */
78 export function pickWorkspaceLinkMatch(
79 relativePath: string,
80 cwd: string,
81 entries: ReadonlyArray<WorkspaceEntryCandidate>,
82 ): string | null {
83 const trimmed = relativePath.trim();
84 if (needsWorkspaceBasenameLookup(trimmed)) return pickWorkspaceBasenameMatch(trimmed, entries);
85 const matches = workspaceQualifiedPathMatches(trimmed, cwd, entries);
86 return matches.length === 1 ? (matches[0] ?? null) : null;
87 }
88
89 function workspaceQualifiedPathMatches(
90 relativePath: string,
91 cwd: string,
92 entries: ReadonlyArray<WorkspaceEntryCandidate>,
93 ): ReadonlyArray<string> {
94 const stripped = stripRepeatedWorkspacePrefix(relativePath, cwd);
95 const strippedMatch =
96 stripped === null ? null : pickStrippedWorkspaceMatch(stripped, cwd, entries);
97 if (strippedMatch !== null) return [strippedMatch];
98 const suffix = relativePath.replaceAll("\\", "/");
99 return entries.flatMap((entry) => {
100 if (entry.kind !== "file") return [];
101 const path = entry.path.replaceAll("\\", "/");
102 return path === suffix || path.endsWith(`/${suffix}`) ? [entry.path] : [];
103 });
104 }
105
106 function pickStrippedWorkspaceMatch(
107 strippedPath: string,
108 cwd: string,
109 entries: ReadonlyArray<WorkspaceEntryCandidate>,
110 ): string | null {
111 const caseInsensitive = isWindowsAbsolutePath(cwd);
112 const key = (path: string) => {
113 const normalized = path.replaceAll("\\", "/");
114 return caseInsensitive ? normalized.toLowerCase() : normalized;
115 };
116 const files = entries.filter((entry) => entry.kind === "file");
117 return files.find((entry) => key(entry.path) === key(strippedPath))?.path ?? null;
118 }
119
120 /**
121 * The absolute path of the one file a chat link names across other project roots, or null when
122 * no root has it or roots name different files. Agents cite paths relative to their repo.
123 * Nested project roots list the same file more than once, which still names one file.
124 */
125 export function pickProjectLinkMatch(
126 relativePath: string,
127 searches: ReadonlyArray<{
128 readonly root: string;
129 readonly entries: ReadonlyArray<WorkspaceEntryCandidate>;
130 }>,
131 ): string | null {
132 const target = relativePath.trim();
133 const isBasename = needsWorkspaceBasenameLookup(target);
134 const matches = new Map<string, string>();
135 let rootHits = 0;
136 const addMatch = (path: string) => {
137 // Windows paths that differ only by case stay distinct: a directory can be case-sensitive.
138 const key = isWindowsAbsolutePath(path) ? path.replaceAll("/", "\\") : path;
139 if (!matches.has(key)) matches.set(key, path);
140 };
141 for (const { root, entries } of searches) {
142 if (isBasename) {
143 const match = pickWorkspaceBasenameMatch(target, entries);
144 if (match === null) continue;
145 rootHits += 1;
146 addMatch(resolveWorkspaceFilePath(match, root));
147 } else {
148 for (const match of workspaceQualifiedPathMatches(target, root, entries)) {
149 addMatch(resolveWorkspaceFilePath(match, root));
150 }
151 }
152 }
153 if (isBasename && rootHits > 1) {
154 // A root's pick, or a root left ambiguous by case, can hide another file elsewhere.
155 const folded = target.toLowerCase();
156 for (const { root, entries } of searches) {
157 for (const entry of entries) {
158 if (entry.kind === "file" && basenameOfPath(entry.path).toLowerCase() === folded) {
159 addMatch(resolveWorkspaceFilePath(entry.path, root));
160 }
161 }
162 }
163 }
164 return matches.size === 1 ? ([...matches.values()][0] ?? null) : null;
165 }
166
167 const AGENT_DIRECTORY_SEARCH_LIMIT = 4;
168
169 /**
170 * The file a bare name cites in the latest folder the agent worked in that has one of that name.
171 * Folders are searched one at a time: the latest usually has it, and each search walks a tree.
172 */
173 export async function findAgentDirectoryMatch(
174 relativePath: string,
175 directories: ReadonlyArray<string>,
176 searchRoot: (root: string) => Promise<{
177 readonly root: string;
178 readonly entries: ReadonlyArray<WorkspaceEntryCandidate>;
179 }>,
180 ): Promise<string | null> {
181 for (const directory of directories.slice(0, AGENT_DIRECTORY_SEARCH_LIMIT)) {
182 const { root, entries } = await searchRoot(directory);
183 const match = pickWorkspaceLinkMatch(relativePath, root, entries);
184 if (match !== null) return resolveWorkspaceFilePath(match, root);
185 }
186 return null;
187 }
188
189 // A quoted string or a comment is one token, so `cd` inside either is not read as a command.
190 const SHELL_TOKEN = /(?<![^\s;&|()])#[^\n]*|"[^"]*"|'[^']*'|[;&|()\n]|[ \t]+|[^\s;&|()"']+/g;
191 const SHELL_NAME = /(?:^|\/)(?:ba|z|da)?sh$/;
192 const CD_OPTION = /^-[LPe@]*$|^--$/;
193
194 /** The operands of the `cd` commands in `script`, in order, through `sh -c "<script>"`. */
195 function cdOperands(script: string): Array<string> {
196 const operands: Array<string> = [];
197 let words: Array<string> = [];
198 let wordOpen = false;
199 const endCommand = () => {
200 const [name = "", ...rest] = words;
201 if (name === "cd") {
202 const operand = rest.find((word) => !CD_OPTION.test(word));
203 if (operand !== undefined) operands.push(operand);
204 } else if (SHELL_NAME.test(name)) {
205 const inner = rest[rest.findIndex((word) => /^-[a-z]*c$/.test(word)) + 1];
206 if (inner !== undefined && /^(["']).*\1$/s.test(inner)) {
207 operands.push(...cdOperands(inner.slice(1, -1)));
208 }
209 }
210 words = [];
211 wordOpen = false;
212 };
213 for (const [token] of script.matchAll(SHELL_TOKEN)) {
214 // A here-document's body is data, and where it ends is the shell's to say.
215 if (!/^["'#]/.test(token) && token.includes("<<")) break;
216 if (/^[;&|()\n]/.test(token)) endCommand();
217 else if (/^[ \t]/.test(token) || (!wordOpen && token.startsWith("#"))) wordOpen = false;
218 else if (wordOpen) words[words.length - 1] += token;
219 else {
220 words.push(token);
221 wordOpen = true;
222 }
223 }
224 endCommand();
225 return operands;
226 }
227
228 function literalDirectory(operand: string): string | null {
229 const path = /^["']/.test(operand) ? operand.slice(1, -1) : operand;
230 // The shell would expand these, and only it knows to what.
231 if (!isAbsolutePath(path) || /[$`*?[\]{}"']/.test(path)) return null;
232 return path.includes("\\") && !isWindowsAbsolutePath(path) ? null : path;
233 }
234
235 interface TimelineItemSource {
236 readonly sourceThreadId: string;
237 readonly sourceItemId: string;
238 }
239
240 /**
241 * The folders the commands above `reply` in a thread's timeline changed into, the latest first.
242 * A reply cites paths relative to where the agent worked, which no project has to be rooted at.
243 * Rows below the reply, a fork's own commands under an inherited one included, came after it.
244 */
245 export function agentWorkingDirectories(
246 items: ReadonlyArray<
247 TimelineItemSource & { readonly item: { readonly type: string; readonly input?: unknown } }
248 >,
249 reply: TimelineItemSource,
250 ): ReadonlyArray<string> {
251 const directories = new Set<string>();
252 const replyIndex = items.findIndex(
253 (row) => row.sourceThreadId === reply.sourceThreadId && row.sourceItemId === reply.sourceItemId,
254 );
255 for (let index = replyIndex - 1; index >= 0; index--) {
256 const item = items[index]?.item;
257 if (item?.type !== "command_execution" || typeof item.input !== "string") continue;
258 for (const operand of cdOperands(item.input).reverse()) {
259 const directory = literalDirectory(operand);
260 if (directory !== null) directories.add(directory);
261 if (directories.size === FILESYSTEM_METADATA_BATCH_LIMIT) return [...directories];
262 }
263 }
264 return [...directories];
265 }