Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

workspaceBasenameLookup.ts

237 lines8.9 KB

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