@ryuu-64/dsh-find-all 0.1.15 → 0.1.16

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.
package/lib/index.js CHANGED
@@ -1,14 +1,23 @@
1
- // Optional Host half. Missing RC2 services leave current-conversation find usable.
2
- import { createSearchHandler, SEARCH_PATH } from './search-host.js';
3
- export const name = 'dsh-find-all';
4
- export const inject = [];
5
- export function apply(ctx) {
6
- ctx.inject(['connection', 'sessionQuery', 'workspaceRegistry'], child => {
7
- if (typeof child.sessionQuery.observeSession !== 'function' || typeof child.sessionQuery.listSessions !== 'function' || typeof child.sessionQuery.readTitleSnapshot !== 'function' || typeof child.connection.fetch?.register !== 'function') return;
8
- child.effect(() => {
9
- const handler = createSearchHandler(child);
10
- const stop = child.connection.fetch.register({ path: SEARCH_PATH, methods: ['POST'], requestBody: 'buffered', fetch: handler.fetch });
11
- return async () => { handler.dispose(); await stop(); };
12
- });
13
- });
14
- }
1
+ // Optional Host half. Missing RC2 services leave current-conversation find usable.
2
+ import z from '@deepseek-ai/schemastery';
3
+ import { createSearchHandler, SEARCH_PATH } from './search-host.js';
4
+ export const name = 'dsh-find-all';
5
+ export const inject = [];
6
+ export const Config = z.object({
7
+ defaultTitleOnly: z.boolean().default(false).volatile(),
8
+ defaultIncludeArchived: z.boolean().default(false).volatile(),
9
+ });
10
+ export function apply(ctx) {
11
+ ctx.inject(['settings'], child => {
12
+ if (typeof child.settings?.configure !== 'function') return;
13
+ child.effect(() => child.settings.configure({ auto: false }, ctx.fiber));
14
+ });
15
+ ctx.inject(['connection', 'sessionQuery', 'workspaceRegistry'], child => {
16
+ if (typeof child.sessionQuery.observeSession !== 'function' || typeof child.sessionQuery.listSessions !== 'function' || typeof child.sessionQuery.readTitleSnapshot !== 'function' || typeof child.connection.fetch?.register !== 'function') return;
17
+ child.effect(() => {
18
+ const handler = createSearchHandler(child);
19
+ const stop = child.connection.fetch.register({ path: SEARCH_PATH, methods: ['POST'], requestBody: 'buffered', fetch: handler.fetch });
20
+ return async () => { handler.dispose(); await stop(); };
21
+ });
22
+ });
23
+ }
@@ -1,223 +1,223 @@
1
- // Read-only RC2 transcript search. No FTS, private storage, or persistent index.
2
- import { randomUUID } from 'node:crypto';
3
-
4
- export const SEARCH_PATH = '/api/dsh-find-all/search';
5
- const VERSION = 1;
6
- const SCOPES = ['ordinary-unarchived', 'ordinary-including-archived'];
7
- const MAX_SEARCHES = 8, MAX_CANDIDATES = 100000, TTL = 5 * 60 * 1000;
8
- const BATCH_SESSIONS = 8, BATCH_MS = 100, CHUNK = 65536;
9
- const MAX_EVENTS = 200000, MAX_TEXT = 32 * 1024 * 1024;
10
- const tick = () => new Promise(resolve => setTimeout(resolve, 0));
11
- const abort = signal => signal.throwIfAborted();
12
- const literal = query => new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'giu');
13
- const json = (value, status = 200) => new Response(JSON.stringify(value), { status, headers: {
14
- 'content-type': 'application/json', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff',
15
- } });
16
- class SearchError extends Error { constructor(code, status = 400) { super(code); this.status = status; } }
17
-
18
- // Same escaped /giu rule as the existing in-conversation matcher. Original
19
- // UTF-16 offsets survive Unicode simple folding; no SQL or user regex syntax.
20
- export async function firstLiteralMatch(text, query, signal) {
21
- const matcher = literal(query);
22
- for (let start = 0; start < text.length; start += CHUNK) {
23
- abort(signal);
24
- // An overlap includes any match beginning before the next chunk. Two extra
25
- // code units protect surrogate boundaries; no normalization is performed.
26
- let end = Math.min(text.length, start + CHUNK + query.length + 2);
27
- let from = start;
28
- if (from > 0 && /[\uDC00-\uDFFF]/u.test(text[from])) from--;
29
- if (end < text.length && /[\uDC00-\uDFFF]/u.test(text[end])) end++;
30
- matcher.lastIndex = 0;
31
- const match = matcher.exec(text.slice(from, end));
32
- if (match) return { start: from + match.index, end: from + match.index + match[0].length };
33
- await tick();
34
- }
35
- return null;
36
- }
37
- function excerpt(text, range) {
38
- let start = Math.max(0, range.start - 80), end = Math.min(text.length, range.end + 120);
39
- if (start && /[\uDC00-\uDFFF]/u.test(text[start])) start--;
40
- if (end < text.length && /[\uDC00-\uDFFF]/u.test(text[end])) end++;
41
- const prefix = start ? '…' : '';
42
- return { snippet: prefix + text.slice(start, end) + (end < text.length ? '…' : ''),
43
- ranges: [{ start: prefix.length + range.start - start, end: prefix.length + range.end - start }] };
44
- }
45
-
46
- // RC2 Chat is an append-origin transcript, NOT the model's current surface:
47
- // compaction hides neither earlier human prompts nor settled assistant text.
48
- // Assistant nodes are per turn:step; a retry clears the preceding settlement.
49
- export async function scanObservation(observation, query, signal) {
50
- const events = observation.events;
51
- if (events.length > MAX_EVENTS) return { limited: true };
52
- const users = [], steps = new Map();
53
- let textSize = 0;
54
- for (let i = 0; i < events.length; i++) {
55
- if (i % 256 === 0) { await tick(); abort(signal); }
56
- const event = events[i], data = event.data;
57
- if (!data) continue;
58
- const key = `${data.turn}:${data.step}`;
59
- if (event.type === 'step/start' || event.type === 'llm/retry') { steps.delete(key); continue; }
60
- if (event.surfaceOp !== 'append') continue;
61
- if (event.type === 'user/message' && data.source?.kind === 'user') users.push(event);
62
- else if (event.type === 'assistant/message') steps.set(key, event);
63
- }
64
- const visible = [...users, ...steps.values()].sort((a, b) => a.seq - b.seq);
65
- for (const event of visible) {
66
- abort(signal);
67
- const message = event.type === 'user/message' ? event.data : event.data.message;
68
- if (!message || typeof message.id !== 'string' || !Array.isArray(message.content)) throw new SearchError('invalid-transcript');
69
- // User text is displayed joined; assistant Markdown text blocks remain
70
- // separate, exactly as the existing full-history reader treats them.
71
- const blocks = event.type === 'user/message'
72
- ? [{ text: message.content.filter(part => part?.type === 'text').map(part => part.text).join(''), index: 0 }]
73
- : message.content.flatMap((part, index) => part?.type === 'text' ? [{ text: part.text, index }] : []);
74
- for (const block of blocks) {
75
- if (typeof block.text !== 'string') throw new SearchError('invalid-transcript');
76
- textSize += block.text.length;
77
- if (textSize > MAX_TEXT) return { limited: true };
78
- const range = await firstLiteralMatch(block.text, query, signal);
79
- if (range) return { ...excerpt(block.text, range), message: {
80
- messageId: message.id, seq: event.seq, contentIndex: block.index, cursor: observation.cursor,
81
- } };
82
- }
83
- }
84
- return null;
85
- }
86
-
87
- /** Leases last one batch. State holds IDs, titles, query and one bounded replay page for at most five minutes. */
88
- export function createSearchHandler(ctx) {
89
- const searches = new Map();
90
- const drop = (id, state) => {
91
- if (searches.get(id) !== state) return;
92
- searches.delete(id); clearTimeout(state.timer); state.controller.abort();
93
- };
94
- function touch(id, state) {
95
- clearTimeout(state.timer);
96
- state.timer = setTimeout(() => drop(id, state), TTL); state.timer.unref?.();
97
- }
98
- const archived = () => new Set(ctx.workspaceRegistry.archivedSessionIds);
99
- const allowed = (header, archive, scope) => header && typeof header.cwd === 'string' && header.origin !== 'subagent' && (scope === 'ordinary-including-archived' || !archive.has(header.id));
100
- async function page(id, state, signal) {
101
- const items = [], started = Date.now();
102
- const records = await ctx.sessionQuery.listSessions(signal);
103
- const current = new Map(records.map(record => [record.header.id, record.header]));
104
- let processed = 0;
105
- while (state.offset < state.candidates.length && processed < BATCH_SESSIONS && (!processed || Date.now() - started < BATCH_MS)) {
106
- abort(signal);
107
- const row = state.candidates[state.offset];
108
- let item = null, observation;
109
- let title = row.title, titleMatch = literal(state.query).test(title);
110
- try {
111
- if (!allowed(current.get(row.id), archived(), state.scope)) { state.skipped++; }
112
- else {
113
- let match = null;
114
- if (state.mode === 'title-body') {
115
- observation = await ctx.sessionQuery.observeSession(row.id, { signal, projectionMode: 'none' });
116
- abort(signal);
117
- if (observation.header.id !== row.id || !allowed(observation.header, archived(), state.scope)) state.skipped++;
118
- else {
119
- const savedTitle = observation.events.findLast(event => event.type === 'session/title')?.data?.title;
120
- if (typeof savedTitle === 'string') title = savedTitle;
121
- titleMatch = literal(state.query).test(title);
122
- match = await scanObservation(observation, state.query, signal);
123
- if (match?.limited) { state.skipped++; match = null; }
124
- if (titleMatch || match) item = { sessionId: row.id, title, titleMatch, bodyMatch: !!match,
125
- snippet: match?.snippet || '', ranges: match?.ranges || [], ...(match?.message ? { message: match.message } : {}) };
126
- }
127
- } else {
128
- // Native cold list metadata may have no cached title. A public
129
- // title read is required for correctness, even in title-only mode.
130
- const saved = await ctx.sessionQuery.readTitleSnapshot(row.id, signal);
131
- abort(signal);
132
- if (saved.session.id !== row.id || !allowed(saved.session, archived(), state.scope)) state.skipped++;
133
- else {
134
- if (typeof saved.title?.title === 'string') title = saved.title.title;
135
- titleMatch = literal(state.query).test(title);
136
- if (titleMatch) item = { sessionId: row.id, title, titleMatch: true, bodyMatch: false, snippet: '', ranges: [] };
137
- }
138
- }
139
- // Archive state can change while cold I/O or chunk scanning yields.
140
- if (item && allowed(current.get(row.id), archived(), state.scope)) items.push(item);
141
- else if (item) state.skipped++;
142
- }
143
- } catch (error) {
144
- abort(signal); state.failed++;
145
- if (titleMatch && allowed(current.get(row.id), archived(), state.scope)) items.push({ sessionId: row.id, title, titleMatch: true, bodyMatch: false, snippet: '', ranges: [] });
146
- } finally { observation?.[Symbol.dispose](); }
147
- state.offset++; processed++;
148
- await tick();
149
- }
150
- abort(signal);
151
- // Recheck immediately before sending snippets; an earlier listing is not
152
- // sufficient when a session is deleted or archived during a cold read.
153
- const fresh = new Map((await ctx.sessionQuery.listSessions(signal)).map(record => [record.header.id, record.header]));
154
- const archive = archived();
155
- const visibleItems = items.filter(item => allowed(fresh.get(item.sessionId), archive, state.scope)).map(item => ({ ...item, archived: archive.has(item.sessionId) }));
156
- state.skipped += items.length - visibleItems.length;
157
- abort(signal);
158
- const complete = state.offset === state.candidates.length;
159
- return { version: VERSION, requestId: id, scope: state.scope, items: visibleItems, cursor: complete ? null : randomUUID(),
160
- scanned: state.offset, total: state.candidates.length, failed: state.failed, skipped: state.skipped, complete };
161
- }
162
- async function handle(request) {
163
- let state, id, requestAbort;
164
- try {
165
- if (request.method !== 'POST') return json({ error: 'method-not-allowed' }, 405);
166
- const raw = await request.text();
167
- if (raw.length > 16 * 1024 * 1024) throw new SearchError('request-too-large', 413);
168
- let input;
169
- try { input = JSON.parse(raw); } catch { throw new SearchError('invalid-request'); }
170
- if (!input || typeof input !== 'object' || Array.isArray(input)) throw new SearchError('invalid-request');
171
- id = input.requestId;
172
- if (input.version !== VERSION || typeof id !== 'string' || !/^[a-zA-Z0-9-]{16,80}$/u.test(id)) throw new SearchError('invalid-request');
173
- state = searches.get(id);
174
- if (input.action === 'cancel') { if (state) drop(id, state); return json({ version: VERSION, cancelled: true }); }
175
- if (!['start', 'next'].includes(input.action) || typeof input.query !== 'string' || !input.query.trim() || input.query !== input.query.trim() || input.query.length > 500 || input.query.includes('\0') || !['title', 'title-body'].includes(input.mode) || !SCOPES.includes(input.scope)) throw new SearchError('invalid-request');
176
- if (input.action === 'start') {
177
- if (state) throw new SearchError('search-already-exists', 409);
178
- if (searches.size >= MAX_SEARCHES) throw new SearchError('too-many-searches', 429);
179
- if (!Array.isArray(input.sessionIds) || !Array.isArray(input.catalog) || input.sessionIds.length > MAX_CANDIDATES || input.catalog.length !== input.sessionIds.length) throw new SearchError('invalid-catalog');
180
- const titles = new Map();
181
- for (const row of input.catalog) {
182
- if (!row || typeof row.id !== 'string' || row.id.length > 200 || typeof row.title !== 'string' || row.title.length > 10000 || titles.has(row.id)) throw new SearchError('invalid-catalog');
183
- titles.set(row.id, row.title);
184
- }
185
- if (new Set(input.sessionIds).size !== input.sessionIds.length || input.sessionIds.some(sid => typeof sid !== 'string' || !titles.has(sid))) throw new SearchError('invalid-catalog');
186
- state = { query: input.query, mode: input.mode, scope: input.scope, candidates: input.sessionIds.map(sid => ({ id: sid, title: titles.get(sid) })), offset: 0, failed: 0, skipped: 0, controller: new AbortController(), busy: false, cursor: null, previousCursor: null, response: null, timer: null };
187
- searches.set(id, state); touch(id, state);
188
- } else {
189
- if (!state) throw new SearchError('search-expired', 410);
190
- if (state.query !== input.query || state.mode !== input.mode || state.scope !== input.scope || typeof input.cursor !== 'string') throw new SearchError('cursor-mismatch', 409);
191
- if (state.busy) throw new SearchError('search-busy', 409);
192
- // A retried previous page is replayed, not consumed again.
193
- if (input.cursor === state.previousCursor && state.response) {
194
- state.busy = true;
195
- try {
196
- const replaySignal = AbortSignal.any([request.signal, state.controller.signal]);
197
- const current = new Map((await ctx.sessionQuery.listSessions(replaySignal)).map(record => [record.header.id, record.header]));
198
- const archive = archived();
199
- if (state.response.items.some(item => !allowed(current.get(item.sessionId), archive, state.scope))) {
200
- drop(id, state); throw new SearchError('search-stale', 410);
201
- }
202
- abort(replaySignal); touch(id, state);
203
- return json({ ...state.response, items: state.response.items.map(item => ({ ...item, archived: archive.has(item.sessionId) })) });
204
- } finally { state.busy = false; }
205
- }
206
- if (input.cursor !== state.cursor || state.cursor === null) throw new SearchError('cursor-mismatch', 409);
207
- }
208
- state.busy = true;
209
- requestAbort = () => drop(id, state);
210
- request.signal.addEventListener('abort', requestAbort, { once: true });
211
- if (request.signal.aborted) requestAbort();
212
- const result = await page(id, state, state.controller.signal);
213
- state.previousCursor = input.action === 'next' ? input.cursor : null;
214
- state.cursor = result.cursor; state.response = result; state.busy = false; touch(id, state);
215
- return json(result);
216
- } catch (error) {
217
- // Invalid requests must never cancel a different live request/generation.
218
- if (requestAbort && state) drop(id, state);
219
- return json({ error: error instanceof SearchError ? error.message : request.signal.aborted ? 'cancelled' : 'search-failed' }, error instanceof SearchError ? error.status : request.signal.aborted ? 499 : 503);
220
- } finally { if (requestAbort) request.signal.removeEventListener('abort', requestAbort); }
221
- }
222
- return { fetch: handle, dispose() { for (const [id, state] of searches) drop(id, state); } };
223
- }
1
+ // Read-only RC2 transcript search. No FTS, private storage, or persistent index.
2
+ import { randomUUID } from 'node:crypto';
3
+
4
+ export const SEARCH_PATH = '/api/dsh-find-all/search';
5
+ const VERSION = 1;
6
+ const SCOPES = ['ordinary-unarchived', 'ordinary-including-archived'];
7
+ const MAX_SEARCHES = 8, MAX_CANDIDATES = 100000, TTL = 5 * 60 * 1000;
8
+ const BATCH_SESSIONS = 8, BATCH_MS = 100, CHUNK = 65536;
9
+ const MAX_EVENTS = 200000, MAX_TEXT = 32 * 1024 * 1024;
10
+ const tick = () => new Promise(resolve => setTimeout(resolve, 0));
11
+ const abort = signal => signal.throwIfAborted();
12
+ const literal = query => new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'giu');
13
+ const json = (value, status = 200) => new Response(JSON.stringify(value), { status, headers: {
14
+ 'content-type': 'application/json', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff',
15
+ } });
16
+ class SearchError extends Error { constructor(code, status = 400) { super(code); this.status = status; } }
17
+
18
+ // Same escaped /giu rule as the existing in-conversation matcher. Original
19
+ // UTF-16 offsets survive Unicode simple folding; no SQL or user regex syntax.
20
+ export async function firstLiteralMatch(text, query, signal) {
21
+ const matcher = literal(query);
22
+ for (let start = 0; start < text.length; start += CHUNK) {
23
+ abort(signal);
24
+ // An overlap includes any match beginning before the next chunk. Two extra
25
+ // code units protect surrogate boundaries; no normalization is performed.
26
+ let end = Math.min(text.length, start + CHUNK + query.length + 2);
27
+ let from = start;
28
+ if (from > 0 && /[\uDC00-\uDFFF]/u.test(text[from])) from--;
29
+ if (end < text.length && /[\uDC00-\uDFFF]/u.test(text[end])) end++;
30
+ matcher.lastIndex = 0;
31
+ const match = matcher.exec(text.slice(from, end));
32
+ if (match) return { start: from + match.index, end: from + match.index + match[0].length };
33
+ await tick();
34
+ }
35
+ return null;
36
+ }
37
+ function excerpt(text, range) {
38
+ let start = Math.max(0, range.start - 80), end = Math.min(text.length, range.end + 120);
39
+ if (start && /[\uDC00-\uDFFF]/u.test(text[start])) start--;
40
+ if (end < text.length && /[\uDC00-\uDFFF]/u.test(text[end])) end++;
41
+ const prefix = start ? '…' : '';
42
+ return { snippet: prefix + text.slice(start, end) + (end < text.length ? '…' : ''),
43
+ ranges: [{ start: prefix.length + range.start - start, end: prefix.length + range.end - start }] };
44
+ }
45
+
46
+ // RC2 Chat is an append-origin transcript, NOT the model's current surface:
47
+ // compaction hides neither earlier human prompts nor settled assistant text.
48
+ // Assistant nodes are per turn:step; a retry clears the preceding settlement.
49
+ export async function scanObservation(observation, query, signal) {
50
+ const events = observation.events;
51
+ if (events.length > MAX_EVENTS) return { limited: true };
52
+ const users = [], steps = new Map();
53
+ let textSize = 0;
54
+ for (let i = 0; i < events.length; i++) {
55
+ if (i % 256 === 0) { await tick(); abort(signal); }
56
+ const event = events[i], data = event.data;
57
+ if (!data) continue;
58
+ const key = `${data.turn}:${data.step}`;
59
+ if (event.type === 'step/start' || event.type === 'llm/retry') { steps.delete(key); continue; }
60
+ if (event.surfaceOp !== 'append') continue;
61
+ if (event.type === 'user/message' && data.source?.kind === 'user') users.push(event);
62
+ else if (event.type === 'assistant/message') steps.set(key, event);
63
+ }
64
+ const visible = [...users, ...steps.values()].sort((a, b) => a.seq - b.seq);
65
+ for (const event of visible) {
66
+ abort(signal);
67
+ const message = event.type === 'user/message' ? event.data : event.data.message;
68
+ if (!message || typeof message.id !== 'string' || !Array.isArray(message.content)) throw new SearchError('invalid-transcript');
69
+ // User text is displayed joined; assistant Markdown text blocks remain
70
+ // separate, exactly as the existing full-history reader treats them.
71
+ const blocks = event.type === 'user/message'
72
+ ? [{ text: message.content.filter(part => part?.type === 'text').map(part => part.text).join(''), index: 0 }]
73
+ : message.content.flatMap((part, index) => part?.type === 'text' ? [{ text: part.text, index }] : []);
74
+ for (const block of blocks) {
75
+ if (typeof block.text !== 'string') throw new SearchError('invalid-transcript');
76
+ textSize += block.text.length;
77
+ if (textSize > MAX_TEXT) return { limited: true };
78
+ const range = await firstLiteralMatch(block.text, query, signal);
79
+ if (range) return { ...excerpt(block.text, range), message: {
80
+ messageId: message.id, seq: event.seq, contentIndex: block.index, cursor: observation.cursor,
81
+ } };
82
+ }
83
+ }
84
+ return null;
85
+ }
86
+
87
+ /** Leases last one batch. State holds IDs, titles, query and one bounded replay page for at most five minutes. */
88
+ export function createSearchHandler(ctx) {
89
+ const searches = new Map();
90
+ const drop = (id, state) => {
91
+ if (searches.get(id) !== state) return;
92
+ searches.delete(id); clearTimeout(state.timer); state.controller.abort();
93
+ };
94
+ function touch(id, state) {
95
+ clearTimeout(state.timer);
96
+ state.timer = setTimeout(() => drop(id, state), TTL); state.timer.unref?.();
97
+ }
98
+ const archived = () => new Set(ctx.workspaceRegistry.archivedSessionIds);
99
+ const allowed = (header, archive, scope) => header && typeof header.cwd === 'string' && header.origin !== 'subagent' && (scope === 'ordinary-including-archived' || !archive.has(header.id));
100
+ async function page(id, state, signal) {
101
+ const items = [], started = Date.now();
102
+ const records = await ctx.sessionQuery.listSessions(signal);
103
+ const current = new Map(records.map(record => [record.header.id, record.header]));
104
+ let processed = 0;
105
+ while (state.offset < state.candidates.length && processed < BATCH_SESSIONS && (!processed || Date.now() - started < BATCH_MS)) {
106
+ abort(signal);
107
+ const row = state.candidates[state.offset];
108
+ let item = null, observation;
109
+ let title = row.title, titleMatch = literal(state.query).test(title);
110
+ try {
111
+ if (!allowed(current.get(row.id), archived(), state.scope)) { state.skipped++; }
112
+ else {
113
+ let match = null;
114
+ if (state.mode === 'title-body') {
115
+ observation = await ctx.sessionQuery.observeSession(row.id, { signal, projectionMode: 'none' });
116
+ abort(signal);
117
+ if (observation.header.id !== row.id || !allowed(observation.header, archived(), state.scope)) state.skipped++;
118
+ else {
119
+ const savedTitle = observation.events.findLast(event => event.type === 'session/title')?.data?.title;
120
+ if (typeof savedTitle === 'string') title = savedTitle;
121
+ titleMatch = literal(state.query).test(title);
122
+ match = await scanObservation(observation, state.query, signal);
123
+ if (match?.limited) { state.skipped++; match = null; }
124
+ if (titleMatch || match) item = { sessionId: row.id, title, titleMatch, bodyMatch: !!match,
125
+ snippet: match?.snippet || '', ranges: match?.ranges || [], ...(match?.message ? { message: match.message } : {}) };
126
+ }
127
+ } else {
128
+ // Native cold list metadata may have no cached title. A public
129
+ // title read is required for correctness, even in title-only mode.
130
+ const saved = await ctx.sessionQuery.readTitleSnapshot(row.id, signal);
131
+ abort(signal);
132
+ if (saved.session.id !== row.id || !allowed(saved.session, archived(), state.scope)) state.skipped++;
133
+ else {
134
+ if (typeof saved.title?.title === 'string') title = saved.title.title;
135
+ titleMatch = literal(state.query).test(title);
136
+ if (titleMatch) item = { sessionId: row.id, title, titleMatch: true, bodyMatch: false, snippet: '', ranges: [] };
137
+ }
138
+ }
139
+ // Archive state can change while cold I/O or chunk scanning yields.
140
+ if (item && allowed(current.get(row.id), archived(), state.scope)) items.push(item);
141
+ else if (item) state.skipped++;
142
+ }
143
+ } catch (error) {
144
+ abort(signal); state.failed++;
145
+ if (titleMatch && allowed(current.get(row.id), archived(), state.scope)) items.push({ sessionId: row.id, title, titleMatch: true, bodyMatch: false, snippet: '', ranges: [] });
146
+ } finally { observation?.[Symbol.dispose](); }
147
+ state.offset++; processed++;
148
+ await tick();
149
+ }
150
+ abort(signal);
151
+ // Recheck immediately before sending snippets; an earlier listing is not
152
+ // sufficient when a session is deleted or archived during a cold read.
153
+ const fresh = new Map((await ctx.sessionQuery.listSessions(signal)).map(record => [record.header.id, record.header]));
154
+ const archive = archived();
155
+ const visibleItems = items.filter(item => allowed(fresh.get(item.sessionId), archive, state.scope)).map(item => ({ ...item, archived: archive.has(item.sessionId) }));
156
+ state.skipped += items.length - visibleItems.length;
157
+ abort(signal);
158
+ const complete = state.offset === state.candidates.length;
159
+ return { version: VERSION, requestId: id, scope: state.scope, items: visibleItems, cursor: complete ? null : randomUUID(),
160
+ scanned: state.offset, total: state.candidates.length, failed: state.failed, skipped: state.skipped, complete };
161
+ }
162
+ async function handle(request) {
163
+ let state, id, requestAbort;
164
+ try {
165
+ if (request.method !== 'POST') return json({ error: 'method-not-allowed' }, 405);
166
+ const raw = await request.text();
167
+ if (raw.length > 16 * 1024 * 1024) throw new SearchError('request-too-large', 413);
168
+ let input;
169
+ try { input = JSON.parse(raw); } catch { throw new SearchError('invalid-request'); }
170
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new SearchError('invalid-request');
171
+ id = input.requestId;
172
+ if (input.version !== VERSION || typeof id !== 'string' || !/^[a-zA-Z0-9-]{16,80}$/u.test(id)) throw new SearchError('invalid-request');
173
+ state = searches.get(id);
174
+ if (input.action === 'cancel') { if (state) drop(id, state); return json({ version: VERSION, cancelled: true }); }
175
+ if (!['start', 'next'].includes(input.action) || typeof input.query !== 'string' || !input.query.trim() || input.query !== input.query.trim() || input.query.length > 500 || input.query.includes('\0') || !['title', 'title-body'].includes(input.mode) || !SCOPES.includes(input.scope)) throw new SearchError('invalid-request');
176
+ if (input.action === 'start') {
177
+ if (state) throw new SearchError('search-already-exists', 409);
178
+ if (searches.size >= MAX_SEARCHES) throw new SearchError('too-many-searches', 429);
179
+ if (!Array.isArray(input.sessionIds) || !Array.isArray(input.catalog) || input.sessionIds.length > MAX_CANDIDATES || input.catalog.length !== input.sessionIds.length) throw new SearchError('invalid-catalog');
180
+ const titles = new Map();
181
+ for (const row of input.catalog) {
182
+ if (!row || typeof row.id !== 'string' || row.id.length > 200 || typeof row.title !== 'string' || row.title.length > 10000 || titles.has(row.id)) throw new SearchError('invalid-catalog');
183
+ titles.set(row.id, row.title);
184
+ }
185
+ if (new Set(input.sessionIds).size !== input.sessionIds.length || input.sessionIds.some(sid => typeof sid !== 'string' || !titles.has(sid))) throw new SearchError('invalid-catalog');
186
+ state = { query: input.query, mode: input.mode, scope: input.scope, candidates: input.sessionIds.map(sid => ({ id: sid, title: titles.get(sid) })), offset: 0, failed: 0, skipped: 0, controller: new AbortController(), busy: false, cursor: null, previousCursor: null, response: null, timer: null };
187
+ searches.set(id, state); touch(id, state);
188
+ } else {
189
+ if (!state) throw new SearchError('search-expired', 410);
190
+ if (state.query !== input.query || state.mode !== input.mode || state.scope !== input.scope || typeof input.cursor !== 'string') throw new SearchError('cursor-mismatch', 409);
191
+ if (state.busy) throw new SearchError('search-busy', 409);
192
+ // A retried previous page is replayed, not consumed again.
193
+ if (input.cursor === state.previousCursor && state.response) {
194
+ state.busy = true;
195
+ try {
196
+ const replaySignal = AbortSignal.any([request.signal, state.controller.signal]);
197
+ const current = new Map((await ctx.sessionQuery.listSessions(replaySignal)).map(record => [record.header.id, record.header]));
198
+ const archive = archived();
199
+ if (state.response.items.some(item => !allowed(current.get(item.sessionId), archive, state.scope))) {
200
+ drop(id, state); throw new SearchError('search-stale', 410);
201
+ }
202
+ abort(replaySignal); touch(id, state);
203
+ return json({ ...state.response, items: state.response.items.map(item => ({ ...item, archived: archive.has(item.sessionId) })) });
204
+ } finally { state.busy = false; }
205
+ }
206
+ if (input.cursor !== state.cursor || state.cursor === null) throw new SearchError('cursor-mismatch', 409);
207
+ }
208
+ state.busy = true;
209
+ requestAbort = () => drop(id, state);
210
+ request.signal.addEventListener('abort', requestAbort, { once: true });
211
+ if (request.signal.aborted) requestAbort();
212
+ const result = await page(id, state, state.controller.signal);
213
+ state.previousCursor = input.action === 'next' ? input.cursor : null;
214
+ state.cursor = result.cursor; state.response = result; state.busy = false; touch(id, state);
215
+ return json(result);
216
+ } catch (error) {
217
+ // Invalid requests must never cancel a different live request/generation.
218
+ if (requestAbort && state) drop(id, state);
219
+ return json({ error: error instanceof SearchError ? error.message : request.signal.aborted ? 'cancelled' : 'search-failed' }, error instanceof SearchError ? error.status : request.signal.aborted ? 499 : 503);
220
+ } finally { if (requestAbort) request.signal.removeEventListener('abort', requestAbort); }
221
+ }
222
+ return { fetch: handle, dispose() { for (const [id, state] of searches) drop(id, state); } };
223
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Find All",
4
+ "description": "Search across conversations or find text in the current conversation.",
5
+ "detail": "README.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "对话查找",
4
+ "description": "跨会话搜索,或在当前对话中查找文字。",
5
+ "detail": "README.zh-CN.md"
6
+ }
7
+ }