@evandu/super-pi 0.1.238 → 0.1.240

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.
@@ -1,252 +1,235 @@
1
1
  import { spawn } from "node:child_process";
2
- import { open, stat } from "node:fs/promises";
3
- import { basename, dirname, join } from "node:path";
2
+ import { createReadStream } from "node:fs";
3
+ import { realpath } from "node:fs/promises";
4
+ import { basename, dirname, isAbsolute, join, posix, resolve } from "node:path";
4
5
  import { fileURLToPath, pathToFileURL } from "node:url";
5
- import { FilesError, createRootGuard, isTextName, looksBinary, toRelative } from "./files.js";
6
- export const MAX_CONTENT_RESULTS = 500;
7
- export const MAX_CONTENT_FILE_BYTES = 512 * 1024;
8
- export const MAX_CONTENT_DEPTH = 12;
9
- export const MAX_CONTENT_MS = 10000;
6
+ import { contains, createRootGuard, FilesError, toRelative } from "./files.js";
7
+ export const MAX_CONTENT_RESULTS = 20000;
8
+ const MAX_SEARCH_MS = 120000;
9
+ const MAX_EVENT_LENGTH = 8 * 1024 * 1024;
10
+ const PREVIEW_LENGTH = 400;
11
+ const BATCH_SIZE = 100;
10
12
  let sdkRipgrep;
11
- /** Pi's public package export hides this helper; resolve the installed module used by createGrepTool. */
12
13
  async function resolveSdkRipgrep() {
13
14
  sdkRipgrep ??= (async () => {
14
15
  const entry = fileURLToPath(await import.meta.resolve("@earendil-works/pi-coding-agent"));
15
16
  const manager = await import(pathToFileURL(join(dirname(entry), "utils", "tools-manager.js")).href);
16
17
  return manager.getToolPath("rg") ?? manager.ensureTool("rg");
17
- })();
18
- return sdkRipgrep;
18
+ })().catch((error) => { sdkRipgrep = undefined; throw error; });
19
+ const path = await sdkRipgrep;
20
+ if (!path)
21
+ sdkRipgrep = undefined;
22
+ return path;
19
23
  }
20
- function normalizeLine(text) { return text.endsWith("\r\n") ? text.slice(0, -2) : text.endsWith("\n") ? text.slice(0, -1) : text; }
21
- /**
22
- * One rg process for all indexed files. createGrepTool is deliberately not used: its path accepts only
23
- * one directory/file and glob cannot express this arbitrary index set, so it would walk a second tree or
24
- * spawn once per file. Matching still uses the SDK's exact ensureTool/getToolPath-selected ripgrep.
25
- * The installed rg has no --files-from flag, so verified absolute candidates are passed as paths.
26
- */
27
- const runRipgrep = ({ rgPath, pattern, paths, signal, onMatch }) => new Promise((resolve, reject) => {
28
- const child = spawn(rgPath, ["--json", "--line-number", "--color=never", "--hidden", "--no-ignore", "--text", "--fixed-strings", "--", pattern, ...paths], { stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
29
- let stdout = "";
30
- let stderr = "";
31
- let chain = Promise.resolve(true);
32
- let stopped = false;
33
- const stop = () => { if (!stopped) {
34
- stopped = true;
35
- child.kill();
36
- } };
37
- const onAbort = () => stop();
38
- signal.addEventListener("abort", onAbort, { once: true });
39
- child.stdout.setEncoding("utf8");
40
- child.stdout.on("data", (chunk) => {
41
- stdout += chunk;
42
- let newline;
43
- while ((newline = stdout.indexOf("\n")) >= 0) {
44
- const row = stdout.slice(0, newline);
45
- stdout = stdout.slice(newline + 1);
46
- chain = chain.then(async (continueSearch) => {
47
- if (!continueSearch)
48
- return false;
49
- let event;
50
- try {
51
- event = JSON.parse(row);
52
- }
53
- catch {
54
- return true;
55
- }
56
- if (event.type !== "match")
57
- return true;
58
- const path = event.data?.path?.text;
59
- const line = event.data?.line_number;
60
- const text = event.data?.lines?.text;
61
- if (!path || !Number.isSafeInteger(line))
62
- return true;
63
- const keepGoing = await onMatch({ path, line: line, text: typeof text === "string" ? normalizeLine(text) : "" });
64
- if (!keepGoing)
65
- stop();
66
- return keepGoing;
67
- });
68
- chain.catch(() => { });
69
- }
70
- });
71
- child.stderr.setEncoding("utf8");
72
- child.stderr.on("data", (chunk) => { stderr += chunk; });
73
- child.on("error", (error) => { signal.removeEventListener("abort", onAbort); reject(new Error(`Failed to run ripgrep: ${error.message}`)); });
74
- child.on("close", (code) => {
75
- signal.removeEventListener("abort", onAbort);
76
- void chain.then(() => {
77
- if (signal.aborted || stopped || code === 0 || code === 1)
78
- resolve();
79
- else
80
- reject(new Error(`ripgrep failed (${code}): ${stderr.trim() || "unknown error"}`));
81
- }, reject);
82
- });
83
- });
84
- async function checkedTextFile(absolute) {
85
- try {
86
- const info = await stat(absolute);
87
- if (!info.isFile())
88
- return "skip";
89
- if (info.size > MAX_CONTENT_FILE_BYTES)
90
- return "size";
91
- const handle = await open(absolute, "r");
92
- try {
93
- const buffer = Buffer.alloc(MAX_CONTENT_FILE_BYTES + 1);
94
- let length = 0;
95
- while (length < buffer.length) {
96
- const read = await handle.read(buffer, length, buffer.length - length, null);
97
- if (!read.bytesRead)
98
- break;
99
- length += read.bytesRead;
100
- }
101
- if (length > MAX_CONTENT_FILE_BYTES)
102
- return "size";
103
- const bytes = buffer.subarray(0, length);
104
- if (looksBinary(bytes) || bytes.includes(0))
105
- return "skip";
106
- new TextDecoder("utf-8", { fatal: true }).decode(bytes);
107
- return "text";
108
- }
109
- finally {
110
- await handle.close();
24
+ export function isProtectedSearchPath(path) {
25
+ return path.split("/").some((segment) => /^\.(?:git|super-pi)$/iu.test(segment));
26
+ }
27
+ function ripgrepArgs(query, { exclude, useIgnoreFiles }) {
28
+ const args = ["--no-config", "--json", "--hidden", "--no-follow", "--fixed-strings", "--color=never", "--no-require-git", "--threads", "4"];
29
+ if (useIgnoreFiles === false)
30
+ args.push("--no-ignore");
31
+ if (exclude)
32
+ args.push("--glob", "!" + exclude);
33
+ // The final exclusions cannot be overridden by an include glob.
34
+ for (const name of [".git", ".super-pi"])
35
+ args.push("--iglob", `!**/${name}`, "--iglob", `!**/${name}/**`);
36
+ if (useIgnoreFiles !== false) {
37
+ for (const name of ["node_modules", ".next", ".cache", ".venv", "coverage", "dist", "build"]) {
38
+ args.push("--glob", `!**/${name}`, "--glob", `!**/${name}/**`);
111
39
  }
112
40
  }
113
- catch {
114
- return "skip";
115
- }
41
+ return [...args, "--", query, "."];
116
42
  }
117
- async function checkedFileSize(absolute) {
43
+ async function isUtf8Text(path, signal) {
44
+ const decoder = new TextDecoder("utf-8", { fatal: true });
118
45
  try {
119
- const info = await stat(absolute);
120
- return !info.isFile() ? "skip" : info.size > MAX_CONTENT_FILE_BYTES ? "size" : "ok";
46
+ for await (const bytes of createReadStream(path, { signal })) {
47
+ if (bytes.includes(0))
48
+ return false;
49
+ decoder.decode(bytes, { stream: true });
50
+ }
51
+ decoder.decode();
52
+ return true;
121
53
  }
122
- catch {
123
- return "skip";
54
+ catch (error) {
55
+ if (error instanceof TypeError)
56
+ return false;
57
+ throw error;
124
58
  }
125
59
  }
126
- function needsContainmentCheck(path) {
127
- return /(^|[\\/])\.\.([\\/]|$)|^[\\/]|^[A-Za-z]:/.test(path);
60
+ function makeHit(path, event) {
61
+ const { line_number: line, lines, submatches } = event.data;
62
+ if (line === undefined || typeof lines?.text !== "string")
63
+ return;
64
+ const fullLine = lines.text.replace(/\r?\n$/u, "");
65
+ const before = submatches?.[0]?.start ?? 0;
66
+ const column = (before ? Buffer.from(fullLine).subarray(0, before).toString("utf8").length : 0) + 1;
67
+ const start = Math.max(0, column - Math.floor(PREVIEW_LENGTH / 3));
68
+ const excerpt = fullLine.slice(start, start + PREVIEW_LENGTH);
69
+ const text = (start ? "…" : "") + excerpt + (start + excerpt.length < fullLine.length ? "…" : "");
70
+ return { path, name: basename(path), line, column, text };
128
71
  }
129
- async function mapConcurrently(items, limit, fn) {
130
- const output = new Array(items.length);
131
- let next = 0;
132
- await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
133
- for (;;) {
134
- const index = next++;
135
- if (index >= items.length)
136
- return;
137
- output[index] = await fn(items[index]);
138
- }
139
- }));
140
- return output;
141
- }
142
- export async function searchByContent(root, candidates, query, indexStatus = { complete: true, skipped: [] }, options = {}) {
72
+ export async function searchByContent(root, query, options = {}) {
73
+ const hits = [];
74
+ const skipped = [];
75
+ const reasons = new Set();
76
+ const result = () => ({ hits, skipped, complete: reasons.size === 0, truncated: reasons.size > 0, reasons: [...reasons] });
77
+ if (!query.trim())
78
+ return result();
79
+ const timeout = AbortSignal.timeout(MAX_SEARCH_MS);
80
+ const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
81
+ const maxResults = options.maxResults ?? MAX_CONTENT_RESULTS;
82
+ const include = options.include && (options.include.includes("/") ? options.include : "**/" + options.include);
143
83
  const guard = createRootGuard(root);
144
84
  await guard("");
145
- const hits = [];
146
- const skipped = new Set(indexStatus.skipped);
147
- const reasons = new Set(indexStatus.complete ? [] : ["index"]);
148
- const needle = query.trim();
149
- if (!needle)
150
- return { hits, truncated: false, skipped: [...skipped], complete: indexStatus.complete, reasons: [...reasons] };
151
- const controller = new AbortController();
152
- const timer = setTimeout(() => controller.abort(), MAX_CONTENT_MS);
153
- const paths = [];
154
- const candidateByPath = new Map();
155
- const eligible = [];
156
- for (const candidate of candidates) {
157
- if (controller.signal.aborted) {
158
- reasons.add("time");
159
- break;
85
+ const canonicalRoot = await realpath(root);
86
+ if (isProtectedSearchPath(root.replaceAll("\\", "/").split("/").at(-1) ?? "")) {
87
+ throw new FilesError(403, "不能搜索应用或 Git 内部目录。", "protected_path");
88
+ }
89
+ signal.throwIfAborted();
90
+ const rgPath = await (options.resolveRipgrep ?? resolveSdkRipgrep)();
91
+ if (!rgPath)
92
+ throw new FilesError(503, "内容搜索不可用(ripgrep 不可用)", "ripgrep_unavailable");
93
+ signal.throwIfAborted();
94
+ const child = spawn(rgPath, ripgrepArgs(query, options), { cwd: root, stdio: ["ignore", "pipe", "pipe"], shell: false, windowsHide: true });
95
+ let spawnError;
96
+ let diagnostic = "";
97
+ child.stderr.setEncoding("utf8").on("data", (chunk) => { diagnostic = (diagnostic + chunk).slice(-4096); });
98
+ child.on("error", (error) => { spawnError = error; });
99
+ const closed = new Promise((done) => child.once("close", done));
100
+ const stop = () => { child.kill(); };
101
+ signal.addEventListener("abort", stop, { once: true });
102
+ let path = "";
103
+ let matches = [];
104
+ let overflow = false;
105
+ let accepted = 0;
106
+ let batch = [];
107
+ let lastFlush = 0;
108
+ const flush = async () => {
109
+ if (!batch.length)
110
+ return;
111
+ await options.onHits(batch);
112
+ batch = [];
113
+ lastFlush = Date.now();
114
+ };
115
+ const publishFile = async (event) => {
116
+ if ((!matches.length && !overflow) || event.data.binary_offset != null || signal.aborted)
117
+ return;
118
+ try {
119
+ // Ripgrep does not follow links. Revalidate on publication in case the tree changed during the scan.
120
+ const canonical = await realpath(await guard(path));
121
+ if (!contains(canonicalRoot, canonical) || isProtectedSearchPath(toRelative(canonicalRoot, canonical)))
122
+ return;
123
+ if (!await isUtf8Text(canonical, signal)) {
124
+ if (skipped.length < 100)
125
+ skipped.push(path);
126
+ reasons.add("encoding");
127
+ return;
128
+ }
160
129
  }
161
- if (candidate.kind !== "file")
162
- continue;
163
- if (candidate.path.replace(/\\/g, "/").split("/").length - 1 > MAX_CONTENT_DEPTH) {
164
- skipped.add(candidate.path);
165
- reasons.add("depth");
166
- continue;
130
+ catch (error) {
131
+ if (error.code === "outside_workspace")
132
+ return;
133
+ if (!signal.aborted)
134
+ reasons.add("unreadable");
135
+ return;
167
136
  }
168
- if (candidate.text === false || !isTextName(candidate.path)) {
169
- skipped.add(candidate.path);
170
- continue;
137
+ if (signal.aborted)
138
+ return;
139
+ for (const match of matches) {
140
+ if (signal.aborted)
141
+ return;
142
+ if (options.onHits) {
143
+ batch.push(match);
144
+ if (batch.length >= BATCH_SIZE || Date.now() - lastFlush >= 80)
145
+ await flush();
146
+ }
147
+ else
148
+ hits.push(match);
171
149
  }
172
- if (candidate.size !== null && candidate.size > MAX_CONTENT_FILE_BYTES) {
173
- skipped.add(candidate.path);
174
- reasons.add("size");
175
- continue;
150
+ accepted += matches.length;
151
+ if (overflow) {
152
+ reasons.add("results");
153
+ stop();
176
154
  }
177
- // Index paths are normalized and symlink-free. Reject any shape that could escape before creating an
178
- // rg argument; all output still takes the full shared containment path below before it is published.
179
- if (needsContainmentCheck(candidate.path)) {
180
- await guard(candidate.path);
155
+ };
156
+ const consume = async (line) => {
157
+ if (line.length > MAX_EVENT_LENGTH) {
158
+ reasons.add("line");
159
+ return;
181
160
  }
182
- eligible.push(candidate);
183
- }
184
- // Do bounded metadata checks concurrently. rg's binary heuristic cannot prove strict UTF-8, so matching
185
- // files get the full byte check below; output passes the shared containment guard before publication.
186
- const checkedCandidates = await mapConcurrently(eligible, 96, async (candidate) => ({ candidate, absolute: join(root, candidate.path), classification: await checkedFileSize(join(root, candidate.path)) }));
187
- for (const { candidate, absolute, classification } of checkedCandidates) {
188
- if (controller.signal.aborted) {
189
- reasons.add("time");
190
- break;
161
+ const event = JSON.parse(line);
162
+ if (event.type === "begin") {
163
+ matches = [];
164
+ overflow = false;
165
+ const supplied = event.data.path?.text;
166
+ path = supplied && !isAbsolute(supplied) ? toRelative(root, resolve(root, supplied)) : "";
167
+ if (path === ".." || path.startsWith("../") || isAbsolute(path) || isProtectedSearchPath(path))
168
+ path = "";
169
+ // A positive rg glob overrides ignore files. Match includes separately so users can combine both.
170
+ if (include && !posix.matchesGlob(path, include))
171
+ path = "";
191
172
  }
192
- if (classification !== "ok") {
193
- skipped.add(candidate.path);
194
- if (classification === "size")
195
- reasons.add("size");
196
- continue;
173
+ else if (event.type === "match" && path) {
174
+ const match = makeHit(path, event);
175
+ if (match && accepted + matches.length < maxResults)
176
+ matches.push(match);
177
+ else if (match)
178
+ overflow = true;
179
+ else {
180
+ reasons.add("encoding");
181
+ if (skipped.length < 100 && !skipped.includes(path))
182
+ skipped.push(path);
183
+ }
197
184
  }
198
- paths.push(absolute);
199
- candidateByPath.set(candidate.path, candidate);
200
- }
185
+ else if (event.type === "end" && path) {
186
+ await publishFile(event);
187
+ path = "";
188
+ }
189
+ };
201
190
  try {
202
- if (controller.signal.aborted)
203
- return { hits, truncated: true, skipped: [...skipped], complete: indexStatus.complete, reasons: [...reasons] };
204
- const rgPath = await (options.resolveRipgrep ?? resolveSdkRipgrep)();
205
- if (!rgPath)
206
- throw new FilesError(503, "内容搜索不可用(ripgrep 不可用)", "ripgrep_unavailable");
207
- await (options.runRipgrep ?? runRipgrep)({ rgPath, pattern: needle, paths, signal: controller.signal, onMatch: async (match) => {
208
- if (controller.signal.aborted) {
209
- reasons.add("time");
210
- return false;
211
- }
212
- let path;
213
- let absolute;
214
- try {
215
- path = toRelative(root, match.path);
216
- absolute = await guard(path);
217
- }
218
- catch (error) {
219
- const code = error.code;
220
- if (code === "outside_workspace" || code === "bad_path" || code === "workspace_missing")
221
- throw error;
222
- skipped.add(match.path);
223
- reasons.add("unreadable");
224
- return true;
225
- }
226
- if (!candidateByPath.has(path)) {
227
- skipped.add(path);
228
- reasons.add("unreadable");
229
- return true;
230
- }
231
- const classification = await checkedTextFile(absolute);
232
- if (classification !== "text") {
233
- skipped.add(path);
234
- if (classification === "size")
235
- reasons.add("size");
236
- return true;
237
- }
238
- hits.push({ path, name: basename(absolute), line: match.line, text: match.text });
239
- if (hits.length >= MAX_CONTENT_RESULTS) {
240
- reasons.add("results");
241
- return false;
191
+ let pending = "";
192
+ let discard = false;
193
+ child.stdout.setEncoding("utf8");
194
+ read: for await (const chunk of child.stdout) {
195
+ const rows = chunk.split("\n");
196
+ const tail = rows.pop();
197
+ for (const row of rows) {
198
+ if (signal.aborted || reasons.has("results"))
199
+ break read;
200
+ if (!discard)
201
+ await consume(pending + row);
202
+ pending = "";
203
+ discard = false;
204
+ }
205
+ if (!discard) {
206
+ pending += tail;
207
+ if (pending.length > MAX_EVENT_LENGTH) {
208
+ reasons.add("line");
209
+ pending = "";
210
+ discard = true;
242
211
  }
243
- return true;
244
- } });
245
- if (controller.signal.aborted)
212
+ }
213
+ }
214
+ const code = await closed;
215
+ if (spawnError)
216
+ throw new FilesError(503, "无法启动正文搜索引擎。", "ripgrep_unavailable");
217
+ if (timeout.aborted)
246
218
  reasons.add("time");
219
+ if (!signal.aborted && !reasons.has("results") && code !== 0 && code !== 1) {
220
+ if (/^rg:.*(?:glob|error parsing|invalid definition)/imu.test(diagnostic))
221
+ throw new FilesError(400, "文件筛选规则无效。", "bad_glob");
222
+ if (!diagnostic.startsWith("rg: No files were searched"))
223
+ reasons.add("unreadable");
224
+ }
225
+ if (!options.signal?.aborted && options.onHits)
226
+ await flush();
227
+ return result();
247
228
  }
248
229
  finally {
249
- clearTimeout(timer);
230
+ signal.removeEventListener("abort", stop);
231
+ if (child.exitCode === null && child.signalCode === null && !spawnError)
232
+ stop();
233
+ await closed;
250
234
  }
251
- return { hits, truncated: reasons.size > 0, skipped: [...skipped], complete: indexStatus.complete, reasons: [...reasons] };
252
235
  }
@@ -288,7 +288,7 @@ export class FileNameIndex {
288
288
  const files = [...this.entries.values()].filter(entry => entry.kind === "file");
289
289
  const ranked = query ? rankPathMatches(files, query) : files;
290
290
  if (query && !ranked.length && this.indexed) {
291
- const approximate = new Fuse(files, { keys: ["path"], threshold: 0.38, ignoreLocation: true });
291
+ const approximate = new Fuse(files, { keys: [{ name: "name", weight: 2 }, { name: "path", weight: 1 }], threshold: 0.38, ignoreLocation: true });
292
292
  ranked.push(...approximate.search(query, { limit: QUICK_OPEN_PAGE_SIZE }).map(match => match.item));
293
293
  }
294
294
  return {
@@ -2,7 +2,8 @@ import { createReadStream, existsSync } from "node:fs";
2
2
  import { matchPathMentions } from "../shared/file-mentions.js";
3
3
  import { spawn } from "node:child_process";
4
4
  import { randomUUID } from "node:crypto";
5
- import { readdir, rm, stat } from "node:fs/promises";
5
+ import { once } from "node:events";
6
+ import { readdir, realpath, rm, stat } from "node:fs/promises";
6
7
  import { createServer } from "node:http";
7
8
  import { gzip } from "node:zlib";
8
9
  import { promisify } from "node:util";
@@ -36,7 +37,7 @@ import { readMessageMedia } from "./message-media.js";
36
37
  import { MESSAGE_FRAME_CSP, MESSAGE_HTML_CSP } from "../shared/message-media.js";
37
38
  import { verifyDirectChildScope, verifyListParentScope, verifyReportTargetScope, verifySpawnParentScope } from "./session-tree-scope.js";
38
39
  import { CHILD_SESSION_LOCK_REASON } from "../shared/child-session-lock.js";
39
- import { MAX_CONTENT_DEPTH, MAX_CONTENT_FILE_BYTES, MAX_CONTENT_RESULTS, searchByContent } from "./content-search.js";
40
+ import { isProtectedSearchPath, MAX_CONTENT_RESULTS, searchByContent } from "./content-search.js";
40
41
  import { getAvailableSkills, readSkill } from "./skills.js";
41
42
  /**
42
43
  * THE NAME INDEX FOR ONE WORKSPACE, created on first use and then kept.
@@ -2818,6 +2819,22 @@ export function createHttpServer(options) {
2818
2819
  }
2819
2820
  if (url.pathname === "/api/files/search") {
2820
2821
  const json = (status, body) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(body)); };
2822
+ const controller = new AbortController();
2823
+ const cancel = () => controller.abort();
2824
+ response.once("close", cancel);
2825
+ const send = async (event) => {
2826
+ controller.signal.throwIfAborted();
2827
+ if (!response.write(JSON.stringify(event) + "\n")) {
2828
+ try {
2829
+ await once(response, "drain", { signal: AbortSignal.any([controller.signal, AbortSignal.timeout(15000)]) });
2830
+ }
2831
+ catch (error) {
2832
+ cancel();
2833
+ response.destroy();
2834
+ throw error;
2835
+ }
2836
+ }
2837
+ };
2821
2838
  try {
2822
2839
  if (request.method !== "GET") {
2823
2840
  json(405, { error: "内容搜索需要 GET 请求。", code: "method" });
@@ -2826,41 +2843,56 @@ export function createHttpServer(options) {
2826
2843
  const workspaceId = url.searchParams.get("workspaceId")?.trim();
2827
2844
  const query = url.searchParams.get("q")?.trim() ?? "";
2828
2845
  const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
2829
- if (!workspaceId || !workspace) {
2830
- json(404, { error: "找不到这个工作区——它可能已经被删除。", code: "no_workspace" });
2846
+ if (!workspaceId || !workspace || workspace.closedAt) {
2847
+ json(404, { error: "找不到这个工作区——它可能已经被关闭或删除。", code: "no_workspace" });
2831
2848
  return;
2832
2849
  }
2833
2850
  const root = await resolveFileCwd(workspace.path, url.searchParams.get("cwd"));
2834
2851
  await explorerPath(workspace.path, root, "", true);
2835
- const cwd = relative(resolve(workspace.path), root).replaceAll("\\", "/");
2836
- const indexKey = sessionScopeKey(workspaceId, cwd);
2837
- if (query.length > 256 || /[\r\n]/.test(query)) {
2852
+ const cwd = toRelative(resolve(workspace.path), root);
2853
+ const canonicalCwd = toRelative(await realpath(workspace.path), await realpath(root));
2854
+ if (isProtectedSearchPath(cwd) || isProtectedSearchPath(canonicalCwd))
2855
+ throw new FilesError(403, "不能搜索应用或 Git 内部目录。", "protected_path");
2856
+ if (query.length > 256 || /[\0\r\n]/u.test(query)) {
2838
2857
  json(400, { error: "搜索词只能是一行,且不超过 256 个字符。", code: "bad_query" });
2839
2858
  return;
2840
2859
  }
2841
- if (!query) {
2842
- json(200, { mode: "content", query, hits: [], truncated: false, skipped: [], complete: true, reasons: [], maxResults: MAX_CONTENT_RESULTS, maxFileBytes: MAX_CONTENT_FILE_BYTES, maxDepth: MAX_CONTENT_DEPTH });
2860
+ const include = url.searchParams.get("include")?.trim();
2861
+ const exclude = url.searchParams.get("exclude")?.trim();
2862
+ if ([include, exclude].some((glob) => glob && (glob.length > 512 || /^[!]/u.test(glob) || /[\0\r\n]/u.test(glob)))) {
2863
+ throw new FilesError(400, "文件筛选规则须为单行 glob,且不超过 512 个字符。", "bad_glob");
2864
+ }
2865
+ const stream = url.searchParams.get("stream") === "1";
2866
+ if (controller.signal.aborted)
2843
2867
  return;
2868
+ if (stream) {
2869
+ response.writeHead(200, { "content-type": "application/x-ndjson; charset=utf-8", "cache-control": "no-store", "x-accel-buffering": "no" });
2870
+ response.flushHeaders();
2844
2871
  }
2845
- const indexes = context.fileIndexes ?? new Map();
2846
- if (!context.fileIndexes)
2847
- context.fileIndexes = indexes;
2848
- let index = indexes.get(indexKey);
2849
- if (!index) {
2850
- index = new FileIndex(workspaceId, (event) => broadcaster.broadcast(event), cwd);
2851
- indexes.set(indexKey, index);
2872
+ const { hits, skipped, ...summary } = await searchByContent(root, query, {
2873
+ include, exclude, useIgnoreFiles: url.searchParams.get("ignore") !== "0", signal: controller.signal,
2874
+ onHits: stream ? (hits) => send({ type: "matches", hits }) : undefined,
2875
+ });
2876
+ if (controller.signal.aborted)
2877
+ return;
2878
+ if (stream) {
2879
+ await send({ type: "done", summary });
2880
+ response.end();
2852
2881
  }
2853
- index.start(root);
2854
- const deadline = Date.now() + 4500;
2855
- while (!index.builtAt && Date.now() < deadline)
2856
- await new Promise((resolve) => setTimeout(resolve, 25));
2857
- const snapshot = index.snapshot();
2858
- const result = await searchByContent(root, [...index.entries.values()], query, snapshot);
2859
- json(200, { mode: "content", query, ...result, maxResults: MAX_CONTENT_RESULTS, maxFileBytes: MAX_CONTENT_FILE_BYTES, maxDepth: MAX_CONTENT_DEPTH });
2882
+ else
2883
+ json(200, { mode: "content", query, hits, skipped, ...summary, maxResults: MAX_CONTENT_RESULTS });
2860
2884
  }
2861
2885
  catch (error) {
2886
+ if (controller.signal.aborted)
2887
+ return;
2862
2888
  const described = describeFilesError(error);
2863
- json(described.status, described.body);
2889
+ if (response.headersSent)
2890
+ response.end(JSON.stringify({ type: "error", error: described.body.error }) + "\n");
2891
+ else
2892
+ json(described.status, described.body);
2893
+ }
2894
+ finally {
2895
+ response.removeListener("close", cancel);
2864
2896
  }
2865
2897
  return;
2866
2898
  }
@@ -512,6 +512,7 @@ export declare class Store {
512
512
  */
513
513
  addToolMessage(conversationId: string, content: string, options?: {
514
514
  delivery?: MessageDelivery;
515
+ prioritizeWaiting?: boolean;
515
516
  }): Promise<Message>;
516
517
  /**
517
518
  * Records the model a conversation runs on. `updatedAt` is deliberately NOT touched, for the same
@@ -842,30 +843,10 @@ export declare class Store {
842
843
  * already decided, so it is refused instead.
843
844
  */
844
845
  reorderWaitingMessage(conversationId: string, messageId: string, toIndex: number): Promise<Message>;
846
+ private moveWaitingMessage;
845
847
  /**
846
- * Pi has just delivered one steered message: unmark it and open the answer to it, in ONE write.
847
- *
848
- * Oldest rather than matched on text, and that is forced on us by Pi rather than chosen: Pi identifies
849
- * its own queued entry by `indexOf` on the message text (`agent-session.ts:1123`), so two identical
850
- * steered messages are ONE entry to it and no host-side matching could do better. Position is sufficient
851
- * anyway because Pi's steering queue is FIFO and Super Pi only ever steers from the front of the waiting
852
- * group.
853
- *
854
- * ONE WRITE, because the reader must never see the intermediate: a message that has stopped waiting but
855
- * has no answer under it yet is the exact broken state this refactor exists to remove, and a browser
856
- * that broadcast between the two halves would put it right back on screen.
857
- *
858
- * WHAT IS DIFFERENT FROM BEFORE, and is the whole point: the message used to be DELETED here. It is now
859
- * merely unmarked, with an assistant message spliced in after it. It was on screen the whole time - it
860
- * was written into the transcript when the user pressed send, long before Pi ever saw it - and it stays
861
- * exactly where it was, now with the agent answering it. Deleting it is what made a steered reply appear
862
- * with no question above it.
863
- *
864
- * `messageId` says WHICH message Pi picked up, for the case where position cannot answer it. A message
865
- * handed to Pi's follow-up queue was never CLAIMED here - it is still `waiting`, because Super Pi keeps
866
- * it in its own list so the user can still withdraw it - and a conversation can hold a `waiting` message
867
- * and a `sending` one at the same time. The caller resolves the delivery by the text Pi announced,
868
- * which is the same text Pi itself matched on.
848
+ * Open the reply to a Pi steer and clear its delivery state in one write.
849
+ * The text match and the FIFO fallback both require a claimed `sending` row.
869
850
  */
870
851
  deliverWaitingMessage(conversationId: string, agentIdentity?: Message["agentIdentity"], messageId?: string): Promise<{
871
852
  user: Message;