aegiscode 6.8.25 → 6.8.28

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/src/history.js CHANGED
@@ -47,8 +47,13 @@ function ensureHistoryDir() {
47
47
  * (input/output/cacheRead/cacheWrite + costUsd), stored verbatim;
48
48
  * demo — estimated from text length (~4 chars/token), labeled real:false.
49
49
  * /cost aggregates these records, so compacted-away exchanges still count.
50
+ *
51
+ * `title` is the conversation's own name (naming.js). It is written on every
52
+ * record for the session so `/resume` shows what the session is ABOUT — it used
53
+ * to show `prompt.slice(0, 60)`, the raw first message, which is a prompt and
54
+ * not a name ("heey").
50
55
  */
51
- function appendHistory({ sessionId, prompt, reply, status, usage }) {
56
+ function appendHistory({ sessionId, prompt, reply, status, usage, title }) {
52
57
  try {
53
58
  const entry = {
54
59
  ts: new Date().toISOString(),
@@ -68,6 +73,8 @@ function appendHistory({ sessionId, prompt, reply, status, usage }) {
68
73
  : { input: estimateTokens(prompt), output: estimateTokens(reply || ''), real: false },
69
74
  };
70
75
  if (usage && typeof usage.costUsd === 'number') entry.costUsd = usage.costUsd;
76
+ const clean = String(title || '').trim();
77
+ if (clean) entry.title = clean;
71
78
  return appendHistoryEntries([entry]);
72
79
  } catch (e) {
73
80
  // Persistence is best-effort; never crash the session over it.
@@ -160,7 +167,16 @@ function readOwnSessions(limit = 8) {
160
167
  const entries = readEntries();
161
168
  const byId = new Map();
162
169
  for (const e of entries) {
163
- if (!byId.has(e.sessionId)) byId.set(e.sessionId, e);
170
+ const cur = byId.get(e.sessionId);
171
+ if (!cur) {
172
+ byId.set(e.sessionId, e);
173
+ continue;
174
+ }
175
+ // Prefer a record that carries the conversation's name — naming lands one
176
+ // model round after the first exchange is persisted, so the newest record
177
+ // is not necessarily the titled one. Failing that, the newest wins.
178
+ if (!cur.title && e.title) byId.set(e.sessionId, e);
179
+ else if (!cur.title === !e.title && String(e.ts) > String(cur.ts)) byId.set(e.sessionId, e);
164
180
  }
165
181
  const items = [...byId.values()]
166
182
  .sort((a, b) => (a.ts < b.ts ? 1 : -1))
@@ -168,7 +184,10 @@ function readOwnSessions(limit = 8) {
168
184
  .map((e) => ({
169
185
  id: e.sessionId,
170
186
  cwd: (e.cwd || '').split('/').filter(Boolean).pop() || '~',
171
- summary: (e.prompt || '').slice(0, 60),
187
+ // The conversation's own name when it has one (naming.js), else the old
188
+ // raw-prompt fallback so a session recorded before naming existed is
189
+ // still identifiable.
190
+ summary: (e.title || e.prompt || '').slice(0, 60),
172
191
  time: e.ts,
173
192
  own: true,
174
193
  }));
@@ -212,6 +231,67 @@ function sessionHistoryEntries(sessionId) {
212
231
  return readEntries().filter((e) => e.sessionId === sessionId);
213
232
  }
214
233
 
234
+ /**
235
+ * Stamp a conversation's name onto every record this session already has.
236
+ *
237
+ * Naming is one model round, run off the critical path, so it usually lands
238
+ * *after* the first exchange was written to history.jsonl. Without this the
239
+ * resume list would show the raw first prompt for the rest of the session's
240
+ * life, because readOwnSessions() would find no `title` anywhere.
241
+ *
242
+ * Best-effort, like every other writer here: a failed rewrite costs a name in a
243
+ * picker, never a turn. Records are rewritten to the same 0600 file via
244
+ * securefs, and only the session's own lines are touched.
245
+ */
246
+ function setSessionTitle(sessionId, title) {
247
+ const clean = String(title || '').trim();
248
+ if (!clean) return 0;
249
+ // The shared store is the other surface a name is read from: the desktop app
250
+ // and the MCP plugin list sessions from `sessions.json`, so a name that lived
251
+ // only in history.jsonl would name the session in `/resume` and leave it
252
+ // unnamed in the GUI. Stamped first and unconditionally — the store may hold
253
+ // this session even when the ledger does not. Best-effort, like everything
254
+ // else here.
255
+ try {
256
+ sessionStore.setTitle(aegisDir(), sessionId, clean);
257
+ } catch {
258
+ /* the store is optional; the ledger below is the CLI's own */
259
+ }
260
+ try {
261
+ const p = historyPath();
262
+ if (!fs.existsSync(p)) return 0;
263
+ let touched = 0;
264
+ const out = fs
265
+ .readFileSync(p, 'utf8')
266
+ .split('\n')
267
+ .map((l) => l.trim())
268
+ .filter(Boolean)
269
+ .map((l) => {
270
+ try {
271
+ const j = JSON.parse(l);
272
+ if (j.sessionId !== sessionId || j.title === clean) return l;
273
+ j.title = clean;
274
+ touched++;
275
+ return JSON.stringify(j);
276
+ } catch {
277
+ return l;
278
+ }
279
+ });
280
+ if (!touched) return 0;
281
+ writePrivateFile(p, out.join('\n') + '\n');
282
+ return touched;
283
+ } catch (e) {
284
+ if (process.env.AEGIS_HIST_DEBUG) console.error('[history] title write failed:', e);
285
+ return 0;
286
+ }
287
+ }
288
+
289
+ /** The conversation's name, if any record for it carries one. */
290
+ function readSessionTitle(sessionId) {
291
+ const hit = readEntries().find((e) => e.sessionId === sessionId && e.title);
292
+ return hit ? String(hit.title) : '';
293
+ }
294
+
215
295
  /**
216
296
  * Drop every history record for a session. /clear
217
297
  * calls this so /cost stops summing old rows — the sessionId stays stable, so
@@ -312,4 +392,6 @@ module.exports = {
312
392
  pruneSessionHistory,
313
393
  aggregateSessionUsage,
314
394
  readResumeList,
395
+ setSessionTitle,
396
+ readSessionTitle,
315
397
  };
package/src/keys.js CHANGED
@@ -42,6 +42,8 @@ const KEY = Object.freeze({
42
42
  CTRL_N: 'ctrl-n',
43
43
  CTRL_P: 'ctrl-p',
44
44
  CTRL_O: 'ctrl-o',
45
+ CTRL_V: 'ctrl-v',
46
+ CTRL_B: 'ctrl-b',
45
47
  CTRL_LEFT: 'ctrl-left',
46
48
  CTRL_RIGHT: 'ctrl-right',
47
49
  });
@@ -80,6 +82,16 @@ function decodePlain(chunk) {
80
82
  return { name: KEY.CTRL_P };
81
83
  case '\x0f':
82
84
  return { name: KEY.CTRL_O };
85
+ // Ctrl+V pastes the clipboard (image → a saved path, else its text) and
86
+ // Ctrl+B copies the whole conversation. Both were dead letters here: `\x16`
87
+ // and `\x02` fell into the "any other control char" branch below and
88
+ // decoded as ESC — so Ctrl+V did nothing on every platform, and Ctrl+B
89
+ // aborted a running turn. The upstream engine names both keys; this host
90
+ // now does too.
91
+ case '\x16':
92
+ return { name: KEY.CTRL_V };
93
+ case '\x02':
94
+ return { name: KEY.CTRL_B };
83
95
  case '\x7f':
84
96
  case '\x08':
85
97
  return { name: KEY.BACKSPACE };
package/src/naming.js ADDED
@@ -0,0 +1,226 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Naming a conversation, with the model — the CLI's half of what the engine
5
+ * ships as `generateTitle()` in `aegiscodex-dev/src/backend.js`.
6
+ *
7
+ * What the CLI had before this module: `title.js`, which derives the terminal
8
+ * title *locally* from the user's own words (`topicFrom`), and `/resume`, which
9
+ * lists sessions by `(e.prompt || '').slice(0, 60)` — the raw first message,
10
+ * truncated. So a session was called "heey" in the tab bar and "heey" in the
11
+ * picker, which is a prompt, not a name.
12
+ *
13
+ * This is the ladder the engine settled on, in order:
14
+ *
15
+ * 1. topicless first message (a greeting) → GENERIC_TITLE, and NO model call.
16
+ * Asking just makes the model echo the prompt back ("heey" → "Heey
17
+ * There"), so it is both cheaper and more deterministic to answer locally.
18
+ * 2. the session's own model, one no-tool round, asked to name the
19
+ * conversation (2–6 words, never the user's words verbatim).
20
+ * 3. a purely local derivation from the prompt (capitalized head, stopwords
21
+ * trimmed) when no model answered.
22
+ *
23
+ * Two guarantees carry over from the engine, and both are load-bearing:
24
+ *
25
+ * · a title that merely echoes the prompt ("fix bug" → "Fix The Bug") is not a
26
+ * name — it is replaced by GENERIC_TITLE, and the caller keeps re-asking on
27
+ * later turns until a real topic lands. That is what makes a session named
28
+ * after a greeting get its real name once the user says what they want.
29
+ * · naming is best-effort and never on the critical path: `nameConversation`
30
+ * resolves (never throws) and its caller is free to ignore the result.
31
+ *
32
+ * The model round is *injected* (`callModel`), not spawned here: the CLI's own
33
+ * turn path already knows how to talk to whichever backend the session uses
34
+ * (pooled, BYOK or the reference CLI), and a naming round must not become a
35
+ * second, differently-authenticated client.
36
+ *
37
+ * Ported from aegiscodex-dev/src/backend.js (TITLE_SYSTEM, isTopicless,
38
+ * looksLikeEcho, deriveTitle, titleModelChain) so a terminal session and a
39
+ * desktop thread are named by the same rules.
40
+ */
41
+
42
+ /** The name a conversation gets before it has a topic. Deliberately generic and
43
+ * deliberately NOT the raw prompt — the whole point is that "heey" is not a
44
+ * name, and the caller re-asks until a real one lands. */
45
+ const GENERIC_TITLE = 'New conversation';
46
+
47
+ const TITLE_SYSTEM =
48
+ 'You name conversations. Write a short descriptive title (2 to 6 words) that captures the topic of the conversation. Never repeat the user\'s words verbatim — if the message is just a greeting or has no clear topic, name it something like "New conversation". Sentence case, no quotes, no markdown, no trailing punctuation, no explanation.';
49
+
50
+ const isGenericTitle = (t) => !t || String(t).trim().toLowerCase() === GENERIC_TITLE.toLowerCase();
51
+
52
+ // A greeting / topicless first message has no topic to name — asking the model
53
+ // just makes it echo the prompt back ("heey" -> "Heey There"). Detect those up
54
+ // front and skip the round entirely: it is cheaper and deterministic.
55
+ const GREETINGS = new Set([
56
+ 'hey', 'heey', 'heyy', 'heyyy', 'hi', 'hii', 'hello', 'hej', 'hejj', 'yo',
57
+ 'sup', 'hola', 'howdy', 'hai', 'heyo', 'hiya', 'wassup', 'greetings',
58
+ 'namaste', 'ahoy', 'hallo',
59
+ ]);
60
+
61
+ function isTopicless(raw) {
62
+ const p = String(raw).trim().toLowerCase().replace(/[^a-z0-9\s]/g, ' ').replace(/\s+/g, ' ').trim();
63
+ if (!p) return true;
64
+ const words = p.split(' ');
65
+ if (/^(good (morning|afternoon|evening)|whats up|wassup|hey there|hello there|hi there|how are you)\b/.test(p)) return true;
66
+ // A lone greeting word, or a short greeting phrase (<=2 words, <=12 chars)
67
+ // whose first word is a greeting, has no discernible topic.
68
+ return words.length <= 2 && p.length <= 12 && GREETINGS.has(words[0]);
69
+ }
70
+
71
+ /** The model sometimes still echoes a short prompt despite the instruction
72
+ * ("fix bug" -> "Fix The Bug"). That is not a rename; treat it as topicless. */
73
+ function looksLikeEcho(title, prompt) {
74
+ const norm = (s) => String(s).toLowerCase().replace(/[^a-z0-9\s]/g, '').replace(/\s+/g, ' ').trim();
75
+ const t = norm(title);
76
+ const p = norm(prompt);
77
+ if (!t || !p) return false;
78
+ if (t === p) return true;
79
+ // Short prompt that the title merely prefixes with a trivial continuation.
80
+ if (p.length <= 14 && (t.startsWith(p) || p.startsWith(t))) return true;
81
+ // …and the rule the engine's own comment names but its test misses. The
82
+ // engine compares raw prefixes, so its documented example — "fix bug" ->
83
+ // "Fix The Bug" — slips through: the model inserted "the", `t.startsWith(p)`
84
+ // is false, and the session keeps a title that is just the prompt again.
85
+ // Compare the CONTENT words instead (function words dropped on both sides),
86
+ // for short prompts only, where the risk of discarding a genuine title is
87
+ // negligible and the benefit is the case the rule exists for.
88
+ if (p.length <= 24) {
89
+ const words = (s) => new Set((String(s).toLowerCase().match(/[a-z0-9]+/g) || []).filter((w) => !ECHO_STOP.has(w)));
90
+ const a = words(title);
91
+ const b = words(prompt);
92
+ if (a.size && a.size === b.size && [...a].every((w) => b.has(w))) return true;
93
+ }
94
+ return false;
95
+ }
96
+
97
+ /** Function words that carry no topic, dropped before the echo comparison. */
98
+ const ECHO_STOP = new Set([
99
+ 'the', 'a', 'an', 'to', 'of', 'in', 'on', 'at', 'for', 'and', 'or', 'is',
100
+ 'are', 'be', 'it', 'its', 'my', 'our', 'please', 'can', 'you', 'just', 'do',
101
+ 'that', 'this',
102
+ ]);
103
+
104
+ /** One-line cleanup of whatever the model answered: no quotes, no markdown, no
105
+ * trailing punctuation, clipped. '' means "unusable".
106
+ *
107
+ * Order matters: a model asked not to quote often answers `"Title: Fixing the
108
+ * slow request."` anyway, and stripping the label prefix BEFORE the quotes
109
+ * leaves it in place (the `^` never sees past the opening quote) — measured.
110
+ * Quotes and markdown come off first, then the label. */
111
+ function cleanTitle(raw) {
112
+ return String(raw == null ? '' : raw)
113
+ .replace(/\s+/g, ' ')
114
+ .trim()
115
+ .replace(/["'`“”‘’]/g, '')
116
+ .replace(/[*_#]/g, '')
117
+ .replace(/^\s*(?:title|name)\s*[:\-–]\s*/i, '')
118
+ .replace(/[.\s]+$/g, '')
119
+ .slice(0, 60)
120
+ .trim();
121
+ }
122
+
123
+ /** The naming instruction the model is asked to answer (never the user's task). */
124
+ const titlePromptOf = (prompt) =>
125
+ `Write a short title for a conversation that begins with: "${String(prompt).slice(0, 500)}"`;
126
+
127
+ /**
128
+ * Politeness and throat-clearing, stripped from the front of a prompt, so the
129
+ * fallback name says "Do the thing" instead of "Please Can You Just Do". Same
130
+ * list `title.js` uses for the terminal topic — one habit, stripped once.
131
+ */
132
+ const FILLER =
133
+ /^(?:please|pls|plz|hey|hi|hello|ok(?:ay)?|so|now|just|also|and|then|maybe|well|um|uh|can you|could you|would you|will you|i want you to|i want to|i need you to|i need to|i'?d like you to|i would like you to|i'?d like to|help me|help|let'?s|lets|go ahead and)\b[\s,:;-]*/i;
134
+
135
+ /** Words that carry no topic when trimming the tail of a derived name. */
136
+ const TRAILING_STOP = new Set([
137
+ 'the', 'a', 'an', 'in', 'on', 'at', 'to', 'for', 'of', 'and', 'or', 'with',
138
+ 'is', 'are', 'my', 'our', 'this', 'that', 'please', 'can', 'you', 'could',
139
+ 'would', 'i', 'we', 'just', 'do', 'it',
140
+ ]);
141
+
142
+ /**
143
+ * Last rung: a name derived from the prompt, used only when no model answered.
144
+ * Never the bare product name, and never the raw prompt verbatim.
145
+ *
146
+ * Sentence case, not Title Case: that is what TITLE_SYSTEM asks the model for,
147
+ * so the fallback matches the names around it. (The engine's derivation
148
+ * capitalizes every word — "Add A Retry To The Fetcher" — which reads like a
149
+ * heading next to the model's own answers.)
150
+ */
151
+ function deriveTitle(prompt) {
152
+ let body = String(prompt == null ? '' : prompt).trim().replace(/\s+/g, ' ');
153
+ if (!body) return GENERIC_TITLE;
154
+ for (let i = 0; i < 6; i++) {
155
+ const next = body.replace(FILLER, '').trim();
156
+ if (next === body) break;
157
+ body = next;
158
+ }
159
+ const words = body.split(' ').filter(Boolean);
160
+ if (!words.length) return GENERIC_TITLE;
161
+ const head = words.slice(0, 6);
162
+ while (head.length > 2 && TRAILING_STOP.has(head[head.length - 1].toLowerCase().replace(/[^a-z0-9]/g, ''))) head.pop();
163
+ let out = head.join(' ').replace(/[.,!?;:]+$/, '').trim();
164
+ if (!out) return GENERIC_TITLE;
165
+ out = out[0].toUpperCase() + out.slice(1);
166
+ return out.slice(0, 60).trim() || GENERIC_TITLE;
167
+ }
168
+
169
+ /**
170
+ * Name a conversation from its first user prompt.
171
+ *
172
+ * `callModel(prompt)` (async) is the caller's own model seam and must return a
173
+ * string (or null). With no `callModel` — demo mode, or a caller that has no
174
+ * backend — it answers from the local derivation, exactly like the engine's
175
+ * `generateTitle` falls back through its chain. Never throws; resolves '' only
176
+ * when there was no prompt at all (the caller keeps whatever it had).
177
+ *
178
+ * `{ signal }` is honoured between rounds and passed through, so aborting a turn
179
+ * abandons a naming round in flight rather than leaving it running.
180
+ */
181
+ async function nameConversation(prompt, { callModel, signal } = {}) {
182
+ const raw = prompt == null ? '' : String(prompt);
183
+ if (!raw.trim()) return '';
184
+ if (isTopicless(raw)) return GENERIC_TITLE;
185
+ if (typeof callModel === 'function' && !(signal && signal.aborted)) {
186
+ let answer = null;
187
+ try {
188
+ answer = await callModel(titlePromptOf(raw), { system: TITLE_SYSTEM, signal, naming: true });
189
+ } catch {
190
+ answer = null;
191
+ }
192
+ const title = cleanTitle(answer);
193
+ if (title) return looksLikeEcho(title, raw) ? GENERIC_TITLE : title;
194
+ }
195
+ return deriveTitle(raw);
196
+ }
197
+
198
+ /**
199
+ * The title a session should carry after a later prompt, given the one it has.
200
+ *
201
+ * While the session is still wearing GENERIC_TITLE (the user opened with "heey"
202
+ * and has now said what they actually want) the next real ask renames it; once a
203
+ * real title exists it is kept, so a follow-up does not rename a session away
204
+ * from its topic. `null` means "no opinion, keep what you have".
205
+ */
206
+ async function refineTitle(currentTitle, prompt, opts = {}) {
207
+ if (!isGenericTitle(currentTitle)) return null;
208
+ if (!String(prompt || '').trim() || isTopicless(prompt)) return null;
209
+ const next = await nameConversation(prompt, opts);
210
+ const cleaned = cleanTitle(next);
211
+ if (!cleaned || isGenericTitle(cleaned)) return null;
212
+ return cleaned;
213
+ }
214
+
215
+ module.exports = {
216
+ GENERIC_TITLE,
217
+ TITLE_SYSTEM,
218
+ isGenericTitle,
219
+ isTopicless,
220
+ looksLikeEcho,
221
+ cleanTitle,
222
+ titlePromptOf,
223
+ deriveTitle,
224
+ nameConversation,
225
+ refineTitle,
226
+ };
@@ -438,6 +438,97 @@ function hasDisplay(options = {}) {
438
438
  // homeDir / resolvePath
439
439
  // ---------------------------------------------------------------------------
440
440
 
441
+ /**
442
+ * Normalise anything a machine calls a locale into a BCP-47 `ll` / `ll-CC`
443
+ * code, or `''` for "no answer".
444
+ *
445
+ * Four spellings reach this function and only the first is already usable:
446
+ * `sv-SE`, the POSIX `sv_SE.UTF-8` (and `sv_SE.utf8`, `sv_SE`), the GNU
447
+ * `LANGUAGE` list (`sv:en:de` — the caller splits it), and the two settings
448
+ * that mean NOT a language: `C` and `POSIX`, which say "no locale configured"
449
+ * and must never render as a language called "c". The modifier tail
450
+ * (`@euro`, `@latin`) is dropped: it changes collation, not language.
451
+ */
452
+ function normalizeLocale(value) {
453
+ if (value == null) return '';
454
+ const raw = String(value).trim();
455
+ if (!raw) return '';
456
+ const head = raw.split('@')[0].split('.')[0];
457
+ if (/^(c|posix)$/i.test(head)) return '';
458
+ const m = /^([A-Za-z]{2,3})(?:[_-]([A-Za-z0-9]{2,8}))?$/.exec(head);
459
+ if (!m) return '';
460
+ const lang = m[1].toLowerCase();
461
+ if (lang === 'c' || lang === 'posix') return '';
462
+ return m[2] ? `${lang}-${m[2].toUpperCase()}` : lang;
463
+ }
464
+
465
+ /**
466
+ * The language the user's own machine and account run in — `''` when nothing
467
+ * can say.
468
+ *
469
+ * The model has always been told the platform, the home directory and the real
470
+ * Desktop path, but never this, so a Swedish user's DeepSeek turn started with
471
+ * no field saying the machine is Swedish: the model mirrored whatever language
472
+ * arrived in the message and defaulted to the prompt's English otherwise.
473
+ * Mirrored language is not the same as known language — an up-front
474
+ * `locale: sv-SE` is what lets it answer a Swedish one-word request ("städa")
475
+ * in Swedish instead of asking which language to use.
476
+ *
477
+ * POSIX order is the order below (`LC_ALL` overrides `LC_CTYPE` overrides
478
+ * `LC_MESSAGES` overrides `LANG`); `LANGUAGE` is a GNU preference LIST and is
479
+ * consulted last only for its first entry. Windows sets none of these, and
480
+ * macOS sets none of them for an app launched from Finder, so `Intl` is the
481
+ * fallback — it reads the ICU default the runtime was started with, which is
482
+ * the same answer the OS gives the app. An `env` the caller INJECTED is trusted
483
+ * as given (never topped up from `Intl`), which is what makes a test with
484
+ * `env: {}` deterministic instead of dependent on the CI runner's locale.
485
+ */
486
+ function appLocale(options = {}) {
487
+ const { platform, env, o } = seams(options);
488
+ if (typeof o.locale === 'string') return normalizeLocale(o.locale);
489
+ const injected = o.env && typeof o.env === 'object';
490
+ for (const key of ['LC_ALL', 'LC_CTYPE', 'LC_MESSAGES', 'LANG']) {
491
+ const hit = normalizeLocale(envValue(env, key, platform));
492
+ if (hit) return hit;
493
+ }
494
+ const list = String(envValue(env, 'LANGUAGE', platform) || '');
495
+ if (list) {
496
+ // A colon list is a PREFERENCE order, and an empty field in it (":de" — how
497
+ // a launch script that cleared the first entry leaves it) means "skip this
498
+ // one", not "the answer is nothing".
499
+ for (const part of list.split(':')) {
500
+ const first = normalizeLocale(part);
501
+ if (first) return first;
502
+ }
503
+ }
504
+ if (injected) return ''; // the caller owns the environment; it said nothing
505
+ try {
506
+ return normalizeLocale(new Intl.DateTimeFormat().resolvedOptions().locale);
507
+ } catch {
508
+ return '';
509
+ }
510
+ }
511
+
512
+ /**
513
+ * The English name of a language code — `Swedish` for `sv`, `''` when the
514
+ * runtime has no display table for it (Node without full ICU). Named in
515
+ * ENGLISH on purpose: it is interpolated into the English system prompt, so a
516
+ * Swedish host must not render it as "svenska".
517
+ */
518
+ function languageName(code, options = {}) {
519
+ const { o } = seams(options);
520
+ if (typeof o.languageName === 'string') return o.languageName;
521
+ const hit = normalizeLocale(code);
522
+ if (!hit) return '';
523
+ const base = hit.split('-')[0];
524
+ try {
525
+ const display = new Intl.DisplayNames(['en'], { type: 'language' });
526
+ return display.of(base) || '';
527
+ } catch {
528
+ return '';
529
+ }
530
+ }
531
+
441
532
  /**
442
533
  * This user's home directory, `''` when nothing can say what it is.
443
534
  *
@@ -628,6 +719,36 @@ function desktopDir(options = {}) {
628
719
  return '';
629
720
  }
630
721
 
722
+ /**
723
+ * If `work` names this user's home "Desktop" folder by its generic literal
724
+ * name — the one a model guesses, in English, regardless of locale or
725
+ * OneDrive redirection — rewrite it to the REAL desktop directory the caller
726
+ * already asked Windows/XDG for (`desktopDir()` above).
727
+ *
728
+ * The environment preamble already NAMES the real directory and tells the
729
+ * model to copy it verbatim rather than build it — but that is advisory, and
730
+ * a model that still writes `~/Desktop/notes.txt` was silently creating (and
731
+ * reporting success into) a spurious English "Desktop" folder next to the
732
+ * user's real one, which on a redirected or localised Windows session is a
733
+ * different, empty directory the user never sees. This is the opposite of
734
+ * desktopDir()'s own job: that function stops US from guessing a locale name;
735
+ * this stops a model's literal "Desktop" guess from winning when we were
736
+ * already told the real answer.
737
+ *
738
+ * No-op when no `desktopdir` was supplied, when it is simply `home/Desktop`
739
+ * (nothing to correct), or when `work` is not rooted at the guessed path.
740
+ */
741
+ function applyDesktopAlias(work, { home, desktopdir, win32, P }) {
742
+ if (!home || !desktopdir) return work;
743
+ const guessed = P.join(home, 'Desktop');
744
+ const fold = (s) => (win32 ? s.toLowerCase() : s);
745
+ if (fold(guessed) === fold(desktopdir)) return work;
746
+ if (fold(work) === fold(guessed)) return desktopdir;
747
+ const prefix = guessed + P.sep;
748
+ if (fold(work).startsWith(fold(prefix))) return desktopdir + P.sep + work.slice(prefix.length);
749
+ return work;
750
+ }
751
+
631
752
  /** `C:\…` / `C:/…` — a drive-qualified Windows path. */
632
753
  const WIN_DRIVE_RE = /^[A-Za-z]:[\\/]/;
633
754
  /** `C:` with nothing after it — drive-relative, and never what a model means. */
@@ -703,6 +824,12 @@ function resolvePath(input, options = {}) {
703
824
  );
704
825
  }
705
826
 
827
+ // ── the desktop alias ─────────────────────────────────────────────────────
828
+ // Runs before the wrong-OS check below because a corrected `work` is always
829
+ // native by construction (desktopDir() returns a real path for THIS
830
+ // platform), exactly like a `~` expansion already is.
831
+ work = applyDesktopAlias(work, { home: homeDir(options), desktopdir: o.desktopdir, win32, P });
832
+
706
833
  // ── absolute-for-the-wrong-OS ─────────────────────────────────────────────
707
834
  // Skipped after a `~` expansion: that result is native by construction.
708
835
  if (!expandedHome) {
@@ -755,6 +882,9 @@ const api = {
755
882
  desktopDir,
756
883
  resolvePath,
757
884
  hasPosixModes,
885
+ appLocale,
886
+ languageName,
887
+ normalizeLocale,
758
888
  };
759
889
 
760
890
  module.exports = api;
@@ -288,6 +288,31 @@ function recordExchange(dir, exchange) {
288
288
  });
289
289
  }
290
290
 
291
+ /**
292
+ * Stamp a conversation's name.
293
+ *
294
+ * The name is what the session LIST shows (the desktop app, the MCP plugin and
295
+ * `/resume` all read it from here or from their own mirror), and it is NOT the
296
+ * raw first message: `recordExchange` seeds `title` with the prompt so a
297
+ * session has something to show before anything has named it, and this replaces
298
+ * that seed with the real name once one exists (the CLI's `naming.js`).
299
+ *
300
+ * An empty name is refused rather than written: a namer that failed must not
301
+ * blank a name that is already there.
302
+ */
303
+ function setTitle(dir, sessionId, title) {
304
+ const clean = String(title == null ? '' : title).trim().slice(0, 200);
305
+ if (!sessionId || !clean) return null;
306
+ return mutate(dir, (sessions) => {
307
+ const session = sessions[sessionId];
308
+ if (!session) return null;
309
+ session.title = clean;
310
+ session.updatedAt = Date.now();
311
+ session.seq = nextSeq(sessions);
312
+ return session;
313
+ });
314
+ }
315
+
291
316
  function listSessions(dir) {
292
317
  const sessions = load(dir);
293
318
  return Object.values(sessions)
@@ -389,10 +414,15 @@ function listSummaries(dir, limit = 8) {
389
414
  .map((s) => {
390
415
  const messages = Array.isArray(s.messages) ? s.messages : [];
391
416
  const first = messages.find((m) => m && m.role === 'user');
417
+ // A named session lists by its name. `title` is seeded from the prompt at
418
+ // record time, so for an unnamed session this is the same string the
419
+ // first message would have produced — no visible change — while a real
420
+ // name (setTitle) wins over the raw prompt, which is the whole point of
421
+ // naming a conversation.
392
422
  return {
393
423
  id: s.id,
394
424
  cwd: (s.cwd || '').split(/[\\/]/).filter(Boolean).pop() || '~',
395
- summary: String((first && first.content) || s.title || '').slice(0, 60),
425
+ summary: String(s.title || (first && first.content) || '').slice(0, 60),
396
426
  time: new Date(s.updatedAt || Date.now()).toISOString(),
397
427
  own: true,
398
428
  origin: s.origin || 'unknown',
@@ -499,6 +529,7 @@ module.exports = {
499
529
  upsertSession,
500
530
  appendMessage,
501
531
  recordExchange,
532
+ setTitle,
502
533
  listSessions,
503
534
  getSession,
504
535
  deleteSession,