@phren/cli 0.3.23 → 0.3.25

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.
@@ -9,6 +9,18 @@ export declare function resolveCodeStore(base: string, value?: string | null, wr
9
9
  export declare class CodeRoutes {
10
10
  private readonly store;
11
11
  constructor(store: string);
12
+ /** A filename need not resemble a symbol declared inside it. Query the
13
+ * index's files table through @phren/code's existing public read API so
14
+ * installed optional packages need no new export to serve this route. */
15
+ files(projectValue: string | null, nameValue: string | null, limitValue?: string | null): Promise<{
16
+ project: string;
17
+ name: string;
18
+ files: {
19
+ path: string;
20
+ language: string;
21
+ }[];
22
+ truncated: boolean;
23
+ }>;
12
24
  status(projectValue: string | null): Promise<CodeStatus>;
13
25
  search(projectValue: string | null, queryValue: string | null, kindValue: string | null, limitValue: string | null, directoryValue?: string | null): Promise<{
14
26
  project: string;
@@ -69,6 +69,29 @@ export class CodeRoutes {
69
69
  constructor(store) {
70
70
  this.store = store;
71
71
  }
72
+ /** A filename need not resemble a symbol declared inside it. Query the
73
+ * index's files table through @phren/code's existing public read API so
74
+ * installed optional packages need no new export to serve this route. */
75
+ async files(projectValue, nameValue, limitValue) {
76
+ const project = projectSchema.parse(projectValue ?? "");
77
+ const name = relativePathSchema.refine(value => !/[\x00-\x1f\x7f]/.test(value)
78
+ && !value.split("/").includes(".git")).parse(nameValue ?? "");
79
+ const limit = limitValue ? topSchema.parse(limitValue) : 20;
80
+ const code = await requireCodePackage(this.store);
81
+ const database = await code.openCodeDatabase(this.store, project, false);
82
+ if (!database)
83
+ throw noIndex(project);
84
+ try {
85
+ const suffix = "/" + name;
86
+ const rows = code.rowsOf(database.db, `SELECT path, language FROM files WHERE path = ? OR substr(path, -?) = ?
87
+ ORDER BY CASE WHEN path = ? THEN 0 ELSE 1 END, length(path), path LIMIT ?`, [name, [...suffix].length, suffix, name, limit + 1]);
88
+ return { project, name, files: rows.slice(0, limit).map(row => ({ path: code.stringAt(row, 0), language: code.stringAt(row, 1) })),
89
+ truncated: rows.length > limit };
90
+ }
91
+ finally {
92
+ database.close();
93
+ }
94
+ }
72
95
  async status(projectValue) {
73
96
  const project = projectSchema.parse(projectValue ?? "");
74
97
  const result = await (await requireCodePackage(this.store)).codeIndexStatus(this.store, project);
@@ -0,0 +1,10 @@
1
+ /** Resolve a chat reference in a server-selected repository. Cwd-relative
2
+ * names win over root-relative ones. Never turn an outside absolute path
3
+ * into an unrelated in-repository suffix match. Metadata is checked by the
4
+ * same no-symlink reader that will subsequently serve the file's bytes. */
5
+ export declare function resolveFilePath(root: string, cwd: string, requested: string): Promise<{
6
+ path: string;
7
+ size: number;
8
+ contentType: string;
9
+ version: string;
10
+ }>;
@@ -0,0 +1,63 @@
1
+ import { lstat, realpath } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { readFileRange } from "./file-range.js";
4
+ import { BridgeError } from "./protocol.js";
5
+ function beneath(root, file) {
6
+ const relative = path.relative(root, file);
7
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
8
+ }
9
+ /** Resolve a chat reference in a server-selected repository. Cwd-relative
10
+ * names win over root-relative ones. Never turn an outside absolute path
11
+ * into an unrelated in-repository suffix match. Metadata is checked by the
12
+ * same no-symlink reader that will subsequently serve the file's bytes. */
13
+ export async function resolveFilePath(root, cwd, requested) {
14
+ // Native Windows references use backslashes; walk the same components as
15
+ // slash-form chat links. On POSIX a backslash remains an invalid reference.
16
+ if (process.platform === "win32")
17
+ requested = requested.replaceAll("\\", "/");
18
+ if (!requested || requested.length > 4096 || /[\x00-\x1f\x7f\\]/.test(requested)
19
+ || /^[A-Za-z]:[^/]/.test(requested)
20
+ || requested.split("/").includes(".git") || path.win32.isAbsolute(requested) && !path.isAbsolute(requested)) {
21
+ throw new BridgeError(400, "Invalid file path.");
22
+ }
23
+ const base = await realpath(root), folder = await realpath(cwd);
24
+ if (!beneath(base, folder))
25
+ throw new BridgeError(403, "This folder is outside the repository.");
26
+ // macOS /tmp is an alias of /private/tmp. Preserve a trusted cwd's root
27
+ // spelling without resolving any client-supplied symlink beneath it.
28
+ const roots = [base, path.resolve(root), path.resolve(cwd, path.relative(folder, base))]
29
+ .map(value => value.split(path.sep).join("/"));
30
+ const absolute = path.isAbsolute(requested);
31
+ const alias = roots.find(candidate => requested === candidate || requested.startsWith(candidate + "/"));
32
+ if (absolute && !alias)
33
+ throw new BridgeError(403, "This file is outside the repository.");
34
+ const candidates = absolute ? [{ start: base, name: requested.slice(alias.length) }]
35
+ : [...new Set([folder, base])].map(start => ({ start, name: requested }));
36
+ for (const candidate of candidates) {
37
+ try {
38
+ let file = candidate.start;
39
+ // Walk before normalizing '..': link/../file must not hide a symlink,
40
+ // nor may a path leave the repository and then come back into it.
41
+ for (const part of candidate.name.split("/").filter(part => part && part !== ".")) {
42
+ file = path.resolve(file, part);
43
+ if (!beneath(base, file))
44
+ throw new BridgeError(403, "This file is outside the repository.");
45
+ if ((await lstat(file)).isSymbolicLink())
46
+ throw new BridgeError(403, "Symbolic links cannot be opened.");
47
+ }
48
+ const relative = path.relative(base, file).split(path.sep).join("/");
49
+ const metadata = await readFileRange(base, relative, 0, 0);
50
+ return { path: relative, size: metadata.total, contentType: metadata.contentType, version: metadata.version };
51
+ }
52
+ catch (error) {
53
+ // Only a missing name permits a root-relative fallback. A symlink or
54
+ // other rejected cwd candidate must not silently select another file.
55
+ if (error instanceof BridgeError && error.status === 404)
56
+ continue;
57
+ if (["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
58
+ continue;
59
+ throw error;
60
+ }
61
+ }
62
+ throw new BridgeError(404, "This file is no longer available.");
63
+ }
@@ -95,6 +95,7 @@ export declare const capabilities: {
95
95
  providers: string[];
96
96
  files: boolean;
97
97
  repositoryFiles: boolean;
98
+ fileResolution: boolean;
98
99
  subagents: boolean;
99
100
  sideQuestions: boolean;
100
101
  dispatch: boolean;
@@ -105,6 +106,7 @@ export declare const capabilities: {
105
106
  approvalPush: string;
106
107
  simulators: boolean;
107
108
  code: boolean;
109
+ codeFiles: boolean;
108
110
  overviewStream: boolean;
109
111
  speech: boolean;
110
112
  speechTimestamps: boolean;
@@ -22,6 +22,7 @@ import { optionalHookPeers, peerRequest } from "./peers.js";
22
22
  import { candidateRepos, enrollProject } from "./enroll.js";
23
23
  import { browseFiles } from "./files.js";
24
24
  import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
25
+ import { resolveFilePath } from "./file-resolve.js";
25
26
  import { storeRoute } from "./memory-store.js";
26
27
  import { liveBackground, markBackground, paneRecord, recordTitle } from "./session-activity.js";
27
28
  import { paneAccountField, paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
@@ -72,7 +73,7 @@ async function childActivity(source, session) {
72
73
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
73
74
  terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
74
75
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
75
- files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true };
76
+ files: true, repositoryFiles: true, fileResolution: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, ownerInbox: true, workerReports: true, queuedHandOff: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, codeFiles: true, overviewStream: true, speech: true, speechTimestamps: true, speechTimestampStream: true, speechLive: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, deliveryFrames: true, resources: true, sudo: true, sudoOutcome: true, previewDeltas: true, quickChat: true };
76
77
  export function capabilitiesForModules(snapshot) {
77
78
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
78
79
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -403,6 +404,15 @@ export function createRouteHandler(ctx) {
403
404
  case "/v1/files":
404
405
  result = { files: await listUploads("files") };
405
406
  break;
407
+ case "/v1/files/resolve": {
408
+ const target = targetFromURL(url), pane = await validateTarget(target);
409
+ const cwd = await gitRepository(pane, target, url.searchParams.get("child") ?? undefined, url.searchParams.get("worktree") ?? undefined);
410
+ const repository = await gitRoot(cwd);
411
+ if (!repository)
412
+ throw new BridgeError(409, "This pane is not in a project repository.");
413
+ result = await resolveFilePath(repository, cwd, url.searchParams.get("path") ?? "");
414
+ break;
415
+ }
406
416
  case "/v1/files/range": {
407
417
  let root;
408
418
  if (url.searchParams.get("scope") === "uploads") {
@@ -587,6 +597,9 @@ export function createRouteHandler(ctx) {
587
597
  case "/v1/code/search":
588
598
  result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).search(url.searchParams.get("project"), url.searchParams.get("q"), url.searchParams.get("kind"), url.searchParams.get("limit"), url.searchParams.get("directory"));
589
599
  break;
600
+ case "/v1/code/files":
601
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).files(url.searchParams.get("project"), url.searchParams.get("name"), url.searchParams.get("limit"));
602
+ break;
590
603
  case "/v1/code/outline-summary":
591
604
  result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).outlineSummary(url.searchParams.get("project"), url.searchParams.get("paths"));
592
605
  break;