@causyne/agent 1.20.118 → 1.20.121

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 (101) hide show
  1. package/package.json +1 -1
  2. package/src/agent/errorClassifier.js +113 -0
  3. package/src/agent/errorClassifier.ts +161 -0
  4. package/src/agent/promptIntent.js +200 -0
  5. package/src/agent/promptIntent.ts +203 -0
  6. package/src/agent/toolArgValidator.js +97 -0
  7. package/src/agent/toolArgValidator.ts +112 -0
  8. package/src/agentLoop.js +51 -351
  9. package/src/agentLoop.ts +69 -363
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/browser/causyneBrowser.js +231 -136
  13. package/src/browser/causyneBrowser.ts +229 -140
  14. package/src/browser/searchProviders.js +41 -30
  15. package/src/browser/searchProviders.ts +24 -14
  16. package/src/browser/workspacePathSafety.js +50 -0
  17. package/src/browser/workspacePathSafety.ts +50 -0
  18. package/src/browser/workspacePreview.js +27 -4
  19. package/src/browser/workspacePreview.ts +28 -4
  20. package/src/cliMode.js +17 -3
  21. package/src/commands.js +15 -22
  22. package/src/config.js +42 -63
  23. package/src/configVault.js +204 -0
  24. package/src/configVault.ts +213 -0
  25. package/src/core/contextCompactor.js +70 -11
  26. package/src/core/contextCompactor.ts +83 -11
  27. package/src/creative/liveBridge.js +34 -1
  28. package/src/creative/liveBridge.ts +28 -1
  29. package/src/dynamicCatalogue.js +42 -73
  30. package/src/dynamicCatalogue.ts +74 -60
  31. package/src/entrypoint.js +77 -4
  32. package/src/headlessCli.js +304 -0
  33. package/src/headlessCli.ts +380 -0
  34. package/src/mcp/mcpClient.js +38 -11
  35. package/src/mcp/mcpClient.ts +44 -11
  36. package/src/mcp/mcpRegistry.js +2 -5
  37. package/src/mcp/mcpRegistry.ts +2 -5
  38. package/src/mcp/mcpSecurity.js +189 -0
  39. package/src/mcp/mcpSecurity.ts +190 -0
  40. package/src/observer/evidence.js +23 -0
  41. package/src/observer/evidence.ts +21 -0
  42. package/src/osKeychain.js +209 -0
  43. package/src/osKeychain.ts +245 -0
  44. package/src/providers/anthropic.js +61 -28
  45. package/src/providers/base.js +14 -0
  46. package/src/providers/byokHttp.js +354 -0
  47. package/src/providers/byokHttp.ts +454 -0
  48. package/src/providers/byokStream.js +657 -0
  49. package/src/providers/byokStream.ts +759 -0
  50. package/src/providers/dashscope-byok.js +47 -32
  51. package/src/providers/deepseek.js +43 -39
  52. package/src/providers/gemini.js +73 -38
  53. package/src/providers/moonshot.js +43 -33
  54. package/src/providers/muse.js +10 -10
  55. package/src/providers/ollama.js +46 -31
  56. package/src/providers/openai-compatible.js +57 -32
  57. package/src/providers/openrouter.js +77 -113
  58. package/src/providers/openrouter.ts +99 -118
  59. package/src/providers/qwen-byok.js +46 -23
  60. package/src/providers/toolContracts.js +9 -3
  61. package/src/providers/toolContracts.ts +9 -3
  62. package/src/providers/wireNormalizer.js +238 -0
  63. package/src/providers/wireNormalizer.ts +279 -0
  64. package/src/providers/xai.js +43 -33
  65. package/src/sandbox.js +77 -56
  66. package/src/sandboxPolicy.js +1208 -0
  67. package/src/sandboxPolicy.ts +1300 -0
  68. package/src/sessionJournal.js +47 -0
  69. package/src/sessionJournal.ts +49 -0
  70. package/src/tools/browserAutomator.js +13 -1
  71. package/src/tools/browserAutomator.ts +13 -0
  72. package/src/tools/creativeApps.js +2 -1
  73. package/src/tools/creativeApps.ts +2 -1
  74. package/src/tools/gameAssetFetcher.js +130 -26
  75. package/src/tools/gameAssetHarvester.js +80 -58
  76. package/src/tools/nativeEngine.js +1 -1
  77. package/src/tools/nativeEngine.ts +1 -1
  78. package/src/tools/osSandbox.js +473 -0
  79. package/src/tools/osSandbox.ts +554 -0
  80. package/src/tools/persistentShell.js +8 -3
  81. package/src/tools/registry.js +13 -0
  82. package/src/tools/subprocessEnv.js +197 -0
  83. package/src/tools/subprocessEnv.ts +212 -0
  84. package/src/tools/sysRun.js +39 -6
  85. package/src/tools/sysRun.ts +53 -7
  86. package/src/tools/toolScanner.js +596 -140
  87. package/src/tools/toolScanner.ts +665 -147
  88. package/src/tools/toolSelfRepair.js +243 -114
  89. package/src/tools/toolSelfRepair.ts +262 -111
  90. package/src/tools/webFetch.js +161 -24
  91. package/src/tools/webFetch.ts +157 -22
  92. package/src/tools/webSearch.js +33 -4
  93. package/src/tools/webSearch.ts +27 -4
  94. package/src/tui/sessionPicker.js +132 -35
  95. package/src/tui/sessionPicker.ts +153 -32
  96. package/src/tui/sessionPickerView.js +277 -34
  97. package/src/tui/sessionPickerView.ts +328 -34
  98. package/src/tui/statusLine.js +3 -0
  99. package/src/tui/statusLine.ts +5 -0
  100. package/src/tui/workspaceIdentity.js +133 -0
  101. package/src/tui/workspaceIdentity.ts +146 -0
@@ -1,14 +1,20 @@
1
1
  /**
2
- * Causyne Agent /sessions: session-specific presentation on the existing modal stack.
3
- * No changes to the session store, approval policy or the shared SelectList.
2
+ * Causyne Agent /sessions: workspace-aware session presentation on the existing modal stack.
3
+ * Preserves the date-grouped placement algorithm while elevating the active workspace's
4
+ * sessions (or an explicit Empty state) above deduplicated All Sessions.
4
5
  */
5
- import path from 'node:path';
6
6
  // @ts-expect-error The existing dialog component is authored in JavaScript.
7
7
  import { SelectLayer } from './dialogs.js';
8
8
  // @ts-expect-error The theme is authored in JavaScript.
9
9
  import { bold, dim, paint, GLYPHS } from './theme.js';
10
10
  import { safeDisplay, truncate, visibleWidth } from './text.js';
11
- import type { SessionPickerItem } from './sessionPicker.js';
11
+ import {
12
+ sameWorkspace,
13
+ workspaceDisplayName,
14
+ shortenWorkspacePath,
15
+ formatWorkspaceSectionTitle
16
+ } from './workspaceIdentity.js';
17
+ import type { SessionPickerItem, SessionPickerSection } from './sessionPicker.js';
12
18
 
13
19
  export interface SessionPickerViewOptions {
14
20
  items: SessionPickerItem[];
@@ -17,6 +23,15 @@ export interface SessionPickerViewOptions {
17
23
  onPick: (item: SessionPickerItem | null) => void;
18
24
  }
19
25
 
26
+ export interface RenderSessionRowsOptions {
27
+ currentWorkspace?: string | undefined;
28
+ workspaceCount?: number | undefined;
29
+ otherCount?: number | undefined;
30
+ scope?: SessionScope | undefined;
31
+ isSearching?: boolean | undefined;
32
+ canonicalCache?: Map<string, string> | undefined;
33
+ }
34
+
20
35
  type SessionScope = 'all' | 'workspace';
21
36
  type Key = { name?: string; ctrl?: boolean; sequence?: string; text?: string } | null;
22
37
 
@@ -28,16 +43,10 @@ function clean(value: unknown): string {
28
43
  return safeDisplay(typeof value === 'string' ? value : String(value ?? '')).replace(/[\r\n]+/g, ' ');
29
44
  }
30
45
 
31
- function sameWorkspace(first: string | undefined, second: string): boolean {
32
- if (!first || !second) return false;
33
- const a = path.resolve(first);
34
- const b = path.resolve(second);
35
- return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
36
- }
37
-
38
46
  function rowPair(left: string, right: string, width: number): string {
39
47
  const room = Number.isFinite(width) ? Math.max(0, Math.floor(width)) : 60;
40
48
  const rightWidth = visibleWidth(right);
49
+ if (rightWidth === 0) return truncate(left, room, '…');
41
50
  if (rightWidth >= room - 5) return truncate(left, room, '…');
42
51
  const safeLeft = truncate(left, Math.max(0, room - rightWidth - 2), '…');
43
52
  return safeLeft + ' '.repeat(Math.max(1, room - visibleWidth(safeLeft) - rightWidth)) + right;
@@ -81,42 +90,277 @@ function actionOrSessionText(item: SessionPickerItem, selected: boolean, width:
81
90
  return rowPair(leftPrefix + styledName, usableRight, width);
82
91
  }
83
92
 
93
+ function resolveItemSection(
94
+ item: SessionPickerItem,
95
+ currentWorkspace?: string,
96
+ cache?: Map<string, string>
97
+ ): SessionPickerSection {
98
+ if (item.value.type !== 'switch') return 'actions';
99
+ if (item.section === 'workspace' || item.section === 'all') {
100
+ if (!currentWorkspace || item.value.workspace === undefined) return item.section;
101
+ }
102
+ if (currentWorkspace && sameWorkspace(item.value.workspace, currentWorkspace, cache)) {
103
+ return 'workspace';
104
+ }
105
+ return 'all';
106
+ }
107
+
108
+ export interface PartitionedSessionItems {
109
+ ordered: SessionPickerItem[];
110
+ workspaceCount: number;
111
+ otherCount: number;
112
+ }
113
+
114
+ /**
115
+ * Partition picker items into:
116
+ * 1. Pinned actions
117
+ * 2. Current workspace sessions (preserving date-sorted order)
118
+ * 3. All other sessions (preserving date-sorted order, strictly deduplicated)
119
+ */
120
+ export function partitionSessionPickerItems(
121
+ items: SessionPickerItem[],
122
+ currentWorkspace: string,
123
+ cache?: Map<string, string>
124
+ ): PartitionedSessionItems {
125
+ const actions: SessionPickerItem[] = [];
126
+ const workspace: SessionPickerItem[] = [];
127
+ const other: SessionPickerItem[] = [];
128
+ const seenIds = new Set<string>();
129
+
130
+ for (const raw of Array.isArray(items) ? items : []) {
131
+ if (!raw || !raw.value) continue;
132
+ const key = typeof raw.id === 'string' && raw.id ? raw.id : '';
133
+ if (key && seenIds.has(key)) continue;
134
+ if (key) seenIds.add(key);
135
+
136
+ if (raw.value.type !== 'switch') {
137
+ actions.push(raw.section === 'actions' ? raw : { ...raw, section: 'actions' });
138
+ continue;
139
+ }
140
+
141
+ const inWorkspace = sameWorkspace(raw.value.workspace, currentWorkspace, cache);
142
+ if (inWorkspace) {
143
+ workspace.push(raw.section === 'workspace' ? raw : { ...raw, section: 'workspace' });
144
+ } else {
145
+ other.push(raw.section === 'all' ? raw : { ...raw, section: 'all' });
146
+ }
147
+ }
148
+
149
+ return {
150
+ ordered: [...actions, ...workspace, ...other],
151
+ workspaceCount: workspace.length,
152
+ otherCount: other.length
153
+ };
154
+ }
155
+
84
156
  interface ListWindow { rows: string[]; lastIndex: number; }
85
157
 
86
158
  /**
87
- * Category headers are terminal rows, not selectable items. This window is
88
- * measured in *actual rows*, preventing selection disappearing at group edges.
159
+ * Section and date headers are terminal rows, not selectable items. This window is
160
+ * measured in *actual rows*, preventing orphaned headers or hidden selections at
161
+ * section and group boundaries.
89
162
  */
90
163
  export function renderSessionRows(
91
164
  entries: Array<{ item: SessionPickerItem }>,
92
165
  start: number,
93
166
  selected: number,
94
167
  width: number,
95
- budget: number
168
+ budget: number,
169
+ options?: RenderSessionRowsOptions
96
170
  ): ListWindow {
97
171
  const rows: string[] = [];
98
172
  const safeStart = Number.isFinite(start) ? Math.max(0, Math.floor(start)) : 0;
99
173
  const safeWidth = Number.isFinite(width) ? Math.max(4, Math.floor(width)) : 60;
100
174
  const safeBudget = budget === Number.POSITIVE_INFINITY
101
- ? entries.length
175
+ ? Math.max(entries.length * 4 + 6, 16)
102
176
  : (Number.isFinite(budget) ? Math.max(0, Math.floor(budget)) : 0);
177
+
178
+ if (safeBudget === 0) {
179
+ return { rows, lastIndex: safeStart - 1 };
180
+ }
181
+
182
+ const useSections = Boolean(
183
+ options?.currentWorkspace
184
+ || entries.some((entry) => entry?.item?.section !== undefined)
185
+ );
186
+
187
+ // Legacy 5-argument direct rendering without workspace sections.
188
+ if (!useSections) {
189
+ let lastIndex = safeStart - 1;
190
+ let previousCategory: string | null = null;
191
+ for (let i = safeStart; i < entries.length && rows.length < safeBudget; i++) {
192
+ const item = entries[i]!.item;
193
+ const category = clean(item.category || 'Sessions');
194
+ const isNewGroup = category !== previousCategory;
195
+ // Avoid leaving an orphaned header in the final available row.
196
+ if (isNewGroup && safeBudget - rows.length >= 2) {
197
+ rows.push(dim(` ${truncate(category.toUpperCase(), Math.max(1, safeWidth - 4), '…')}`));
198
+ } else if (isNewGroup && rows.length > 0) {
199
+ break;
200
+ }
201
+ if (rows.length >= safeBudget) break;
202
+ rows.push(actionOrSessionText(item, i === selected, safeWidth));
203
+ lastIndex = i;
204
+ previousCategory = category;
205
+ }
206
+ return { rows, lastIndex };
207
+ }
208
+
209
+ const currentWorkspace = options?.currentWorkspace;
210
+ const cache = options?.canonicalCache;
211
+ const isSearching = Boolean(options?.isSearching);
212
+
213
+ const wsCount = typeof options?.workspaceCount === 'number' && Number.isFinite(options.workspaceCount)
214
+ ? Math.max(0, Math.floor(options.workspaceCount))
215
+ : entries.filter((entry) => resolveItemSection(entry.item, currentWorkspace, cache) === 'workspace').length;
216
+ const otherCount = typeof options?.otherCount === 'number' && Number.isFinite(options.otherCount)
217
+ ? Math.max(0, Math.floor(options.otherCount))
218
+ : entries.filter((entry) => resolveItemSection(entry.item, currentWorkspace, cache) === 'all').length;
219
+
220
+ const wsDisplayName = workspaceDisplayName(currentWorkspace, cache);
221
+ const wsShortPath = currentWorkspace ? shortenWorkspacePath(currentWorkspace) : '';
222
+
223
+ const actionsHeaderRow = (): string =>
224
+ dim(` ${truncate('ACTIONS', Math.max(1, safeWidth - 4), '…')}`);
225
+
226
+ const workspaceSectionRow = (): string => {
227
+ const title = formatWorkspaceSectionTitle(currentWorkspace, wsCount, cache);
228
+ const styledLeft = ` ${bold(paint('accent', title))}`;
229
+ const leftWidth = visibleWidth(styledLeft);
230
+ const remainingForPath = safeWidth - leftWidth - 3;
231
+ let rightPath = '';
232
+ if (
233
+ safeWidth >= 52
234
+ && remainingForPath >= 12
235
+ && wsShortPath
236
+ && wsShortPath !== wsDisplayName
237
+ && wsShortPath !== '(default)'
238
+ ) {
239
+ let shownPath = wsShortPath;
240
+ if (visibleWidth(shownPath) > remainingForPath) {
241
+ const runes = Array.from(shownPath);
242
+ const budget = Math.max(1, remainingForPath - 1);
243
+ while (runes.length > 0 && visibleWidth(runes.join('')) > budget) runes.shift();
244
+ shownPath = `…${runes.join('')}`;
245
+ }
246
+ rightPath = dim(shownPath);
247
+ }
248
+ return rowPair(styledLeft, rightPath, safeWidth);
249
+ };
250
+
251
+ const workspaceEmptyRow = (): string => {
252
+ const label = safeWidth >= 46
253
+ ? 'Empty — no sessions in this workspace yet'
254
+ : 'Empty';
255
+ return dim(` ${truncate(label, Math.max(1, safeWidth - 4), '…')}`);
256
+ };
257
+
258
+ const allSessionsSectionRow = (): string => {
259
+ const title = `ALL SESSIONS (${otherCount})`;
260
+ return truncate(` ${bold(paint('ink', title))}`, safeWidth, '…');
261
+ };
262
+
263
+ const dateSubHeaderRow = (category: string): string =>
264
+ dim(` ${truncate(category.toUpperCase(), Math.max(1, safeWidth - 6), '…')}`);
265
+
266
+ const searchGroupHeaderRow = (section: SessionPickerSection, category: string): string => {
267
+ if (section === 'actions') return actionsHeaderRow();
268
+ if (section === 'workspace') {
269
+ const text = `${wsDisplayName} ${GLYPHS.dot} ${category.toUpperCase()}`;
270
+ return truncate(` ${paint('accent', text)}`, safeWidth, '…');
271
+ }
272
+ const text = `ALL SESSIONS ${GLYPHS.dot} ${category.toUpperCase()}`;
273
+ return dim(` ${truncate(text, Math.max(1, safeWidth - 4), '…')}`);
274
+ };
275
+
276
+ const shouldShowEmptyWorkspace = !isSearching && wsCount === 0;
277
+ let emptyWorkspaceEmitted = false;
103
278
  let lastIndex = safeStart - 1;
279
+ let previousSection: SessionPickerSection | null = null;
104
280
  let previousCategory: string | null = null;
281
+
105
282
  for (let i = safeStart; i < entries.length && rows.length < safeBudget; i++) {
106
283
  const item = entries[i]!.item;
107
284
  const category = clean(item.category || 'Sessions');
108
- const isNewGroup = category !== previousCategory;
109
- // Avoid leaving an orphaned header in the final available row.
110
- if (isNewGroup && safeBudget - rows.length >= 2) {
111
- rows.push(dim(` ${truncate(category.toUpperCase(), Math.max(1, safeWidth - 4), '…')}`));
112
- } else if (isNewGroup && rows.length > 0) {
285
+ const section = resolveItemSection(item, currentWorkspace, cache);
286
+
287
+ // Emit the Empty workspace block directly after Actions (or at index 0 when
288
+ // there are no Actions) before transitioning into ALL SESSIONS.
289
+ const needsEmptyWorkspaceBefore = shouldShowEmptyWorkspace
290
+ && !emptyWorkspaceEmitted
291
+ && section === 'all'
292
+ && (previousSection === 'actions' || (safeStart === 0 && i === 0));
293
+
294
+ if (needsEmptyWorkspaceBefore) {
295
+ const remainingBeforeEmpty = safeBudget - rows.length;
296
+ if (rows.length === 0 && i === selected && remainingBeforeEmpty < 3) {
297
+ // Ultra-short viewport targeting this item: never let the empty notice starve selection.
298
+ emptyWorkspaceEmitted = true;
299
+ } else if (remainingBeforeEmpty >= 2) {
300
+ rows.push(workspaceSectionRow());
301
+ rows.push(workspaceEmptyRow());
302
+ emptyWorkspaceEmitted = true;
303
+ } else if (rows.length > 0) {
304
+ break;
305
+ }
306
+ }
307
+
308
+ const pendingHeaders: string[] = [];
309
+ if (isSearching) {
310
+ if (section !== previousSection || category !== previousCategory) {
311
+ pendingHeaders.push(searchGroupHeaderRow(section, category));
312
+ }
313
+ } else {
314
+ const sectionChanged = section !== previousSection;
315
+ if (sectionChanged) {
316
+ // Reset date tracking on section change so TODAY renders cleanly under ALL SESSIONS
317
+ // even when the preceding workspace section also ended on TODAY.
318
+ previousCategory = null;
319
+ if (section === 'actions') {
320
+ pendingHeaders.push(actionsHeaderRow());
321
+ } else if (section === 'workspace') {
322
+ pendingHeaders.push(workspaceSectionRow());
323
+ } else {
324
+ pendingHeaders.push(allSessionsSectionRow());
325
+ }
326
+ }
327
+ if (section !== 'actions' && category !== previousCategory) {
328
+ pendingHeaders.push(dateSubHeaderRow(category));
329
+ }
330
+ }
331
+
332
+ const remaining = safeBudget - rows.length;
333
+ if (pendingHeaders.length + 1 <= remaining) {
334
+ rows.push(...pendingHeaders);
335
+ rows.push(actionOrSessionText(item, i === selected, safeWidth));
336
+ } else if (rows.length === 0) {
337
+ // First item in window on a very tight viewport: keep selection visible without orphaned headers.
338
+ if (remaining >= 2 && pendingHeaders.length > 0) {
339
+ rows.push(pendingHeaders[0]!);
340
+ rows.push(actionOrSessionText(item, i === selected, safeWidth));
341
+ } else if (remaining >= 1) {
342
+ rows.push(actionOrSessionText(item, i === selected, safeWidth));
343
+ } else {
344
+ break;
345
+ }
346
+ } else {
113
347
  break;
114
348
  }
115
- if (rows.length >= safeBudget) break;
116
- rows.push(actionOrSessionText(item, i === selected, safeWidth));
349
+
117
350
  lastIndex = i;
351
+ previousSection = section;
118
352
  previousCategory = category;
119
353
  }
354
+
355
+ // When the current workspace has 0 sessions and no other sessions followed Actions
356
+ // (for example: brand-new install or Tab-scoped THIS WORKSPACE view), show the
357
+ // workspace section header + Empty notice directly beneath Actions.
358
+ const reachedEnd = entries.length === 0 || lastIndex === entries.length - 1;
359
+ if (shouldShowEmptyWorkspace && !emptyWorkspaceEmitted && reachedEnd && safeBudget - rows.length >= 2) {
360
+ rows.push(workspaceSectionRow());
361
+ rows.push(workspaceEmptyRow());
362
+ }
363
+
120
364
  return { rows, lastIndex };
121
365
  }
122
366
 
@@ -132,34 +376,69 @@ export class SessionPickerLayer extends SelectLayer {
132
376
  current: SessionPickerItem | null;
133
377
  lastItemRows?: number;
134
378
  setItems(items: SessionPickerItem[]): void;
379
+ move(delta: number, visibleRows: number): void;
135
380
  moveTo(index: number, visibleRows: number): void;
136
381
  };
137
382
  declare cursor: { x: number; y: number } | null;
138
383
  readonly currentWorkspace: string;
139
384
  readonly activeId: string | null;
140
385
  readonly allItems: SessionPickerItem[];
386
+ private readonly canonicalCache: Map<string, string>;
387
+ private lastWidth = 80;
141
388
  scope: SessionScope = 'all';
142
389
 
143
390
  constructor(options: SessionPickerViewOptions) {
391
+ const canonicalCache = new Map<string, string>();
392
+ const partitioned = partitionSessionPickerItems(options.items, options.currentWorkspace, canonicalCache);
393
+ const totalSwitchCount = partitioned.workspaceCount + partitioned.otherCount;
394
+
144
395
  super({
145
- title: `Sessions ${options.items.filter(i => i.value.type === 'switch').length}`,
396
+ title: `Sessions ${totalSwitchCount}`,
146
397
  width: 100,
147
398
  height: MAX_PANEL_HEIGHT,
148
- items: options.items,
399
+ items: partitioned.ordered,
149
400
  placeholder: 'Search sessions by title, ID or workspace',
150
401
  emptyText: 'No matching sessions',
151
402
  footer: `↑↓ navigate ${GLYPHS.dot} enter open ${GLYPHS.dot} tab workspace ${GLYPHS.dot} esc close`,
152
403
  onPick: options.onPick
153
404
  });
154
- this.allItems = options.items;
405
+ this.canonicalCache = canonicalCache;
406
+ this.allItems = partitioned.ordered;
155
407
  this.currentWorkspace = options.currentWorkspace;
156
408
  this.activeId = options.activeId;
157
409
  }
158
410
 
411
+ private renderOptions(entries: Array<{ item: SessionPickerItem }>): RenderSessionRowsOptions {
412
+ const isSearching = Boolean(clean(this.list.query || '').trim());
413
+ let workspaceCount = 0;
414
+ let otherCount = 0;
415
+ for (const entry of entries) {
416
+ const section = resolveItemSection(entry.item, this.currentWorkspace, this.canonicalCache);
417
+ if (section === 'workspace') workspaceCount++;
418
+ else if (section === 'all') otherCount++;
419
+ }
420
+ return {
421
+ currentWorkspace: this.currentWorkspace,
422
+ workspaceCount,
423
+ otherCount,
424
+ scope: this.scope,
425
+ isSearching,
426
+ canonicalCache: this.canonicalCache
427
+ };
428
+ }
429
+
159
430
  preferredHeight(): number {
160
431
  // Modals with a few sessions do not retain a large blank area.
161
- const distinctGroups = new Set(this.list.filtered.map((entry: { item: SessionPickerItem }) => entry.item.category));
162
- const content = this.list.filtered.length + distinctGroups.size;
432
+ const entries = this.list.filtered as Array<{ item: SessionPickerItem }>;
433
+ const rendered = renderSessionRows(
434
+ entries,
435
+ 0,
436
+ 0,
437
+ this.lastWidth,
438
+ MAX_PANEL_HEIGHT,
439
+ this.renderOptions(entries)
440
+ );
441
+ const content = Math.max(1, rendered.rows.length);
163
442
  return Math.min(MAX_PANEL_HEIGHT, Math.max(12, content + INNER_HEADER_ROWS + INNER_DETAIL_ROWS + 2));
164
443
  }
165
444
 
@@ -173,11 +452,11 @@ export class SessionPickerLayer extends SelectLayer {
173
452
  const scoped = this.scope === 'all'
174
453
  ? this.allItems
175
454
  : this.allItems.filter(item => item.value.type !== 'switch' ||
176
- sameWorkspace(item.value.workspace, this.currentWorkspace));
455
+ sameWorkspace(item.value.workspace, this.currentWorkspace, this.canonicalCache));
177
456
  this.list.setItems(scoped);
178
457
  const next = this.list.filtered.findIndex((entry: { item: SessionPickerItem }) => entry.item.id === oldId);
179
- const firstSession = this.list.filtered.findIndex((entry: { item: SessionPickerItem }) => entry.item.value.type === 'switch');
180
- this.list.selected = next >= 0 ? next : Math.max(0, firstSession);
458
+ const firstWorkspace = this.list.filtered.findIndex((entry: { item: SessionPickerItem }) => entry.item.section === 'workspace');
459
+ this.list.selected = next >= 0 ? next : Math.max(0, firstWorkspace);
181
460
  this.list.offset = 0;
182
461
  }
183
462
 
@@ -186,6 +465,17 @@ export class SessionPickerLayer extends SelectLayer {
186
465
  this.toggleWorkspace();
187
466
  return 'handled';
188
467
  }
468
+ if (event?.name === 'pageup' || event?.name === 'pagedown') {
469
+ const entries = this.list.filtered as Array<{ item: SessionPickerItem }>;
470
+ if (entries.length === 0) return 'handled';
471
+ const available = Math.max(1, this.list.lastItemRows || 12);
472
+ const offset = Math.max(0, Math.min(Math.floor(this.list.offset || 0), entries.length - 1));
473
+ const selected = Math.max(0, Math.min(Math.floor(this.list.selected || 0), entries.length - 1));
474
+ const window = renderSessionRows(entries, offset, selected, this.lastWidth, available, this.renderOptions(entries));
475
+ const page = Math.max(1, window.lastIndex - offset + 1);
476
+ this.list.move(event.name === 'pageup' ? -page : page, available);
477
+ return 'handled';
478
+ }
189
479
  const previousQuery = this.list.query;
190
480
  const result = super.key(event);
191
481
  if (this.list.query !== previousQuery) {
@@ -198,12 +488,15 @@ export class SessionPickerLayer extends SelectLayer {
198
488
  body(width: number, height: number): string[] {
199
489
  const w = Math.max(12, Number.isFinite(width) ? Math.floor(width) : 60);
200
490
  const h = Math.max(1, Number.isFinite(height) ? Math.floor(height) : 20);
491
+ this.lastWidth = w;
201
492
  const rows: string[] = [];
202
493
  const scopeLabel = this.scope === 'all' ? 'ALL WORKSPACES' : 'THIS WORKSPACE';
494
+ const wsName = workspaceDisplayName(this.currentWorkspace, this.canonicalCache);
203
495
  const total = this.allItems.filter(item => item.value.type === 'switch').length;
204
496
  const count = this.countSessions();
205
497
 
206
- rows.push(rowPair(` ${paint('accent', scopeLabel)}`, w >= 52 ? dim(`${count} / ${total} sessions`) : '', w));
498
+ const leftScope = ` ${paint('accent', scopeLabel)} ${dim(`${GLYPHS.dot} ${wsName}`)}`;
499
+ rows.push(rowPair(leftScope, w >= 52 ? dim(`${count} / ${total} sessions`) : '', w));
207
500
  const query = clean(this.list.query || '');
208
501
  const lead = ` ${paint('accent', GLYPHS.arrow)} `;
209
502
  const maxInput = Math.max(1, w - visibleWidth(lead) - 1);
@@ -229,10 +522,11 @@ export class SessionPickerLayer extends SelectLayer {
229
522
  const selected = Math.max(0, Math.min(rawSel, entries.length - 1));
230
523
  this.list.selected = selected;
231
524
  let start = Math.max(0, Math.min(rawOff, selected));
232
- let output = renderSessionRows(entries, start, selected, w, available);
525
+ const renderOpts = this.renderOptions(entries);
526
+ let output = renderSessionRows(entries, start, selected, w, available, renderOpts);
233
527
  while (output.lastIndex < selected && start < selected) {
234
528
  start++;
235
- output = renderSessionRows(entries, start, selected, w, available);
529
+ output = renderSessionRows(entries, start, selected, w, available, renderOpts);
236
530
  }
237
531
  this.list.offset = start;
238
532
  this.list.lastItemRows = available;
@@ -249,7 +543,7 @@ export class SessionPickerLayer extends SelectLayer {
249
543
  rows.push(rowPair(` ${truncate(title, Math.max(1, w - 19), '…')}`, state, w));
250
544
  const description = chosen.value.type === 'switch'
251
545
  ? chosen.description
252
- : chosen.value.type === 'new' ? 'Start with an empty conversation in this workspace'
546
+ : chosen.value.type === 'new' ? `Start with an empty conversation in ${wsName}`
253
547
  : 'Duplicate conversation history; authorization is reset';
254
548
  rows.push(dim(` ${truncate(clean(description), Math.max(1, w - 3), '…')}`));
255
549
  } else {
@@ -199,6 +199,9 @@ export class StatusLine {
199
199
  segments.push(formatCost(this.turnCost));
200
200
  if (this.cachedTokens > 0)
201
201
  segments.push(`${compactCount(this.cachedTokens)} cached`);
202
+ const meter = contextMeter(Math.round(this.contextChars / CHARS_PER_TOKEN), Math.round(this.contextLimit / CHARS_PER_TOKEN));
203
+ if (meter)
204
+ segments.push(meter);
202
205
  if (this.model)
203
206
  segments.push(this.model);
204
207
  const separator = ` ${GLYPHS.dot} `;
@@ -225,6 +225,11 @@ export class StatusLine {
225
225
  if (this.turnTokens > 0) segments.push(`${compactCount(this.turnTokens)} tok`);
226
226
  if (this.turnCost > 0) segments.push(formatCost(this.turnCost));
227
227
  if (this.cachedTokens > 0) segments.push(`${compactCount(this.cachedTokens)} cached`);
228
+ const meter = contextMeter(
229
+ Math.round(this.contextChars / CHARS_PER_TOKEN),
230
+ Math.round(this.contextLimit / CHARS_PER_TOKEN)
231
+ );
232
+ if (meter) segments.push(meter);
228
233
  if (this.model) segments.push(this.model);
229
234
 
230
235
  const separator = ` ${GLYPHS.dot} `;
@@ -0,0 +1,133 @@
1
+ // Dynamic canonical workspace identity & display helpers for Causyne Agent TUI.
2
+ // Authored in Strict TypeScript. Never hardcodes user or project workspace names.
3
+ // Source-available under BUSL-1.1.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { safeDisplay } from './text.js';
8
+ function cleanInlineText(value) {
9
+ return safeDisplay(typeof value === 'string' ? value : String(value ?? ''))
10
+ .replace(/[\r\n\t]+/g, ' ')
11
+ .trim();
12
+ }
13
+ function getUserHomeDir() {
14
+ const fromEnv = process.env.HOME || process.env.USERPROFILE || '';
15
+ if (fromEnv && fromEnv.trim())
16
+ return fromEnv.trim();
17
+ try {
18
+ return os.homedir() || '';
19
+ }
20
+ catch {
21
+ return '';
22
+ }
23
+ }
24
+ function isDriveRoot(value) {
25
+ return value.length >= 2
26
+ && value.length <= 3
27
+ && ((value[0] >= 'A' && value[0] <= 'Z') || (value[0] >= 'a' && value[0] <= 'z'))
28
+ && value[1] === ':'
29
+ && (value.length === 2 || value[2] === '\\' || value[2] === '/');
30
+ }
31
+ /**
32
+ * Resolve a workspace path into a canonical comparison key.
33
+ * Resolves symlinks (for example `/tmp` vs `/private/tmp` on macOS) when the
34
+ * directory exists on disk, falling back to `path.resolve()` otherwise.
35
+ */
36
+ export function canonicalWorkspacePath(workspacePath, cache) {
37
+ if (typeof workspacePath !== 'string')
38
+ return '';
39
+ const trimmed = workspacePath.trim();
40
+ if (!trimmed)
41
+ return '';
42
+ const resolved = path.resolve(trimmed);
43
+ const cached = cache?.get(resolved);
44
+ if (cached !== undefined)
45
+ return cached;
46
+ let canonical = resolved;
47
+ try {
48
+ canonical = typeof fs.realpathSync.native === 'function'
49
+ ? fs.realpathSync.native(resolved)
50
+ : fs.realpathSync(resolved);
51
+ }
52
+ catch {
53
+ // Missing or synthetic paths keep their lexical resolved form.
54
+ }
55
+ const normalized = process.platform === 'win32' ? canonical.toLowerCase() : canonical;
56
+ if (cache)
57
+ cache.set(resolved, normalized);
58
+ return normalized;
59
+ }
60
+ /**
61
+ * True when two workspace paths refer to the same canonical directory.
62
+ */
63
+ export function sameWorkspace(first, second, cache) {
64
+ const a = canonicalWorkspacePath(first, cache);
65
+ const b = canonicalWorkspacePath(second, cache);
66
+ return a.length > 0 && a === b;
67
+ }
68
+ /**
69
+ * Shorten a workspace path for display by replacing the exact home prefix with `~`.
70
+ * Always sanitized for safe single-line terminal rendering.
71
+ */
72
+ export function shortenWorkspacePath(workspacePath) {
73
+ if (typeof workspacePath !== 'string' || !workspacePath.trim())
74
+ return '(default)';
75
+ const trimmed = workspacePath.trim();
76
+ const home = getUserHomeDir();
77
+ if (home) {
78
+ const resolved = path.resolve(trimmed);
79
+ const resolvedHome = path.resolve(home);
80
+ const cmpResolved = process.platform === 'win32' ? resolved.toLowerCase() : resolved;
81
+ const cmpHome = process.platform === 'win32' ? resolvedHome.toLowerCase() : resolvedHome;
82
+ if (cmpResolved === cmpHome)
83
+ return '~';
84
+ const prefix = cmpHome.endsWith(path.sep) ? cmpHome : `${cmpHome}${path.sep}`;
85
+ if (cmpResolved.startsWith(prefix)) {
86
+ const tail = resolved.slice(resolvedHome.length);
87
+ return cleanInlineText(`~${tail}`) || '~';
88
+ }
89
+ }
90
+ return cleanInlineText(trimmed) || '(default)';
91
+ }
92
+ /**
93
+ * Dynamically derive the human-readable workspace folder name from any path
94
+ * without hardcoding user or repository names.
95
+ */
96
+ export function workspaceDisplayName(workspacePath, cache) {
97
+ if (typeof workspacePath !== 'string' || !workspacePath.trim())
98
+ return 'Current Workspace';
99
+ const trimmed = workspacePath.trim();
100
+ const resolved = path.resolve(trimmed);
101
+ const home = getUserHomeDir();
102
+ if (home && sameWorkspace(resolved, home, cache)) {
103
+ return '~';
104
+ }
105
+ const base = path.basename(resolved);
106
+ const cleanBase = cleanInlineText(base);
107
+ if (cleanBase)
108
+ return cleanBase;
109
+ const cleanRoot = cleanInlineText(resolved);
110
+ return cleanRoot || 'Current Workspace';
111
+ }
112
+ /**
113
+ * Format the dynamic section header label for the active workspace's sessions.
114
+ * Preserves the user's folder casing (for example `suika-game SESSIONS (2)` or
115
+ * `causyne-agent SESSIONS (0)`) while handling home and filesystem roots cleanly.
116
+ */
117
+ export function formatWorkspaceSectionTitle(workspacePath, sessionCount, cache) {
118
+ const name = workspaceDisplayName(workspacePath, cache);
119
+ let base;
120
+ if (name === '~') {
121
+ base = 'HOME (~) SESSIONS';
122
+ }
123
+ else if (name === '/' || isDriveRoot(name)) {
124
+ base = `WORKSPACE (${name}) SESSIONS`;
125
+ }
126
+ else {
127
+ base = `${name} SESSIONS`;
128
+ }
129
+ if (typeof sessionCount === 'number' && Number.isFinite(sessionCount) && sessionCount >= 0) {
130
+ return `${base} (${Math.floor(sessionCount)})`;
131
+ }
132
+ return base;
133
+ }