wherever-dev 0.10.7 → 0.10.9

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.
Files changed (40) hide show
  1. package/dist/conversation-mode-hint.d.ts +61 -0
  2. package/dist/conversation-mode-hint.d.ts.map +1 -0
  3. package/dist/conversation-mode-hint.js +72 -0
  4. package/dist/conversation-mode-hint.js.map +1 -0
  5. package/dist/index.js +39 -10
  6. package/dist/index.js.map +1 -1
  7. package/dist/protocol.d.ts +2 -0
  8. package/dist/protocol.d.ts.map +1 -1
  9. package/dist/say-tool.d.ts +15 -0
  10. package/dist/say-tool.d.ts.map +1 -1
  11. package/dist/say-tool.js +32 -11
  12. package/dist/say-tool.js.map +1 -1
  13. package/dist/session-pool.d.ts +43 -1
  14. package/dist/session-pool.d.ts.map +1 -1
  15. package/dist/session-pool.js +267 -97
  16. package/dist/session-pool.js.map +1 -1
  17. package/package.json +1 -1
  18. package/public/_app/immutable/chunks/C8RBOgq9.js +2 -0
  19. package/public/_app/immutable/chunks/{C_U1Wf7n.js.map → C8RBOgq9.js.map} +1 -1
  20. package/public/_app/immutable/chunks/{DEHnMYpb.js → DHqQrU3z.js} +2 -2
  21. package/public/_app/immutable/chunks/{DEHnMYpb.js.map → DHqQrU3z.js.map} +1 -1
  22. package/public/_app/immutable/chunks/{CNypXkod.js → NJQCw9It.js} +2 -2
  23. package/public/_app/immutable/chunks/{CNypXkod.js.map → NJQCw9It.js.map} +1 -1
  24. package/public/_app/immutable/entry/{app.C4YBf4E0.js → app.Dd1Cl3I6.js} +3 -3
  25. package/public/_app/immutable/entry/{app.C4YBf4E0.js.map → app.Dd1Cl3I6.js.map} +1 -1
  26. package/public/_app/immutable/entry/start.DBHmFN_F.js +2 -0
  27. package/public/_app/immutable/entry/start.DBHmFN_F.js.map +1 -0
  28. package/public/_app/immutable/nodes/{0.eIidiDOc.js → 0.Bw2Ql94P.js} +2 -2
  29. package/public/_app/immutable/nodes/{0.eIidiDOc.js.map → 0.Bw2Ql94P.js.map} +1 -1
  30. package/public/_app/immutable/nodes/{1.fRyJH8Cr.js → 1.C-hs9yrq.js} +2 -2
  31. package/public/_app/immutable/nodes/{1.fRyJH8Cr.js.map → 1.C-hs9yrq.js.map} +1 -1
  32. package/public/_app/immutable/nodes/{2.DB2e3JOf.js → 2.CTBsackz.js} +58 -58
  33. package/public/_app/immutable/nodes/2.CTBsackz.js.map +1 -0
  34. package/public/_app/version.json +1 -1
  35. package/public/index.html +10 -10
  36. package/public/service-worker.js +1 -1
  37. package/public/_app/immutable/chunks/C_U1Wf7n.js +0 -2
  38. package/public/_app/immutable/entry/start.CPVz7TDN.js +0 -2
  39. package/public/_app/immutable/entry/start.CPVz7TDN.js.map +0 -1
  40. package/public/_app/immutable/nodes/2.DB2e3JOf.js.map +0 -1
@@ -55,16 +55,30 @@ function isValidDate(d) {
55
55
  * the /sessions payload size.
56
56
  */
57
57
  const FIRST_MESSAGE_PREVIEW_MAX = 160;
58
+ /**
59
+ * Force a string to be an independent, flat copy.
60
+ *
61
+ * V8 represents `big.slice(0, 160)` as a SlicedString that keeps its PARENT
62
+ * alive. That is free when the preview is transient, but the listing cache
63
+ * holds one preview per session for the process's lifetime, so an un-flattened
64
+ * slice would pin every full first message (pasted PRDs, specs) in memory:
65
+ * measured at ~33 MB of retained parents for ~2800 sessions whose visible
66
+ * previews total under 1 MB. The Buffer round-trip allocates a fresh string.
67
+ */
68
+ function flattenString(s) {
69
+ return s.length === 0 ? s : Buffer.from(s, 'utf8').toString('utf8');
70
+ }
58
71
  /**
59
72
  * Collapse whitespace and cap to a short preview. Keeps the /sessions payload
60
73
  * tens-of-KB instead of multi-MB while preserving what the sidebar displays and
61
- * filters on.
74
+ * filters on. The result is flattened so caching it cannot retain the (possibly
75
+ * huge) message it was sliced from.
62
76
  */
63
77
  function previewText(text) {
64
78
  const collapsed = (text || '').replace(/\s+/g, ' ').trim();
65
- return collapsed.length > FIRST_MESSAGE_PREVIEW_MAX
79
+ return flattenString(collapsed.length > FIRST_MESSAGE_PREVIEW_MAX
66
80
  ? collapsed.slice(0, FIRST_MESSAGE_PREVIEW_MAX) + '\u2026'
67
- : collapsed;
81
+ : collapsed);
68
82
  }
69
83
  /**
70
84
  * Convert a Date to an ISO string, tolerating invalid/missing dates.
@@ -157,20 +171,20 @@ export function makeIgnoreMatcher(patterns) {
157
171
  * is missing/unreadable. This is the cheap pre-filter that lets us skip an
158
172
  * ignored folder before reading its (potentially many, large) file bodies.
159
173
  */
160
- function readSessionCwdFromHeader(filePath) {
174
+ async function readSessionCwdFromHeader(filePath) {
161
175
  try {
162
- const fd = fs.openSync(filePath, 'r');
176
+ const fh = await fs.promises.open(filePath, 'r');
163
177
  try {
164
178
  const buf = Buffer.alloc(8192);
165
- const bytes = fs.readSync(fd, buf, 0, buf.length, 0);
166
- const text = buf.toString('utf8', 0, bytes);
179
+ const { bytesRead } = await fh.read(buf, 0, buf.length, 0);
180
+ const text = buf.toString('utf8', 0, bytesRead);
167
181
  const nl = text.indexOf('\n');
168
182
  const firstLine = nl === -1 ? text : text.slice(0, nl);
169
183
  const header = JSON.parse(firstLine);
170
184
  return typeof header?.cwd === 'string' ? header.cwd : '';
171
185
  }
172
186
  finally {
173
- fs.closeSync(fd);
187
+ await fh.close();
174
188
  }
175
189
  }
176
190
  catch {
@@ -193,14 +207,14 @@ function resolveSessionCwd(rawCwd) {
193
207
  return normalizePath(cwd);
194
208
  }
195
209
  /**
196
- * Parse one session .jsonl into the subset of fields the listing needs. This is
197
- * the directory-aware path's equivalent of pi's internal buildSessionInfo
198
- * (which is not exported), used ONLY for folders that survived the ignore
199
- * pre-filter. Returns null for a non-session / empty / unreadable file.
210
+ * Parse one session .jsonl body into the subset of fields the listing needs.
211
+ * This is the directory-aware path's equivalent of pi's internal
212
+ * buildSessionInfo (which is not exported). Pure: the caller does the IO, so
213
+ * the result can be cached against the file's (mtime, size) stamp.
214
+ * Returns null for a non-session / empty / unparseable file.
200
215
  */
201
- function buildDiskSessionInfo(filePath) {
216
+ function parseDiskSessionInfo(filePath, content, mtime) {
202
217
  try {
203
- const content = fs.readFileSync(filePath, 'utf8');
204
218
  const lines = content.trim().split('\n');
205
219
  const entries = [];
206
220
  for (const line of lines) {
@@ -219,7 +233,6 @@ function buildDiskSessionInfo(filePath) {
219
233
  const parentSessionPath = typeof header.parentSession === 'string' && header.parentSession
220
234
  ? header.parentSession
221
235
  : undefined;
222
- const stats = fs.statSync(filePath);
223
236
  let messageCount = 0;
224
237
  let firstMessage = '';
225
238
  let name;
@@ -253,7 +266,7 @@ function buildDiskSessionInfo(filePath) {
253
266
  }
254
267
  const headerTime = typeof header.timestamp === 'string' ? new Date(header.timestamp).getTime() : NaN;
255
268
  const created = Number.isFinite(headerTime) ? new Date(headerTime) : new Date(NaN);
256
- const modified = lastMessageTime > 0 ? new Date(lastMessageTime) : stats.mtime;
269
+ const modified = lastMessageTime > 0 ? new Date(lastMessageTime) : mtime;
257
270
  return {
258
271
  path: filePath,
259
272
  id: typeof header.id === 'string' ? header.id : '',
@@ -262,7 +275,10 @@ function buildDiskSessionInfo(filePath) {
262
275
  created,
263
276
  modified,
264
277
  messageCount,
265
- firstMessage: firstMessage || '(no messages)',
278
+ // Store the CAPPED preview, never the raw first message: the cache holds
279
+ // one entry per session on disk, so keeping full first messages (pasted
280
+ // PRDs, specs) resident would cost megabytes of heap for no benefit.
281
+ firstMessage: previewText(firstMessage) || '(no messages)',
266
282
  ...(parentSessionPath ? { parentSessionPath } : {}),
267
283
  };
268
284
  }
@@ -270,8 +286,175 @@ function buildDiskSessionInfo(filePath) {
270
286
  return null;
271
287
  }
272
288
  }
289
+ /**
290
+ * Process-wide cache of parsed session-listing info, keyed by absolute file
291
+ * path. Without it, EVERY `/sessions` request re-read and re-parsed every
292
+ * session file on disk (measured: ~1.1 GB / 341k JSON lines / ~7s of blocking
293
+ * work on a real sessions dir), and the dashboard refetches that list on every
294
+ * `sessions_updated` broadcast. Entries for files that disappear from disk are
295
+ * evicted at the end of each scan, so the cache stays proportional to the
296
+ * sessions that actually exist.
297
+ */
298
+ const diskSessionCache = new Map();
299
+ /**
300
+ * Per-directory cwd probe cache. A session directory name is a stable encoding
301
+ * of its cwd and every session inside shares that cwd, so one header probe
302
+ * decides the whole folder forever (until the directory itself goes away).
303
+ */
304
+ const dirCwdCache = new Map();
305
+ /**
306
+ * Scans currently running, keyed by `sessionsRoot::label`. `label` identifies
307
+ * the FILTER (the view), so callers that want the same view share one pass
308
+ * instead of each paying for its own: N dashboard tabs reconnecting at once,
309
+ * or a burst of requests during the first (cold) scan after a restart, would
310
+ * otherwise all parse the same files concurrently. A joiner gets the snapshot
311
+ * of the in-flight pass, so it can be at most one scan-duration stale, which is
312
+ * the same freshness guarantee a request arriving a moment earlier would get.
313
+ */
314
+ const inFlightScans = new Map();
315
+ /** Test seam: drop all cached listing state. */
316
+ export function clearSessionIndexCache() {
317
+ diskSessionCache.clear();
318
+ dirCwdCache.clear();
319
+ inFlightScans.clear();
320
+ }
321
+ /**
322
+ * Yield to the event loop. The scan runs on the same thread that serves the
323
+ * WebSocket, so a cold pass must never hold the loop: a blocked loop is exactly
324
+ * what made "Loading session..." hang while the browser hammered /sessions.
325
+ */
326
+ function yieldToEventLoop() {
327
+ return new Promise((resolve) => setImmediate(resolve));
328
+ }
329
+ /** How many files to parse between event-loop yields during a cold scan. */
330
+ const SCAN_YIELD_EVERY = 8;
331
+ /** Only log scan stats when a pass did real work (avoids a per-request log). */
332
+ const SCAN_LOG_MIN_READS = 10;
333
+ /**
334
+ * Scan the sessions root and return listing info for every session whose folder
335
+ * passes `folderWanted`. Async, cached and yielding: a warm pass is a `stat`
336
+ * per file (milliseconds), and even a cold pass never blocks the event loop.
337
+ */
338
+ export function scanDiskSessions(sessionsRoot, folderWanted, label) {
339
+ const key = `${sessionsRoot}::${label}`;
340
+ const running = inFlightScans.get(key);
341
+ if (running)
342
+ return running;
343
+ const scan = runDiskScan(sessionsRoot, folderWanted, label).finally(() => {
344
+ inFlightScans.delete(key);
345
+ });
346
+ inFlightScans.set(key, scan);
347
+ return scan;
348
+ }
349
+ async function runDiskScan(sessionsRoot, folderWanted, label) {
350
+ let dirEntries;
351
+ try {
352
+ dirEntries = await fs.promises.readdir(sessionsRoot, { withFileTypes: true });
353
+ }
354
+ catch {
355
+ return [];
356
+ }
357
+ const started = Date.now();
358
+ const seenFiles = new Set();
359
+ const seenDirs = new Set();
360
+ const infos = [];
361
+ let prunedFolders = 0;
362
+ let readCount = 0;
363
+ let parsedSinceYield = 0;
364
+ for (const dirEntry of dirEntries) {
365
+ if (!dirEntry.isDirectory())
366
+ continue;
367
+ const dirPath = path.join(sessionsRoot, dirEntry.name);
368
+ let files;
369
+ try {
370
+ files = (await fs.promises.readdir(dirPath)).filter((f) => f.endsWith('.jsonl'));
371
+ }
372
+ catch {
373
+ continue;
374
+ }
375
+ if (files.length === 0)
376
+ continue;
377
+ seenDirs.add(dirPath);
378
+ for (const f of files)
379
+ seenFiles.add(path.join(dirPath, f));
380
+ // Cheap pre-filter: one header probe (cached per directory) recovers the
381
+ // authoritative cwd for the whole folder. Unwanted folders are skipped
382
+ // before any file body is read.
383
+ let probeCwd = dirCwdCache.get(dirPath);
384
+ if (probeCwd === undefined) {
385
+ probeCwd = resolveSessionCwd(await readSessionCwdFromHeader(path.join(dirPath, files[0])));
386
+ dirCwdCache.set(dirPath, probeCwd);
387
+ }
388
+ if (probeCwd && !folderWanted(probeCwd)) {
389
+ prunedFolders++;
390
+ continue;
391
+ }
392
+ for (const f of files) {
393
+ const filePath = path.join(dirPath, f);
394
+ let stats;
395
+ try {
396
+ stats = await fs.promises.stat(filePath);
397
+ }
398
+ catch {
399
+ continue;
400
+ }
401
+ const cached = diskSessionCache.get(filePath);
402
+ let info;
403
+ if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size) {
404
+ info = cached.info;
405
+ }
406
+ else {
407
+ let content;
408
+ try {
409
+ content = await fs.promises.readFile(filePath, 'utf8');
410
+ }
411
+ catch {
412
+ continue;
413
+ }
414
+ info = parseDiskSessionInfo(filePath, content, stats.mtime);
415
+ diskSessionCache.set(filePath, { mtimeMs: stats.mtimeMs, size: stats.size, info });
416
+ readCount++;
417
+ if (++parsedSinceYield >= SCAN_YIELD_EVERY) {
418
+ parsedSinceYield = 0;
419
+ await yieldToEventLoop();
420
+ }
421
+ }
422
+ if (!info)
423
+ continue;
424
+ // Defensive per-session re-check (mixed/edge cases the folder probe missed).
425
+ if (!folderWanted(resolveSessionCwd(info.cwd)))
426
+ continue;
427
+ infos.push(info);
428
+ }
429
+ }
430
+ // Evict entries whose files/directories are gone (deleted sessions).
431
+ for (const key of diskSessionCache.keys()) {
432
+ if (!seenFiles.has(key))
433
+ diskSessionCache.delete(key);
434
+ }
435
+ for (const key of dirCwdCache.keys()) {
436
+ if (!seenDirs.has(key))
437
+ dirCwdCache.delete(key);
438
+ }
439
+ if (readCount >= SCAN_LOG_MIN_READS) {
440
+ console.log(`[wherever] ${label}: parsed ${readCount} changed session file(s) of ${seenFiles.size}` +
441
+ `${prunedFolders > 0 ? `, skipped ${prunedFolders} folder(s)` : ''} in ${Date.now() - started}ms`);
442
+ }
443
+ return infos;
444
+ }
445
+ /**
446
+ * Directory holding `config.json`. `WHEREVER_CONFIG_DIR` overrides the default
447
+ * `~/.wherever` so a test server can run in FULL isolation (ADR 0001): without
448
+ * it, an isolated harness still reads the developer's real config, so e.g. a
449
+ * personal `sessions.ignore: ["/tmp/**"]` silently hid the harness's own
450
+ * temp-dir sessions from /sessions.
451
+ */
452
+ function getWhereverConfigDir() {
453
+ const override = process.env.WHEREVER_CONFIG_DIR;
454
+ return override && override.trim() ? path.resolve(override.trim()) : path.join(os.homedir(), '.wherever');
455
+ }
273
456
  export function getWhereverConfig() {
274
- const configDir = path.join(os.homedir(), '.wherever');
457
+ const configDir = getWhereverConfigDir();
275
458
  const configPath = path.join(configDir, 'config.json');
276
459
  if (!fs.existsSync(configPath)) {
277
460
  try {
@@ -482,6 +665,7 @@ import { spawn } from 'node:child_process';
482
665
  import { randomUUID } from 'node:crypto';
483
666
  import { createAttachFileTool } from './attach-file-tool.js';
484
667
  import { createSayTool } from './say-tool.js';
668
+ import { createConversationModeSignal } from './conversation-mode-hint.js';
485
669
  export class SessionPool {
486
670
  sessions = new Map();
487
671
  pendingSessions = new Map();
@@ -504,6 +688,20 @@ export class SessionPool {
504
688
  }
505
689
  async initialize() {
506
690
  this.modelRegistry.refresh();
691
+ this.warmSessionIndex();
692
+ }
693
+ /**
694
+ * Populate the session-listing cache in the background at startup, so the
695
+ * first dashboard load does not pay for the one cold pass over the sessions
696
+ * directory (seconds on a large one). Deliberately not awaited: the scan
697
+ * yields to the event loop, so the server accepts connections throughout, and
698
+ * a request arriving mid-warm-up joins this same pass instead of duplicating
699
+ * it (see inFlightScans).
700
+ */
701
+ warmSessionIndex() {
702
+ void this.listSessions('default').catch(() => {
703
+ /* warm-up is best-effort: a real request will retry and report. */
704
+ });
507
705
  }
508
706
  /**
509
707
  * List available models. `isDefault` is resolved against `cwd` (falling back to
@@ -557,8 +755,7 @@ export class SessionPool {
557
755
  resolvedFile = active.sessionFile;
558
756
  }
559
757
  else {
560
- const diskSessions = await SessionManager.listAll();
561
- const found = diskSessions.find(s => s.id === sessionFile || s.name === sessionFile);
758
+ const found = await this.findDiskSessionByIdOrName(sessionFile);
562
759
  if (found) {
563
760
  resolvedFile = found.path;
564
761
  }
@@ -634,8 +831,7 @@ export class SessionPool {
634
831
  }
635
832
  else {
636
833
  // 2. Scan the disk to find the session with the matching ID/name
637
- const diskSessions = await SessionManager.listAll();
638
- const found = diskSessions.find(s => s.id === sessionFile || s.name === sessionFile);
834
+ const found = await this.findDiskSessionByIdOrName(sessionFile);
639
835
  if (found) {
640
836
  resolvedFile = found.path;
641
837
  }
@@ -678,10 +874,16 @@ export class SessionPool {
678
874
  }
679
875
  }
680
876
  const settingsManager = SettingsManager.create(normalizedCwd, this.agentDir);
877
+ // The conversation-mode signal is an INLINE pi extension (the SDK-supported
878
+ // way to get a before_agent_start hook on a server-created session, the
879
+ // counterpart of the pi.on(...) the CLI-bridge extension registers). It is
880
+ // per session, so the armed flag can never cross sessions.
881
+ const conversationSignal = createConversationModeSignal();
681
882
  const resourceLoader = new DefaultResourceLoader({
682
883
  cwd: normalizedCwd,
683
884
  agentDir: this.agentDir,
684
885
  settingsManager,
886
+ extensionFactories: [conversationSignal.inlineExtension],
685
887
  });
686
888
  await resourceLoader.reload();
687
889
  const { session: agentSession } = await createAgentSession({
@@ -713,6 +915,7 @@ export class SessionPool {
713
915
  createdAt: Date.now(),
714
916
  lastActivity: Date.now(),
715
917
  inFlightToolCount: 0,
918
+ conversationSignal,
716
919
  };
717
920
  this.sessions.set(resolvedFile, tracked);
718
921
  return { tracked };
@@ -893,10 +1096,14 @@ export class SessionPool {
893
1096
  }
894
1097
  }
895
1098
  const settingsManager = SettingsManager.create(resolvedCwd, this.agentDir);
1099
+ // Per-turn conversation-mode signal (see the other DefaultResourceLoader
1100
+ // call for the rationale).
1101
+ const conversationSignal = createConversationModeSignal();
896
1102
  const resourceLoader = new DefaultResourceLoader({
897
1103
  cwd: resolvedCwd,
898
1104
  agentDir: this.agentDir,
899
1105
  settingsManager,
1106
+ extensionFactories: [conversationSignal.inlineExtension],
900
1107
  });
901
1108
  await resourceLoader.reload();
902
1109
  const { session: agentSession } = await createAgentSession({
@@ -927,6 +1134,7 @@ export class SessionPool {
927
1134
  createdAt: Date.now(),
928
1135
  lastActivity: Date.now(),
929
1136
  inFlightToolCount: 0,
1137
+ conversationSignal,
930
1138
  };
931
1139
  this.sessions.set(sessionFile, tracked);
932
1140
  return { tracked, sessionFile };
@@ -1209,32 +1417,17 @@ export class SessionPool {
1209
1417
  * tagged `readOnly: true`.
1210
1418
  * In both cases, excluded folders are pruned BEFORE their file bodies are
1211
1419
  * read (cheap one-header probe per folder), so they cost nothing to scan.
1420
+ *
1421
+ * Backed by `scanDiskSessions`, which caches each file's parsed info against
1422
+ * its (mtime, size) stamp and yields to the event loop between parses. The
1423
+ * dashboard refetches this list on every `sessions_updated`, so an uncached
1424
+ * re-read of the whole sessions dir here stalls the WebSocket (and with it
1425
+ * any in-flight session load) for as long as the scan takes.
1212
1426
  */
1213
1427
  async listSessions(view = 'default') {
1214
1428
  const cfg = getWhereverConfig().sessions;
1215
- const ignorePatterns = cfg?.ignore;
1216
- const readOnlyPatterns = cfg?.readOnly;
1217
- const isIgnored = makeIgnoreMatcher(ignorePatterns);
1218
- const isReadOnly = makeIgnoreMatcher(readOnlyPatterns);
1219
- const hasIgnore = !!ignorePatterns && ignorePatterns.length > 0;
1220
- const hasReadOnly = !!readOnlyPatterns && readOnlyPatterns.length > 0;
1221
- // Fast path: no ignore AND no read-only patterns, and the caller wants the
1222
- // default view -> keep pi's listAll() exactly as before (zero behaviour or
1223
- // perf change for users who haven't opted in).
1224
- if (view === 'default' && !hasIgnore && !hasReadOnly) {
1225
- const diskSessions = await SessionManager.listAll();
1226
- return this.buildFolders(diskSessions.map((s) => ({
1227
- path: s.path,
1228
- id: s.id,
1229
- cwd: s.cwd,
1230
- name: s.name,
1231
- created: s.created,
1232
- modified: s.modified,
1233
- messageCount: s.messageCount,
1234
- firstMessage: s.firstMessage,
1235
- parentSessionPath: s.parentSessionPath,
1236
- })));
1237
- }
1429
+ const isIgnored = makeIgnoreMatcher(cfg?.ignore);
1430
+ const isReadOnly = makeIgnoreMatcher(cfg?.readOnly);
1238
1431
  // A folder is KEPT only if its cwd belongs in the requested view:
1239
1432
  // - default: not ignored AND not read-only.
1240
1433
  // - readonly: not ignored AND read-only.
@@ -1243,59 +1436,19 @@ export class SessionPool {
1243
1436
  return false;
1244
1437
  return view === 'readonly' ? isReadOnly(cwd) : !isReadOnly(cwd);
1245
1438
  };
1246
- // Directory-aware path: prune unwanted folders BEFORE reading their file
1247
- // bodies, so the excluded sessions do not slow down /sessions.
1248
- const sessionsRoot = path.join(this.agentDir, 'sessions');
1249
- let dirNames = [];
1250
- try {
1251
- dirNames = fs
1252
- .readdirSync(sessionsRoot, { withFileTypes: true })
1253
- .filter((e) => e.isDirectory())
1254
- .map((e) => e.name);
1255
- }
1256
- catch {
1257
- return [];
1258
- }
1259
- const survivingFiles = [];
1260
- let prunedFolders = 0;
1261
- for (const dirName of dirNames) {
1262
- const dirPath = path.join(sessionsRoot, dirName);
1263
- let files;
1264
- try {
1265
- files = fs.readdirSync(dirPath).filter((f) => f.endsWith('.jsonl'));
1266
- }
1267
- catch {
1268
- continue;
1269
- }
1270
- if (files.length === 0)
1271
- continue;
1272
- // Cheap pre-filter: read ONLY the header of the first file to recover the
1273
- // authoritative cwd. All sessions in one folder share a cwd, so one header
1274
- // decides the whole folder. If the folder is not wanted in this view, skip
1275
- // it entirely (its file bodies are never read).
1276
- const probeCwd = resolveSessionCwd(readSessionCwdFromHeader(path.join(dirPath, files[0])));
1277
- if (probeCwd && !folderWanted(probeCwd)) {
1278
- prunedFolders++;
1279
- continue;
1280
- }
1281
- for (const f of files)
1282
- survivingFiles.push(path.join(dirPath, f));
1283
- }
1284
- const infos = [];
1285
- for (const file of survivingFiles) {
1286
- const info = buildDiskSessionInfo(file);
1287
- if (!info)
1288
- continue;
1289
- // Defensive per-session re-check (mixed/edge cases the folder probe missed).
1290
- if (!folderWanted(resolveSessionCwd(info.cwd)))
1291
- continue;
1292
- infos.push(info);
1293
- }
1294
- if (prunedFolders > 0) {
1295
- console.log(`[wherever] /sessions (${view}): skipped ${prunedFolders} folder(s) before reading file bodies`);
1296
- }
1439
+ const infos = await scanDiskSessions(path.join(this.agentDir, 'sessions'), folderWanted, `/sessions (${view})`);
1297
1440
  return this.buildFolders(infos, view === 'readonly' ? isReadOnly : undefined);
1298
1441
  }
1442
+ /**
1443
+ * Find a session on disk by short ID or name, using the same cached scan as
1444
+ * listSessions(). Replaces `SessionManager.listAll()` on this lookup path:
1445
+ * that helper re-reads and re-parses every session file, which is seconds of
1446
+ * blocking work just to resolve one deep-linked session ID.
1447
+ */
1448
+ async findDiskSessionByIdOrName(idOrName) {
1449
+ const infos = await scanDiskSessions(path.join(this.agentDir, 'sessions'), () => true, 'session lookup');
1450
+ return infos.find((s) => s.id === idOrName || s.name === idOrName);
1451
+ }
1299
1452
  /** True when the given (raw or resolved) cwd matches a sessions.readOnly glob. */
1300
1453
  isReadOnlyCwd(cwd) {
1301
1454
  const patterns = getWhereverConfig().sessions?.readOnly;
@@ -1396,7 +1549,17 @@ export class SessionPool {
1396
1549
  }
1397
1550
  return interruptedClientIds;
1398
1551
  }
1399
- async sendUserMessage(sessionFileOrId, text, streamingBehavior) {
1552
+ /**
1553
+ * Deliver a user message to a session's agent.
1554
+ *
1555
+ * `conversationMode` is the per-turn spoken-conversation SIGNAL the web client
1556
+ * stamped on the message (absent/false = off). It never touches the message
1557
+ * text: for a server session it arms the session's ConversationModeSignal (whose
1558
+ * before_agent_start hook appends the hint to THIS turn's system prompt), and for
1559
+ * a CLI-bridge session it is relayed on `cli_message` so the extension's own
1560
+ * before_agent_start hook does the same in the bridged terminal pi.
1561
+ */
1562
+ async sendUserMessage(sessionFileOrId, text, streamingBehavior, conversationMode = false) {
1400
1563
  const tracked = this.getSession(sessionFileOrId);
1401
1564
  if (!tracked)
1402
1565
  return;
@@ -1444,6 +1607,10 @@ export class SessionPool {
1444
1607
  return;
1445
1608
  }
1446
1609
  if (tracked.type === 'server') {
1610
+ // Arm (or disarm) the conversation-mode hint for the turn this message
1611
+ // starts. Set for EVERY message so the latest one always wins, and consumed
1612
+ // by the before_agent_start handler so it applies to one turn only.
1613
+ tracked.conversationSignal.arm(conversationMode);
1447
1614
  // Slash-prefixed input (/skill:<name> ..., /template ..., extension
1448
1615
  // commands) must be expanded before it reaches the model. sendUserMessage()
1449
1616
  // internally calls prompt() with expandPromptTemplates:false, so it would
@@ -1465,10 +1632,13 @@ export class SessionPool {
1465
1632
  }
1466
1633
  }
1467
1634
  else if (tracked.type === 'cli') {
1635
+ // Relay the signal to the bridged pi (omitted when off, so the payload is
1636
+ // unchanged for a non-conversation message and older extensions are fine).
1468
1637
  tracked.cliWs.send(JSON.stringify({
1469
1638
  type: 'cli_message',
1470
1639
  message: text,
1471
1640
  streamingBehavior,
1641
+ ...(conversationMode ? { conversationMode: true } : {}),
1472
1642
  }));
1473
1643
  }
1474
1644
  }