@clawchatsai/connector 0.2.5 → 0.2.7

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/dist/index.js CHANGED
@@ -16,7 +16,7 @@ import * as os from 'node:os';
16
16
  import * as path from 'node:path';
17
17
  import { createRequire } from 'node:module';
18
18
  import { SignalingClient } from './signaling-client.js';
19
- import { dispatchRpc } from './shim.js';
19
+ import { dispatchRpc, rpcResponseBody } from './shim.js';
20
20
  import { attachBrowserChannel, revokeStaleChannels, loadAuthState } from './auth-handler.js';
21
21
  import { readConfig, writeConfig, updateConfig, readAuthConfig, removeBackupCode, writeFileAtomic, addDevice, touchDevice } from './config-store.js';
22
22
  import { listDevices, revokeDevice, showFingerprint } from './devices-cli.js';
@@ -788,24 +788,7 @@ async function handleRpcMessage(dc, msg, ctx) {
788
788
  };
789
789
  try {
790
790
  const response = await dispatchRpc(rpcReq, app.handleRequest);
791
- // For binary content types (images, audio, etc.), wrap as _binary envelope
792
- // so the browser transport can reconstruct a proper Blob with correct MIME type
793
- const contentType = response.headers['content-type'] || '';
794
- const isBinaryResponse = /^(image|audio|video|application\/octet-stream|application\/pdf)/.test(contentType);
795
- let responseBody;
796
- if (isBinaryResponse && response.rawBody) {
797
- // Encode raw bytes as base64 in a _binary envelope.
798
- // The transport layer on the browser side already handles this format,
799
- // reconstructing a proper Blob with the correct MIME type.
800
- responseBody = {
801
- _binary: true,
802
- contentType,
803
- data: response.rawBody.toString('base64'),
804
- };
805
- }
806
- else {
807
- responseBody = response.body;
808
- }
791
+ const responseBody = rpcResponseBody(response);
809
792
  const responseMsg = {
810
793
  type: 'rpc-res',
811
794
  id: response.id,
package/dist/shim.d.ts CHANGED
@@ -55,6 +55,13 @@ declare class FakeRes extends Writable {
55
55
  writeHead(statusCode: number, headers?: Record<string, string | number>): this;
56
56
  end(chunk?: unknown, encoding?: unknown, _cb?: unknown): this;
57
57
  }
58
+ export declare function isTextContentType(contentType: string): boolean;
59
+ /**
60
+ * The rpc-res body for a response: the text as-is, or a `{ _binary, contentType, data }` envelope
61
+ * (base64) that the browser transport turns back into a Blob. Text goes as text only when its bytes
62
+ * are valid UTF-8, so a Latin-1 CSV still arrives byte-exact. No body or no content type: text.
63
+ */
64
+ export declare function rpcResponseBody(response: RpcResponse): unknown;
58
65
  /**
59
66
  * Dispatch an RPC request through handleRequest and return the response.
60
67
  */
package/dist/shim.js CHANGED
@@ -140,6 +140,33 @@ function tryJsonParse(buf) {
140
140
  return buf.toString('base64');
141
141
  }
142
142
  }
143
+ // Content types sent over the DataChannel as a UTF-8 string; everything else is base64-wrapped.
144
+ // An allowlist, not a binary list: an unknown type (zip, docx, kmz, …) decoded as UTF-8 turns every
145
+ // byte >= 0x80 into U+FFFD. image/svg+xml stays binary: the browser builds typed Blobs from it.
146
+ const TEXT_CONTENT_TYPE = /^(text\/|application\/(json|xml|javascript|x-www-form-urlencoded|yaml)$|application\/[^/]+\+(json|xml)$)/;
147
+ const strictUtf8 = new TextDecoder('utf-8', { fatal: true });
148
+ export function isTextContentType(contentType) {
149
+ return TEXT_CONTENT_TYPE.test(contentType.split(';')[0].trim().toLowerCase());
150
+ }
151
+ /**
152
+ * The rpc-res body for a response: the text as-is, or a `{ _binary, contentType, data }` envelope
153
+ * (base64) that the browser transport turns back into a Blob. Text goes as text only when its bytes
154
+ * are valid UTF-8, so a Latin-1 CSV still arrives byte-exact. No body or no content type: text.
155
+ */
156
+ export function rpcResponseBody(response) {
157
+ const contentType = response.headers['content-type'] || '';
158
+ const raw = response.rawBody;
159
+ if (!contentType || !raw?.length)
160
+ return response.body;
161
+ if (isTextContentType(contentType)) {
162
+ try {
163
+ strictUtf8.decode(raw);
164
+ return response.body;
165
+ }
166
+ catch { /* not UTF-8: send the bytes */ }
167
+ }
168
+ return { _binary: true, contentType, data: raw.toString('base64') };
169
+ }
143
170
  /**
144
171
  * Dispatch an RPC request through handleRequest and return the response.
145
172
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "type": "module",
5
5
  "description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
6
6
  "main": "dist/index.js",
@@ -0,0 +1,66 @@
1
+ // Chat search over the connector's own index (server/search/). The browser falls back to the
2
+ // gateway's sessions.search when these routes are missing (older connector) or answer 503.
3
+ //
4
+ // GET /api/search?q=&role=user|assistant&archived=0|1&limit= one row per chat, best first
5
+ // GET /api/search/status[?detail=1] coverage; detail adds per-chat rows
6
+ // POST /api/search/rebuild drop the index and build it again
7
+
8
+ import http from 'node:http';
9
+ import { send, sendError } from '../util/http.js';
10
+
11
+ const ROLES = new Set(['user', 'assistant']);
12
+
13
+ export function createSearchHandlers({ store, indexer }) {
14
+ function unavailable(res) { return sendError(res, 503, 'Search index unavailable'); }
15
+
16
+ function handleSearch(req, res, query) {
17
+ if (!store) return unavailable(res);
18
+ const q = String(query.q || '').trim();
19
+ if (!q) return sendError(res, 400, 'Missing ?q=');
20
+ const role = ROLES.has(query.role) ? query.role : null;
21
+ const limit = Math.min(Math.max(parseInt(query.limit, 10) || 50, 1), 200);
22
+ const { results, truncated } = store.search({ q, role, archived: query.archived !== '0', limit });
23
+ return send(res, 200, { results, truncated, status: indexer.status() });
24
+ }
25
+
26
+ function handleStatus(req, res, query) {
27
+ if (!store) return unavailable(res);
28
+ return send(res, 200, { status: indexer.status(), ...(query.detail === '1' ? { chats: store.coverage() } : {}) });
29
+ }
30
+
31
+ async function handleRebuild(req, res) {
32
+ if (!store) return unavailable(res);
33
+ indexer.rebuild().catch(e => console.warn(`[search] rebuild: ${e.message}`));
34
+ return send(res, 202, { status: indexer.status() });
35
+ }
36
+
37
+ return { handleSearch, handleStatus, handleRebuild };
38
+ }
39
+
40
+ /**
41
+ * Text of an inbound media file (selection comments), read through the gateway's authenticated
42
+ * assistant-media route (controllers/gateway-media.js). null when the gateway no longer has the
43
+ * file; throws on anything else so the chat is retried.
44
+ */
45
+ export function createInboundTextFetcher({ gatewayWsUrl, gatewayToken, maxBytes = 256 * 1024, timeoutMs = 15_000 }) {
46
+ const base = new URL(gatewayWsUrl.replace(/^ws/, 'http'));
47
+ return function fetchInboundText(url, { sessionKey, field }) {
48
+ const agentId = String(sessionKey || '').split(':')[1] || 'main';
49
+ const q = new URLSearchParams({ source: url, sessionKey: sessionKey || '', agentId });
50
+ const target = `/${field}__/assistant-media?${q}`;
51
+ return new Promise((resolve, reject) => {
52
+ const req = http.request({ hostname: base.hostname, port: base.port, path: target, method: 'GET', headers: { Authorization: `Bearer ${gatewayToken}` }, timeout: timeoutMs }, up => {
53
+ if (up.statusCode === 404 || up.statusCode === 410) { up.resume(); return resolve(null); }
54
+ if (up.statusCode !== 200) { up.resume(); return reject(new Error(`comment file: HTTP ${up.statusCode}`)); }
55
+ const chunks = [];
56
+ let size = 0;
57
+ up.on('data', c => { size += c.length; if (size <= maxBytes) chunks.push(c); });
58
+ up.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
59
+ up.on('error', reject);
60
+ });
61
+ req.on('timeout', () => req.destroy(new Error('comment file: timed out')));
62
+ req.on('error', reject);
63
+ req.end();
64
+ });
65
+ };
66
+ }
@@ -0,0 +1,80 @@
1
+ // Chat tags and summaries (server/tags/). 503 when the tagger isn't running (no search index).
2
+ //
3
+ // GET /api/tags { status, vocabulary: [{ tag, count }], chats: { [key]: { tags, summary } } }
4
+ // PATCH /api/tags/chat { key, add?, remove? } the user's edit of one chat's tags → { chat }
5
+ // POST /api/tags/retag { key } tag this chat again now
6
+ // POST /api/tags/rename { from, to } everywhere; a merge when `to` is in use
7
+ // POST /api/tags/delete { tag } from every chat, and the model won't use it again
8
+ // POST /api/tags/settings { enabled?, backfill?: 'accepted'|'declined' }
9
+
10
+ import { send, sendError, parseBody } from '../util/http.js';
11
+ import { normalizeTag } from '../tags/model.js';
12
+
13
+ const strings = v => (Array.isArray(v) ? v : []).filter(t => typeof t === 'string').slice(0, 20);
14
+
15
+ export function createTagHandlers({ tags, tagger, search }) {
16
+ const unavailable = res => sendError(res, 503, 'Tags unavailable: the search index is off');
17
+
18
+ /** After a change to stored rows: the index copy and every browser follow. */
19
+ function changed(keys) {
20
+ for (const key of keys) {
21
+ const row = tags.get(key);
22
+ if (row) search.setMeta(key, { tags: row.tags, summary: row.summary, keywords: row.keywords });
23
+ tagger.announce(key, row);
24
+ }
25
+ }
26
+
27
+ function handleList(req, res) {
28
+ if (!tagger) return unavailable(res);
29
+ const chats = {};
30
+ for (const r of tags.all()) if (r.tags.length || r.summary) chats[r.key] = { tags: r.tags, summary: r.summary };
31
+ return send(res, 200, { status: tagger.status(), vocabulary: tags.vocabulary(), chats });
32
+ }
33
+
34
+ async function handleEdit(req, res) {
35
+ if (!tagger) return unavailable(res);
36
+ const { key, add, remove } = await parseBody(req);
37
+ if (typeof key !== 'string' || !search.getChat(key)) return sendError(res, 409, 'That chat isn\'t in the search index yet');
38
+ const chat = tags.edit(key, { add: strings(add), remove: strings(remove) });
39
+ changed([key]);
40
+ return send(res, 200, { chat: { key, tags: chat.tags, summary: chat.summary } });
41
+ }
42
+
43
+ async function handleRetag(req, res) {
44
+ if (!tagger) return unavailable(res);
45
+ const { key } = await parseBody(req);
46
+ try { tagger.retag(String(key || '')); }
47
+ catch (e) { return sendError(res, e.status || 500, e.message); }
48
+ return send(res, 202, { status: tagger.status() });
49
+ }
50
+
51
+ async function handleRename(req, res) {
52
+ if (!tagger) return unavailable(res);
53
+ const body = await parseBody(req);
54
+ const from = normalizeTag(body.from), to = normalizeTag(body.to);
55
+ if (!from || !to) return sendError(res, 400, 'A tag is lowercase words joined by hyphens, at most 32 characters');
56
+ if (from === to) return send(res, 200, { changed: 0 });
57
+ const keys = tags.renameTag(from, to);
58
+ changed(keys);
59
+ return send(res, 200, { changed: keys.length });
60
+ }
61
+
62
+ async function handleDelete(req, res) {
63
+ if (!tagger) return unavailable(res);
64
+ const tag = normalizeTag((await parseBody(req)).tag);
65
+ if (!tag) return sendError(res, 400, 'Missing tag');
66
+ const keys = tags.renameTag(tag, '');
67
+ changed(keys);
68
+ return send(res, 200, { changed: keys.length });
69
+ }
70
+
71
+ async function handleSettings(req, res) {
72
+ if (!tagger) return unavailable(res);
73
+ const { enabled, backfill } = await parseBody(req);
74
+ if (typeof enabled === 'boolean') tagger.setEnabled(enabled);
75
+ if (backfill === 'accepted' || backfill === 'declined') tagger.setBackfill(backfill);
76
+ return send(res, 200, { status: tagger.status() });
77
+ }
78
+
79
+ return { handleList, handleEdit, handleRetag, handleRename, handleDelete, handleSettings };
80
+ }
@@ -19,27 +19,32 @@ export function normalizeTitle(raw) {
19
19
  }
20
20
 
21
21
  /**
22
- * Direct completion where the main model's provider has a direct transport; CLI and harness
23
- * runtimes (claude-cli, codex, …) only run in isolated agent-runtime mode.
22
+ * A host-run completion (api.runtime.llm.complete): direct where the model's provider has a direct
23
+ * transport; CLI and harness runtimes (claude-cli, codex, …) only run in isolated agent-runtime mode.
24
+ * `model` pins a model (needs plugins.entries.connector.llm.allowModelOverride); omitted = the host's default.
24
25
  * @param {{ complete?: (params: object) => Promise<{ text?: string }> }} llm api.runtime.llm
26
+ * @param {{ systemPrompt: string, purpose: string, maxTokens?: number }} o
25
27
  */
26
- function createCompletion(llm) {
27
- return async function complete(message) {
28
- const base = { messages: [{ role: 'user', content: message }], systemPrompt: TITLE_PROMPT, purpose: 'clawchats.title', maxTokens: 64 };
28
+ export function createCompletion(llm, { systemPrompt, purpose, maxTokens }) {
29
+ return async function complete(message, { model } = {}) {
30
+ const base = { messages: [{ role: 'user', content: message }], systemPrompt, purpose, maxTokens, ...(model ? { model } : {}) };
29
31
  try {
30
32
  return await llm.complete(base);
31
33
  } catch (err) {
32
34
  // Not a transport problem: isolated mode fails the same way. LLM_RUNTIME_LIFECYCLE (2026.11.5+): the plugin or
33
35
  // model runtime is reloading; the host says to retry from a fresh plugin operation, not inside this one.
34
- if (['LLM_COMPLETION_NOT_AUTHORIZED', 'LLM_RUNTIME_LIFECYCLE', 'LLM_COMPLETION_ABORTED'].includes(err?.code)) throw err;
36
+ // 2026.11.6 reports a retired runtime (plugin reload) by message only.
37
+ if (['LLM_COMPLETION_NOT_AUTHORIZED', 'LLM_RUNTIME_LIFECYCLE', 'LLM_COMPLETION_ABORTED'].includes(err?.code) || /runtime is no longer active/i.test(err?.message || '')) throw err;
35
38
  return await llm.complete({ ...base, maxTokens: undefined, execution: { mode: 'isolated-agent-runtime', timeoutMs: TIMEOUT_MS } });
36
39
  }
37
40
  };
38
41
  }
39
42
 
43
+ const titleCompletion = llm => createCompletion(llm, { systemPrompt: TITLE_PROMPT, purpose: 'clawchats.title', maxTokens: 64 });
44
+
40
45
  /** message → title or null (null also when the host has no plugin model completion). */
41
46
  export function createTitler(llm) {
42
- const complete = createCompletion(llm);
47
+ const complete = titleCompletion(llm);
43
48
  return async message => {
44
49
  if (typeof llm?.complete !== 'function' || typeof message !== 'string' || !message.trim()) return null;
45
50
  return normalizeTitle((await complete(Array.from(message.trim()).slice(0, SOURCE_MAX_CHARS).join('')))?.text);
@@ -50,7 +55,7 @@ export function createTitler(llm) {
50
55
  * @param {{ complete?: (params: object) => Promise<{ text?: string }> }} llm api.runtime.llm
51
56
  */
52
57
  export function createTitleHandler(llm) {
53
- const complete = createCompletion(llm);
58
+ const complete = titleCompletion(llm);
54
59
 
55
60
  return async function handleTitle(req, res) {
56
61
  if (typeof llm?.complete !== 'function') return sendError(res, 501, 'This OpenClaw version has no plugin model completion');
package/server/gateway.js CHANGED
@@ -100,7 +100,7 @@ export class GatewayClient {
100
100
  this.ws = new WS(this.gatewayWsUrl);
101
101
  this.ws.on('open', () => { console.log('Gateway WebSocket connected'); this.reconnectAttempts = 0; });
102
102
  this.ws.on('message', data => this.handleGatewayMessage(data.toString()));
103
- this.ws.on('close', () => { console.log('Gateway WebSocket closed'); this.connected = false; this._failPendingRpcs('gateway disconnected'); this.lens?.reset(); this.broadcastGatewayStatus(false); if (!this._closed) this.scheduleReconnect(); });
103
+ this.ws.on('close', () => { console.log('Gateway WebSocket closed'); this.connected = false; this._failPendingRpcs('gateway disconnected'); this.lens?.reset(); this.onDisconnected?.(); this.broadcastGatewayStatus(false); if (!this._closed) this.scheduleReconnect(); });
104
104
  this.ws.on('error', err => console.error('Gateway WebSocket error:', err.message));
105
105
  }
106
106
 
package/server/index.js CHANGED
@@ -20,6 +20,8 @@ import { handleAgents } from './controllers/agents.js';
20
20
  import { createTitleHandler, createTitler } from './controllers/title.js';
21
21
  import { createSettingsHandlers } from './controllers/settings.js';
22
22
  import { createShareHandlers } from './controllers/shares.js';
23
+ import { createSearchHandlers, createInboundTextFetcher } from './controllers/search.js';
24
+ import { createTagHandlers } from './controllers/tags.js';
23
25
  import { createWorkspaceStore } from './store/workspace-store.js';
24
26
  import { createExtrasStore } from './store/extras-store.js';
25
27
  import { createTeamStore } from './store/team-store.js';
@@ -28,6 +30,11 @@ import { TeamCoordinator } from './team.js';
28
30
  import { SharingManager } from './peer/sharing.js';
29
31
  import { loadOrCreatePeerKey } from './peer/keys.js';
30
32
  import { createGuestAgent } from './peer/guest-agent.js';
33
+ import { SearchStore } from './search/store.js';
34
+ import { SearchIndexer } from './search/indexer.js';
35
+ import { createTagStore } from './tags/store.js';
36
+ import { Tagger } from './tags/tagger.js';
37
+ import { readLegacyThreadSummaries } from './store/legacy-threads.js';
31
38
  import { send, sendError, parseBody, uuid, matchRoute, setCors } from './util/http.js';
32
39
 
33
40
  // PORT is passed via createApp(config.port); env var is read by plugin host (src/index.ts).
@@ -53,7 +60,7 @@ export function createApp(config = {}) {
53
60
  fs.mkdirSync(DATA_DIR, { recursive: true });
54
61
 
55
62
  let namesTimer = null;
56
- function closeAll() { clearInterval(namesTimer); sharing?.close(); gatewayClient?.close(); globalDbCache.close?.(); }
63
+ function closeAll() { clearInterval(namesTimer); tagger?.close(); searchIndexer?.close(); searchStore?.close(); sharing?.close(); gatewayClient?.close(); globalDbCache.close?.(); }
57
64
 
58
65
  // Global DB (custom emojis, cross-workspace data)
59
66
  let _globalDb = null;
@@ -98,10 +105,40 @@ export function createApp(config = {}) {
98
105
  const team = new TeamCoordinator({ store: createTeamStore(() => globalDbCache.get()), request: gwRequest, chatAbort, broadcast, titler: createTitler(config.llm), remote: sharing });
99
106
  // Exec Allows the gateway lost after a session change (OpenClaw 2026.9.7+; server/approval-retry.js).
100
107
  const lostAllows = new LostAllowRetry({ request: gwRequest });
101
- gatewayClient.onEvent = msg => { team.onGatewayEvent(msg); sharing?.onGatewayEvent(msg); };
102
- gatewayClient.onApprovalEvent = msg => { sharing?.onApprovalEvent(msg); lostAllows.onApprovalEvent(msg); };
103
- gatewayClient.onConnected = () => { sharing?.migrateGuestAgents().catch(e => console.warn(`[sharing] guest migration failed: ${e.message}`)); };
104
108
  gatewayClient.lens = new SessionLens({ broadcast, request: gwRequest, extras, team });
109
+ // Chat search: the connector's own full-text index of every chat (server/search/). Derived data in its
110
+ // own file; if it can't open (no FTS5, unreadable file) search falls back to the gateway's in the browser.
111
+ let searchStore = null, searchIndexer = null;
112
+ try {
113
+ searchStore = openSearchStore(path.join(DATA_DIR, 'search.db'));
114
+ searchIndexer = new SearchIndexer({
115
+ store: searchStore, request: gwRequest, lens: gatewayClient.lens, team,
116
+ fetchComment: createInboundTextFetcher({ gatewayWsUrl: gatewayUrl, gatewayToken }),
117
+ notify: frame => broadcast(JSON.stringify(frame)),
118
+ });
119
+ searchIndexer.start();
120
+ } catch (e) { console.error(`[search] index disabled: ${e.message}`); searchStore?.close(); searchStore = null; searchIndexer = null; }
121
+ const search = createSearchHandlers({ store: searchStore, indexer: searchIndexer });
122
+ // Chat tags and summaries (server/tags/): stored in global.db, read from and copied into the search index.
123
+ const tagStore = createTagStore(() => globalDbCache.get());
124
+ let tagger = null;
125
+ if (searchIndexer) {
126
+ try {
127
+ tagger = new Tagger({
128
+ tags: tagStore, search: searchStore, indexer: searchIndexer, llm: config.llm,
129
+ legacy: () => readLegacyThreadSummaries(DATA_DIR), notify: frame => broadcast(JSON.stringify(frame)),
130
+ });
131
+ tagger.start();
132
+ } catch (e) { console.error(`[tags] disabled: ${e.message}`); tagger?.close(); tagger = null; }
133
+ }
134
+ const tagRoutes = createTagHandlers({ tags: tagStore, tagger, search: searchStore });
135
+ gatewayClient.onEvent = msg => {
136
+ team.onGatewayEvent(msg); sharing?.onGatewayEvent(msg);
137
+ if (msg.event === 'sessions.changed') { try { searchIndexer?.onSessionsChanged(msg.payload); } catch (e) { console.warn(`[search] change: ${e.message}`); } }
138
+ };
139
+ gatewayClient.onApprovalEvent = msg => { sharing?.onApprovalEvent(msg); lostAllows.onApprovalEvent(msg); };
140
+ gatewayClient.onConnected = () => { sharing?.migrateGuestAgents().catch(e => console.warn(`[sharing] guest migration failed: ${e.message}`)); searchIndexer?.onConnected(); };
141
+ gatewayClient.onDisconnected = () => searchIndexer?.onDisconnected();
105
142
  // Renamed agents: shares re-issued with the new names, copies of rooms here told (peer/sharing.js, team.js).
106
143
  const quiet = what => e => { if (!/not connected|closed/i.test(e.message)) console.warn(`[${what}] names: ${e.message}`); };
107
144
  namesTimer = setInterval(() => {
@@ -224,6 +261,19 @@ export function createApp(config = {}) {
224
261
  if (method === 'GET' && urlPath === '/api/agents') return handleAgents(req, res);
225
262
  if (method === 'POST' && urlPath === '/api/title') return await handleTitle(req, res);
226
263
 
264
+ // Chat search (controllers/search.js)
265
+ if (method === 'GET' && urlPath === '/api/search') return search.handleSearch(req, res, query);
266
+ if (method === 'GET' && urlPath === '/api/search/status') return search.handleStatus(req, res, query);
267
+ if (method === 'POST' && urlPath === '/api/search/rebuild') return await search.handleRebuild(req, res);
268
+
269
+ // Chat tags (controllers/tags.js)
270
+ if (method === 'GET' && urlPath === '/api/tags') return tagRoutes.handleList(req, res);
271
+ if (method === 'PATCH' && urlPath === '/api/tags/chat') return await tagRoutes.handleEdit(req, res);
272
+ if (method === 'POST' && urlPath === '/api/tags/retag') return await tagRoutes.handleRetag(req, res);
273
+ if (method === 'POST' && urlPath === '/api/tags/rename') return await tagRoutes.handleRename(req, res);
274
+ if (method === 'POST' && urlPath === '/api/tags/delete') return await tagRoutes.handleDelete(req, res);
275
+ if (method === 'POST' && urlPath === '/api/tags/settings') return await tagRoutes.handleSettings(req, res);
276
+
227
277
  // ClawChats-only extras (see EXTRAS.md)
228
278
  if (method === 'GET' && urlPath === '/api/extras/project-styles') {
229
279
  extras.seedFromWorkspaces(getWorkspaces()); // legacy projects renamed by gateway sync keep their style
@@ -443,6 +493,17 @@ export function createApp(config = {}) {
443
493
  };
444
494
  }
445
495
 
496
+ /** The search index; an unreadable file is moved aside and rebuilt (it only holds derived data). */
497
+ function openSearchStore(file) {
498
+ try { return new SearchStore(file); }
499
+ catch (e) {
500
+ if (!fs.existsSync(file)) throw e;
501
+ console.warn(`[search] ${file} unreadable (${e.message}); starting a new index`);
502
+ for (const suffix of ['', '-wal', '-shm']) { try { fs.renameSync(file + suffix, `${file}${suffix}.broken`); } catch { /* absent */ } }
503
+ return new SearchStore(file);
504
+ }
505
+ }
506
+
446
507
  // Standalone mode (node server/index.js or via isDirectRun check in bundle)
447
508
  const isDirectRun = import.meta.url === `file://${process.argv[1]}`;
448
509
  if (isDirectRun) {