@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-4

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.
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Automatic sync scheduling for DSH增强.
3
+ *
4
+ * Three triggers share one serial runner:
5
+ * - interval: every N minutes (settings.syncIntervalMinutes, 0 = off)
6
+ * - daily: one run per day at HH:MM (settings.syncDailyAt)
7
+ * - idle: the first time every agent leaves the running state
8
+ *
9
+ * A run never starts while a session is running, never overlaps another run, and
10
+ * backs off after repeated failures. The engine itself stays the PowerShell
11
+ * script; this module only decides when to call it.
12
+ */
13
+ import { promises as fsp } from 'node:fs';
14
+ import path from 'node:path';
15
+ import { readSettings } from './trash.js';
16
+ import { runSync } from './sync.js';
17
+ import { restartApplication } from './restart.js';
18
+
19
+ const TICK_MS = 60_000;
20
+ const IDLE_DELAY_MS = 30_000;
21
+ const FAILURE_LIMIT = 3;
22
+
23
+ function localDateKey(date) {
24
+ return `${String(date.getFullYear())}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
25
+ }
26
+
27
+ function localClock(date) {
28
+ return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
29
+ }
30
+
31
+ /** Local timestamp with offset, e.g. 2026-11-04 15:17:25+08:00 (human-readable log). */
32
+ function localStamp(date) {
33
+ const pad = (value) => String(value).padStart(2, '0');
34
+ const offset = -date.getTimezoneOffset();
35
+ const sign = offset >= 0 ? '+' : '-';
36
+ const hours = pad(Math.floor(Math.abs(offset) / 60));
37
+ const minutes = pad(Math.abs(offset) % 60);
38
+ return `${String(date.getFullYear())}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}${sign}${hours}${minutes}`;
39
+ }
40
+
41
+ /**
42
+ * Install the scheduler.
43
+ * @param ctx - owning Cordis context.
44
+ * @param deps - resolved paths and the agent registry.
45
+ * @returns disposer that clears every timer and listener.
46
+ */
47
+ export function installSyncScheduler(ctx, deps) {
48
+ const { paths, agents } = deps;
49
+ // One small trace file makes "why did it not run" answerable without a debugger.
50
+ // It is trimmed to the newest 500 lines so it can stay on permanently.
51
+ const traceFile = path.join(paths.base, 'scheduler.log');
52
+ const TRACE_MAX_LINES = 500;
53
+ let traceWrites = 0;
54
+ const trimTrace = async () => {
55
+ try {
56
+ const text = await fsp.readFile(traceFile, 'utf8');
57
+ const lines = text.split('\n');
58
+ if (lines.length <= TRACE_MAX_LINES + 20) return;
59
+ const kept = lines.slice(-(TRACE_MAX_LINES + 1));
60
+ await fsp.writeFile(traceFile, kept.join('\n'), 'utf8');
61
+ } catch {
62
+ // Tracing is diagnostic only; never let it interfere.
63
+ }
64
+ };
65
+ const trace = (message) => {
66
+ void (async () => {
67
+ try {
68
+ await fsp.appendFile(traceFile, `${localStamp(new Date())} ${message}\n`, 'utf8');
69
+ traceWrites += 1;
70
+ if (traceWrites % 20 === 0) await trimTrace();
71
+ } catch {
72
+ // Ignore: the log is best effort.
73
+ }
74
+ })();
75
+ };
76
+ void trimTrace();
77
+ trace(`install agents=${agents === undefined ? 'missing' : 'ok'} syncDir=${String(deps.settings?.syncDir ?? '')}`);
78
+ let tick = null;
79
+ let idleTimer = null;
80
+ let retryTimer = null;
81
+ let disposed = false;
82
+ let running = false;
83
+ let cooldownUntil = 0;
84
+ let failures = 0;
85
+ let paused = false;
86
+ let pausedAt = null;
87
+ let startupTimer = null;
88
+ let lastIntervalAt = 0;
89
+ let lastDailyKey = '';
90
+
91
+ const note = (message, level = 'warn') => {
92
+ const line = `dsh-enhanced sync: ${message}`;
93
+ const logger = ctx.logger;
94
+ if (logger !== undefined && typeof logger[level] === 'function') logger[level](line);
95
+ else if (level === 'error') console.error(line);
96
+ else console.warn(line);
97
+ };
98
+
99
+ const busy = () => {
100
+ try {
101
+ return (agents?.list?.() ?? []).some((agent) => agent?.status === 'running');
102
+ } catch {
103
+ return false;
104
+ }
105
+ };
106
+
107
+ /**
108
+ * Restart so newly synced sessions become visible, but only when nobody is
109
+ * working and the last automatic restart was long enough ago.
110
+ */
111
+ async function restartForNewSessions(record, context) {
112
+ const pulled = Number(record?.summary?.sessions?.pulled) || Number(record?.summary?.sessions?.created) || 0;
113
+ if (pulled <= 0) return false;
114
+ const { paths, settings, agents } = context;
115
+ const busy = (agents?.list?.() ?? []).some((agent) => agent?.status === 'running');
116
+ if (busy) {
117
+ trace(`restart skipped: a session is running (${String(pulled)} new)`);
118
+ return false;
119
+ }
120
+ const marker = path.join(paths.base, 'restart-last.json');
121
+ let last = 0;
122
+ try {
123
+ const stored = JSON.parse(await fsp.readFile(marker, 'utf8'));
124
+ if (Number.isFinite(Number(stored?.at))) last = Number(stored.at);
125
+ } catch {
126
+ last = 0;
127
+ }
128
+ // Reuse the sync cooldown: it already describes how often this machine acts.
129
+ const gapMs = Math.max(0, Number(settings.syncCooldownMinutes) || 0) * 60_000;
130
+ if (last > 0 && Date.now() - last < gapMs) {
131
+ trace(`restart skipped: only ${String(Math.round((Date.now() - last) / 1000))}s since the last one`);
132
+ return false;
133
+ }
134
+ try {
135
+ await fsp.writeFile(marker, JSON.stringify({ at: Date.now(), pulled }), 'utf8');
136
+ } catch {
137
+ // A missing marker only means the next run may restart sooner.
138
+ }
139
+ trace(`restarting for ${String(pulled)} new sessions`);
140
+ await restartApplication(paths);
141
+ return true;
142
+ }
143
+
144
+ async function autoRun(reason) {
145
+ if (disposed || running || paused) {
146
+ trace(`autoRun ${reason}: ignored (disposed=${String(disposed)} running=${String(running)} paused=${String(paused)})`);
147
+ return false;
148
+ }
149
+ if (Date.now() < cooldownUntil) {
150
+ trace(`autoRun ${reason}: cooldown until ${new Date(cooldownUntil).toISOString()}`);
151
+ // The cooldown is the only thing blocking; without this the run is lost,
152
+ // because an idle that lasts minutes produces no further idle edge.
153
+ if (retryTimer === null && !disposed) {
154
+ const delay = Math.max(1000, cooldownUntil - Date.now() + 500);
155
+ trace(`retry scheduled in ${String(Math.round(delay / 1000))}s (after cooldown)`);
156
+ retryTimer = setTimeout(() => {
157
+ retryTimer = null;
158
+ void autoRun('cooldown-retry');
159
+ }, delay);
160
+ }
161
+ return false;
162
+ }
163
+ let settings;
164
+ try {
165
+ settings = await readSettings(paths);
166
+ } catch {
167
+ trace(`autoRun ${reason}: settings unreadable`);
168
+ return false;
169
+ }
170
+ if (settings.syncEnabled !== true) {
171
+ trace(`autoRun ${reason}: syncEnabled is false`);
172
+ return false;
173
+ }
174
+ if (busy()) {
175
+ note(`${reason}: skipped, a session is running`);
176
+ trace(`autoRun ${reason}: skipped, a session is running`);
177
+ return false;
178
+ }
179
+ running = true;
180
+ trace(`autoRun ${reason}: start`);
181
+ try {
182
+ const record = await runSync({ paths, settings, agents }, { probe: false });
183
+ if (record.ok === true) {
184
+ failures = 0;
185
+ note(`${reason}: ok in ${String(record.durationMs)} ms`, 'info');
186
+ await restartForNewSessions(record, { paths, settings, agents }).catch(() => {});
187
+ } else {
188
+ failures += 1;
189
+ paused = failures >= FAILURE_LIMIT;
190
+ if (paused && pausedAt === null) pausedAt = new Date().toISOString();
191
+ if (paused && pausedAt === null) pausedAt = new Date().toISOString();
192
+ note(`${reason}: failed (${String(failures)}/${String(FAILURE_LIMIT)})${paused ? ', auto sync paused' : ''}`, 'error');
193
+ }
194
+ } catch (error) {
195
+ if (error?.code === 'webdav-throttled') {
196
+ // The cloud asked us to back off: skip quietly instead of counting a failure.
197
+ const minutes = Math.max(1, Math.ceil((Number(error.until) - Date.now()) / 60_000));
198
+ note(`${reason}: throttled, waiting ${String(minutes)} min`, 'info');
199
+ trace(`autoRun ${reason}: throttled until ${new Date(Number(error.until)).toISOString()}`);
200
+ return false;
201
+ }
202
+ failures += 1;
203
+ paused = failures >= FAILURE_LIMIT;
204
+ if (paused && pausedAt === null) pausedAt = new Date().toISOString();
205
+ trace(`autoRun ${reason} failed: ${String(error?.code ?? '')} ${String(error?.message ?? error)}`);
206
+ if (!paused && retryTimer === null) {
207
+ trace('retry scheduled in 60s');
208
+ retryTimer = setTimeout(() => {
209
+ retryTimer = null;
210
+ void autoRun('retry');
211
+ }, 60_000);
212
+ }
213
+ note(`${reason}: ${String(error?.message ?? error)}${paused ? ', auto sync paused' : ''}`, 'error');
214
+ } finally {
215
+ running = false;
216
+ cooldownUntil = Date.now() + Math.max(1, Number(settings.syncCooldownMinutes) || 5) * 60_000;
217
+ }
218
+ }
219
+
220
+ async function onTick() {
221
+ if (disposed || paused) return;
222
+ let settings;
223
+ try {
224
+ settings = await readSettings(paths);
225
+ } catch {
226
+ return;
227
+ }
228
+ if (settings.syncEnabled !== true) return;
229
+
230
+ const now = new Date();
231
+ const intervalMinutes = Number(settings.syncIntervalMinutes) || 0;
232
+ if (intervalMinutes > 0) {
233
+ const due = lastIntervalAt === 0 ? false : Date.now() - lastIntervalAt >= intervalMinutes * 60_000;
234
+ if (due && (await autoRun('interval'))) lastIntervalAt = Date.now();
235
+ }
236
+
237
+ const dailyAt = typeof settings.syncDailyAt === 'string' ? settings.syncDailyAt : '';
238
+ if (dailyAt !== '' && localClock(now) === dailyAt && lastDailyKey !== localDateKey(now)) {
239
+ // 只有真的跑起来才记日期,被忙碌/草稿挡住时下一分钟还会再试
240
+ if (await autoRun('daily')) lastDailyKey = localDateKey(now);
241
+ }
242
+ }
243
+
244
+ /** Arm one idle run; a later idle edge (or an emptied composer) replaces it. */
245
+ function armIdle() {
246
+ if (idleTimer !== null) clearTimeout(idleTimer);
247
+ trace('idle armed (+30s)');
248
+ idleTimer = setTimeout(() => {
249
+ idleTimer = null;
250
+ trace('idle timer fired');
251
+ void autoRun('idle');
252
+ }, IDLE_DELAY_MS);
253
+ }
254
+
255
+ const status = () => ({ paused, failures, pausedAt, cooldownUntil, running });
256
+
257
+ const resume = () => {
258
+ failures = 0;
259
+ paused = false;
260
+ pausedAt = null;
261
+ cooldownUntil = 0;
262
+ trace('auto sync resumed by the user');
263
+ return status();
264
+ };
265
+
266
+ // Catch up with other machines right after launch: the first idle edge may be
267
+ // minutes away. The cooldown still applies, so a restart right after a sync
268
+ // costs nothing.
269
+ startupTimer = setTimeout(() => {
270
+ void autoRun('startup');
271
+ }, 5000);
272
+
273
+ const statusListener = ctx.on('agent/status', (payload) => {
274
+ trace(`agent/status=${String(payload?.status)}`);
275
+ if (payload?.status === 'running' && retryTimer !== null) {
276
+ clearTimeout(retryTimer);
277
+ retryTimer = null;
278
+ trace('retry cancelled: a new task started');
279
+ }
280
+ if (payload?.status !== 'idle') return;
281
+ armIdle();
282
+ });
283
+
284
+ tick = setInterval(() => { void onTick(); }, TICK_MS);
285
+
286
+ const dispose = () => {
287
+ disposed = true;
288
+ if (tick !== null) clearInterval(tick);
289
+ if (idleTimer !== null) clearTimeout(idleTimer);
290
+ if (retryTimer !== null) clearTimeout(retryTimer);
291
+ if (startupTimer !== null) clearTimeout(startupTimer);
292
+ if (typeof statusListener === 'function') statusListener();
293
+ };
294
+
295
+ return { dispose, status, resume };
296
+ }
package/host/search.js ADDED
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Full-corpus session text search for DSH增强.
3
+ *
4
+ * The shipped composition mounts `session-query-sqlite` with `openAt: never`
5
+ * and an in-memory index, so full-text search is off by default; its
6
+ * `unicode61` tokenizer would also split Chinese poorly. This module keeps its
7
+ * own derived text cache instead: one plain document per session, rebuilt only
8
+ * when the persistence revision changes, matched by literal substring.
9
+ *
10
+ * Nothing here writes to a session log or activates an Agent.
11
+ */
12
+ const MAX_SEGMENT_CHARS = 24000;
13
+ const MAX_MATCHES_PER_SESSION = Number.POSITIVE_INFINITY;
14
+ const MAX_TOTAL_MATCHES = 500;
15
+ const CONTEXT_CHARS = 42;
16
+
17
+ /** Text blocks of one message, tolerating every message shape the log stores. */
18
+ function messageText(message) {
19
+ if (message === null || typeof message !== 'object') return '';
20
+ const content = message.content;
21
+ if (typeof content === 'string') return content.trim();
22
+ if (!Array.isArray(content)) return '';
23
+ const parts = [];
24
+ for (const block of content) {
25
+ if (block === null || typeof block !== 'object') continue;
26
+ if (block.type === 'text' && typeof block.text === 'string' && block.text.trim() !== '') parts.push(block.text);
27
+ }
28
+ return parts.join('\n').trim();
29
+ }
30
+
31
+ function clip(text) {
32
+ if (text.length <= MAX_SEGMENT_CHARS) return text;
33
+ return text.slice(0, MAX_SEGMENT_CHARS);
34
+ }
35
+
36
+ /** Fold one stored log into the searchable shape, keeping seq for citations. */
37
+ function buildDocument(sessionId, header, events) {
38
+ const segments = [];
39
+ let title = '';
40
+ let updatedAt = typeof header.createdAt === 'number' ? header.createdAt : 0;
41
+ let firstUserText = '';
42
+ for (const event of events) {
43
+ if (typeof event.time === 'number' && event.time > updatedAt) updatedAt = event.time;
44
+ if (event.type === 'user/message') {
45
+ const text = messageText(event.data);
46
+ if (text !== '') {
47
+ if (firstUserText === '') firstUserText = text;
48
+ segments.push({ seq: event.seq, role: 'user', text: clip(text) });
49
+ }
50
+ } else if (event.type === 'assistant/message') {
51
+ const text = messageText(event.data?.message);
52
+ if (text !== '') segments.push({ seq: event.seq, role: 'assistant', text: clip(text) });
53
+ } else if (event.type === 'tool/result') {
54
+ const text = messageText(event.data?.message);
55
+ if (text !== '') segments.push({ seq: event.seq, role: 'tool', text: clip(text) });
56
+ } else if (event.type === 'session/title') {
57
+ const value = event.data?.title;
58
+ if (typeof value === 'string' && value.trim() !== '') title = value.trim();
59
+ }
60
+ }
61
+ if (title === '' && firstUserText !== '') title = firstUserText.split('\n', 1)[0].slice(0, 60);
62
+ return { sessionId, title, updatedAt, segments };
63
+ }
64
+
65
+ async function readDocument(persistence, sessionId, header, signal) {
66
+ const handle = await persistence.open(sessionId, 'read', { signal });
67
+ try {
68
+ const result = await handle.read(undefined, undefined, { signal });
69
+ return buildDocument(sessionId, header, result.events);
70
+ } finally {
71
+ await handle.close();
72
+ }
73
+ }
74
+
75
+ function snippetAround(text, index, length) {
76
+ const start = Math.max(0, index - CONTEXT_CHARS);
77
+ const end = Math.min(text.length, index + length + CONTEXT_CHARS);
78
+ const prefix = start > 0 ? '…' : '';
79
+ const suffix = end < text.length ? '…' : '';
80
+ return `${prefix}${text.slice(start, end)}${suffix}`;
81
+ }
82
+
83
+ /** One document's matches, capped per session. */
84
+ function matchDocument(document, needle, settings, budget) {
85
+ const matches = [];
86
+ if (settings.matchTitle === true && document.title !== '') {
87
+ if (document.title.toLowerCase().includes(needle)) {
88
+ matches.push({ kind: 'title', role: 'title', snippet: document.title, at: document.title.toLowerCase().indexOf(needle) });
89
+ budget.total += 1;
90
+ }
91
+ }
92
+ if (settings.matchBody !== true && settings.matchTools !== true) return matches;
93
+ for (const segment of document.segments) {
94
+ if (matches.length >= MAX_MATCHES_PER_SESSION) break;
95
+ if (segment.role === 'tool' && settings.matchTools !== true) continue;
96
+ if (segment.role !== 'tool' && settings.matchBody !== true) continue;
97
+ if (budget.total >= MAX_TOTAL_MATCHES) break;
98
+ const haystack = segment.text.toLowerCase();
99
+ let from = 0;
100
+ while (matches.length < MAX_MATCHES_PER_SESSION && budget.total < MAX_TOTAL_MATCHES) {
101
+ const at = haystack.indexOf(needle, from);
102
+ if (at < 0) break;
103
+ matches.push({
104
+ kind: 'body',
105
+ role: segment.role,
106
+ seq: segment.seq,
107
+ snippet: snippetAround(segment.text, at, needle.length),
108
+ at,
109
+ });
110
+ budget.total += 1;
111
+ from = at + needle.length;
112
+ }
113
+ }
114
+ return matches;
115
+ }
116
+
117
+ /**
118
+ * Build the search service: one document cache keyed by persistence revision.
119
+ * @param options - Host services the document builder reads.
120
+ * @returns search, plus a cache reset for settings changes.
121
+ */
122
+ export function createSearch(options) {
123
+ const { persistence } = options;
124
+ const cache = new Map();
125
+
126
+ async function ensureDocument(snapshot, signal) {
127
+ const sessionId = snapshot.header.id;
128
+ const revision = String(snapshot.revision ?? '');
129
+ const cached = cache.get(sessionId);
130
+ if (cached !== undefined && cached.revision === revision) return cached.document;
131
+ const document = await readDocument(persistence, sessionId, snapshot.header, signal);
132
+ cache.set(sessionId, { revision, document });
133
+ return document;
134
+ }
135
+
136
+ async function search(query, settings, signal) {
137
+ const started = Date.now();
138
+ const trimmed = query.trim();
139
+ if (trimmed === '') return { groups: [], scanned: 0, truncated: false, tookMs: 0 };
140
+ const needle = trimmed.toLowerCase();
141
+ const snapshotList = await persistence.list({ signal });
142
+ const budget = { total: 0 };
143
+ const groups = [];
144
+ const seen = new Set();
145
+ for (const snapshot of snapshotList) {
146
+ if (signal?.aborted === true) throw Object.assign(new Error('搜索已取消'), { code: 'cancelled' });
147
+ if (snapshot.formatStatus === 'migration-required') continue;
148
+ let document;
149
+ try {
150
+ document = await ensureDocument(snapshot, signal);
151
+ } catch {
152
+ continue;
153
+ }
154
+ seen.add(document.sessionId);
155
+ const matches = matchDocument(document, needle, settings, budget);
156
+ if (matches.length === 0) continue;
157
+ groups.push({
158
+ sessionId: document.sessionId,
159
+ title: document.title !== '' ? document.title : '未命名会话',
160
+ updatedAt: document.updatedAt,
161
+ cwd: typeof snapshot.header.cwd === 'string' ? snapshot.header.cwd : undefined,
162
+ matches,
163
+ });
164
+ if (budget.total >= MAX_TOTAL_MATCHES) break;
165
+ }
166
+ // Drop cache rows whose session log no longer exists.
167
+ for (const id of cache.keys()) if (!seen.has(id)) cache.delete(id);
168
+ groups.sort((a, b) => b.updatedAt - a.updatedAt);
169
+ return {
170
+ groups,
171
+ scanned: snapshotList.length,
172
+ truncated: budget.total >= MAX_TOTAL_MATCHES,
173
+ tookMs: Date.now() - started,
174
+ };
175
+ }
176
+
177
+ function reset() {
178
+ cache.clear();
179
+ }
180
+
181
+ return { search, reset };
182
+ }