@causyne/agent 1.20.117 → 1.20.120

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 (82) hide show
  1. package/package.json +7 -2
  2. package/src/agentLoop.js +29 -12
  3. package/src/agentLoop.ts +29 -16
  4. package/src/browser/causyneBrowser.js +231 -136
  5. package/src/browser/causyneBrowser.ts +229 -140
  6. package/src/browser/searchProviders.js +41 -30
  7. package/src/browser/searchProviders.ts +24 -14
  8. package/src/browser/workspacePathSafety.js +50 -0
  9. package/src/browser/workspacePathSafety.ts +50 -0
  10. package/src/browser/workspacePreview.js +27 -4
  11. package/src/browser/workspacePreview.ts +28 -4
  12. package/src/cliMode.js +20 -4
  13. package/src/commands.js +12 -14
  14. package/src/creative/liveBridge.js +34 -1
  15. package/src/creative/liveBridge.ts +28 -1
  16. package/src/observer/evidence.js +23 -0
  17. package/src/observer/evidence.ts +21 -0
  18. package/src/plugins/pluginManager.js +74 -0
  19. package/src/providers/anthropic.js +33 -17
  20. package/src/providers/base.js +14 -0
  21. package/src/providers/dashscope-byok.js +13 -7
  22. package/src/providers/deepseek.js +13 -18
  23. package/src/providers/gemini.js +33 -25
  24. package/src/providers/moonshot.js +13 -12
  25. package/src/providers/ollama.js +21 -21
  26. package/src/providers/openai-compatible.js +12 -19
  27. package/src/providers/openrouter.js +20 -90
  28. package/src/providers/openrouter.ts +31 -94
  29. package/src/providers/qwen-byok.js +13 -7
  30. package/src/providers/toolContracts.js +9 -3
  31. package/src/providers/toolContracts.ts +9 -3
  32. package/src/providers/wireNormalizer.js +238 -0
  33. package/src/providers/wireNormalizer.ts +279 -0
  34. package/src/providers/xai.js +13 -12
  35. package/src/reporting.js +12 -4
  36. package/src/skillsManager.js +3 -2
  37. package/src/skillsManager.ts +3 -2
  38. package/src/tools/browserAutomator.js +13 -1
  39. package/src/tools/browserAutomator.ts +13 -0
  40. package/src/tools/creativeApps.js +2 -1
  41. package/src/tools/creativeApps.ts +2 -1
  42. package/src/tools/gameAssetFetcher.js +130 -26
  43. package/src/tools/gameAssetHarvester.js +80 -58
  44. package/src/tools/nativeEngine.js +1 -1
  45. package/src/tools/nativeEngine.ts +1 -1
  46. package/src/tools/pluginManager.js +17 -2
  47. package/src/tools/registry.js +13 -0
  48. package/src/tools/toolScanner.js +596 -140
  49. package/src/tools/toolScanner.ts +665 -147
  50. package/src/tools/toolSelfRepair.js +243 -114
  51. package/src/tools/toolSelfRepair.ts +262 -111
  52. package/src/tools/webFetch.js +161 -24
  53. package/src/tools/webFetch.ts +157 -22
  54. package/src/tools/webSearch.js +33 -4
  55. package/src/tools/webSearch.ts +27 -4
  56. package/src/tui/composerControls.js +16 -3
  57. package/src/tui/composerControls.ts +14 -3
  58. package/src/tui/prompt.js +122 -16
  59. package/src/tui/sessionPicker.js +132 -35
  60. package/src/tui/sessionPicker.ts +153 -32
  61. package/src/tui/sessionPickerView.js +277 -34
  62. package/src/tui/sessionPickerView.ts +328 -34
  63. package/src/tui/statusLine.js +3 -0
  64. package/src/tui/statusLine.ts +5 -0
  65. package/src/tui/usageCard.js +119 -47
  66. package/src/tui/usageCard.ts +133 -49
  67. package/src/tui/workspaceIdentity.js +133 -0
  68. package/src/tui/workspaceIdentity.ts +146 -0
  69. package/src/tui/workspaceSwitch.js +2 -0
  70. package/src/tui/workspaceSwitch.ts +1 -0
  71. package/src/verification/boundedExplorer.js +119 -0
  72. package/src/verification/cliProbe.js +116 -0
  73. package/src/verification/featureMap.js +78 -0
  74. package/src/verification/interactivePty.js +188 -0
  75. package/src/verification/propertyProbe.js +121 -0
  76. package/src/verification/ptyProbe.js +125 -0
  77. package/src/verification/skillCatalog.d.ts +1 -0
  78. package/src/verification/skillCatalog.js +60 -0
  79. package/src/verification/statechart.js +143 -0
  80. package/src/verification/uiRuntime.js +57 -0
  81. package/src/verificationPlan.js +1 -1
  82. package/src/verificationPlan.ts +1 -1
@@ -143,9 +143,22 @@ export function handlePromptEscape(prompt, formatInterruptedRow) {
143
143
  prompt.scheduleDraw();
144
144
  return;
145
145
  }
146
- if (prompt.usageCard) {
147
- prompt.usageCard = null;
148
- prompt.scheduleDraw();
146
+ if (prompt.usageCard || prompt.usageCardLoading) {
147
+ if (typeof prompt.closeUsageCard === 'function')
148
+ prompt.closeUsageCard();
149
+ else {
150
+ prompt.usageCard = null;
151
+ prompt.scheduleDraw();
152
+ }
153
+ return;
154
+ }
155
+ if (prompt.statusCard !== null && prompt.statusCard !== undefined) {
156
+ if (typeof prompt.closeStatusCard === 'function')
157
+ prompt.closeStatusCard();
158
+ else {
159
+ prompt.statusCard = null;
160
+ prompt.scheduleDraw();
161
+ }
149
162
  return;
150
163
  }
151
164
  if (prompt.completion) {
@@ -193,9 +193,20 @@ export function handlePromptEscape(
193
193
  prompt.scheduleDraw();
194
194
  return;
195
195
  }
196
- if ((prompt as any).usageCard) {
197
- (prompt as any).usageCard = null;
198
- prompt.scheduleDraw();
196
+ if ((prompt as any).usageCard || (prompt as any).usageCardLoading) {
197
+ if (typeof (prompt as any).closeUsageCard === 'function') (prompt as any).closeUsageCard();
198
+ else {
199
+ (prompt as any).usageCard = null;
200
+ prompt.scheduleDraw();
201
+ }
202
+ return;
203
+ }
204
+ if ((prompt as any).statusCard !== null && (prompt as any).statusCard !== undefined) {
205
+ if (typeof (prompt as any).closeStatusCard === 'function') (prompt as any).closeStatusCard();
206
+ else {
207
+ (prompt as any).statusCard = null;
208
+ prompt.scheduleDraw();
209
+ }
199
210
  return;
200
211
  }
201
212
  if (prompt.completion) {
package/src/tui/prompt.js CHANGED
@@ -29,7 +29,8 @@ import { composerGeometry } from './composerGeometry.js';
29
29
  import { visibleWidth, truncate, wrapBlock, shortenHome, safeDisplay, stripAnsi } from './text.js';
30
30
  import { pickExample, fitHints } from './banner.js';
31
31
  import { panelRows } from './overlay.js';
32
- import { renderUsageCardRows, collectUsageCardData } from './usageCard.js';
32
+ import { renderUsageCardRows, renderStatusCardRows, collectUsageCardData } from './usageCard.js';
33
+ import { buildStatusText } from '../reporting.js';
33
34
  import { commandPalette, skillPicker, ApprovalLayer, DecisionLayer, ConfirmLayer, HomeLayer, TextLayer } from './dialogs.js';
34
35
  import { describeTool } from './toolDisplay.js';
35
36
  import { readClipboardSync, writeClipboardSync } from './clipboardSync.js';
@@ -135,6 +136,11 @@ export class ChatPrompt {
135
136
  this.exitHook = null;
136
137
  this.drawnRows = 0;
137
138
  this.usageCard = null;
139
+ this.usageCardLoading = false;
140
+ this.statusCard = null;
141
+ this.statusCardUsage = null;
142
+ this.infoPanelVersion = 0;
143
+ this.usageRefreshPending = false;
138
144
 
139
145
  // Which row of the drawn block the caret is parked on.
140
146
  //
@@ -542,6 +548,10 @@ export class ChatPrompt {
542
548
  this.tickTimer = setInterval(() => {
543
549
  this.tick++;
544
550
  if (this.busy) this.scheduleDraw();
551
+ // Keep the pinned usage/status view current without disk reads every 125 ms.
552
+ if (this.busy && (this.usageCard || this.statusCard !== null) && this.tick % 32 === 0) {
553
+ this.refreshPinnedPanels();
554
+ }
545
555
  }, 125);
546
556
  if (this.tickTimer.unref) this.tickTimer.unref();
547
557
  }
@@ -667,16 +677,31 @@ export class ChatPrompt {
667
677
  }));
668
678
  }
669
679
 
670
- /** Toggle the docked usage card directly above the chatbox. */
680
+ /** Usage and Status are non-modal panels: ordinary chat must not close them. */
671
681
  async toggleUsageCard(loop = null) {
672
- if (this.usageCard) {
673
- this.usageCard = null;
682
+ if (this.usageCard || this.usageCardLoading) {
683
+ this.closeUsageCard();
684
+ return false;
685
+ }
686
+ const version = ++this.infoPanelVersion;
687
+ this.statusCard = null;
688
+ this.statusCardUsage = null;
689
+ this.usageCardLoading = true;
690
+ try {
691
+ const data = await collectUsageCardData(loop || this.messageActionLoop);
692
+ if (version !== this.infoPanelVersion || !this.usageCardLoading) return false;
693
+ this.usageCard = data;
694
+ this.usageCardLoading = false;
674
695
  this.scheduleDraw();
696
+ return true;
697
+ } catch (error) {
698
+ if (version === this.infoPanelVersion) {
699
+ this.usageCardLoading = false;
700
+ this.notice = this.sanitizeSingleLine(error instanceof Error ? error.message : String(error));
701
+ this.scheduleDraw();
702
+ }
675
703
  return false;
676
704
  }
677
- this.usageCard = await collectUsageCardData(loop || this.messageActionLoop);
678
- this.scheduleDraw();
679
- return true;
680
705
  }
681
706
 
682
707
  showUsageCard(loop = null) {
@@ -684,12 +709,84 @@ export class ChatPrompt {
684
709
  }
685
710
 
686
711
  closeUsageCard() {
687
- if (this.usageCard) {
688
- this.usageCard = null;
712
+ if (!this.usageCard && !this.usageCardLoading) return false;
713
+ ++this.infoPanelVersion; // Invalidate an in-flight open or refresh.
714
+ this.usageCard = null;
715
+ this.usageCardLoading = false;
716
+ this.scheduleDraw();
717
+ return true;
718
+ }
719
+
720
+ async refreshUsageCard(loop = null) {
721
+ if (!this.usageCard || this.usageRefreshPending) return false;
722
+ const version = this.infoPanelVersion;
723
+ this.usageRefreshPending = true;
724
+ try {
725
+ const data = await collectUsageCardData(loop || this.messageActionLoop);
726
+ if (version !== this.infoPanelVersion || !this.usageCard) return false;
727
+ this.usageCard = data;
689
728
  this.scheduleDraw();
690
729
  return true;
730
+ } catch {
731
+ // A transient ledger read failure must not close an already visible panel.
732
+ return false;
733
+ } finally {
734
+ this.usageRefreshPending = false;
691
735
  }
692
- return false;
736
+ }
737
+
738
+ toggleStatusCard(loop = null) {
739
+ if (this.statusCard !== null) {
740
+ this.closeStatusCard();
741
+ return false;
742
+ }
743
+ const targetLoop = loop || this.messageActionLoop;
744
+ ++this.infoPanelVersion; // A pending usage read must not reopen a replaced panel.
745
+ this.usageCard = null;
746
+ this.usageCardLoading = false;
747
+ this.statusCardUsage = null;
748
+ this.statusCard = buildStatusText({ loop: targetLoop });
749
+ this.scheduleDraw();
750
+ void this.refreshStatusCardMeta(targetLoop);
751
+ return true;
752
+ }
753
+
754
+ closeStatusCard() {
755
+ if (this.statusCard === null) return false;
756
+ ++this.infoPanelVersion;
757
+ this.statusCard = null;
758
+ this.statusCardUsage = null;
759
+ this.scheduleDraw();
760
+ return true;
761
+ }
762
+
763
+ async refreshStatusCardMeta(loop = null) {
764
+ if (this.statusCard === null) return false;
765
+ const version = this.infoPanelVersion;
766
+ try {
767
+ const data = await collectUsageCardData(loop || this.messageActionLoop);
768
+ if (version !== this.infoPanelVersion || this.statusCard === null) return false;
769
+ this.statusCardUsage = data;
770
+ this.scheduleDraw();
771
+ return true;
772
+ } catch {
773
+ return false;
774
+ }
775
+ }
776
+
777
+ refreshPinnedPanels(loop = null) {
778
+ const targetLoop = loop || this.messageActionLoop;
779
+ if (this.usageCard) void this.refreshUsageCard(targetLoop);
780
+ if (this.statusCard !== null) {
781
+ this.statusCard = buildStatusText({ loop: targetLoop });
782
+ this.scheduleDraw();
783
+ void this.refreshStatusCardMeta(targetLoop);
784
+ }
785
+ }
786
+
787
+ statusCardRows(width) {
788
+ if (this.statusCard === null) return [];
789
+ return renderStatusCardRows(this.statusCard, this.statusCardUsage, width);
693
790
  }
694
791
 
695
792
  /**
@@ -877,6 +974,11 @@ export class ChatPrompt {
877
974
  this.busy = busy;
878
975
  resetTurnInterruptState(this, busy);
879
976
  if (busy) this.startTick(); else this.stopTick();
977
+ if (!busy && this.usageCard) void this.refreshUsageCard();
978
+ if (this.statusCard !== null) {
979
+ this.statusCard = buildStatusText({ loop: this.messageActionLoop });
980
+ if (!busy) void this.refreshStatusCardMeta(this.messageActionLoop);
981
+ }
880
982
  if (this.surface?.stage) this.surface.stage.invalidate();
881
983
  this.draw();
882
984
  }
@@ -897,15 +999,18 @@ export class ChatPrompt {
897
999
  this.history.add(text);
898
1000
  this.editor.clear();
899
1001
  this.completion = null;
900
- if (this.usageCard && !this.isCommand(text)) {
901
- this.usageCard = null;
902
- }
903
-
1002
+ // Do not dismiss a pinned information panel on any chat submission,
1003
+ // queued prompt, or agent run. Only Esc or the same command closes it.
904
1004
  // Instant slash command shortcuts that operate directly on the prompt surface
905
- if (text === '/usage' && typeof this.toggleUsageCard === 'function') {
1005
+ if ((text.trim().toLowerCase() === '/usage' || text.trim().toLowerCase() === '/cost')
1006
+ && typeof this.toggleUsageCard === 'function') {
906
1007
  void this.toggleUsageCard();
907
1008
  return;
908
1009
  }
1010
+ if (text.trim().toLowerCase() === '/status' && typeof this.toggleStatusCard === 'function') {
1011
+ this.toggleStatusCard();
1012
+ return;
1013
+ }
909
1014
 
910
1015
  if (text === '/observer' || text === '/observer status') {
911
1016
  import('./observerPicker.js').then(({ runInteractiveObserverPicker }) => {
@@ -1918,7 +2023,8 @@ export class ChatPrompt {
1918
2023
  punctuate: false
1919
2024
  });
1920
2025
 
1921
- const usageCardRows = this.usageCard ? renderUsageCardRows(this.usageCard, width) : [];
2026
+ const usageCardRows = this.usageCard ? renderUsageCardRows(this.usageCard, boxWidth)
2027
+ : this.statusCard !== null ? this.statusCardRows(boxWidth) : [];
1922
2028
  const planRows = this.planRows(width);
1923
2029
  const pickerRows = this.completion ? this.pickerRows(width) : [];
1924
2030
  this.pickerLayout = this.completion ? {
@@ -2,6 +2,7 @@
2
2
  // Authored in Strict TypeScript for Causyne Agent.
3
3
  // Source-available under BUSL-1.1.
4
4
  import { SessionPickerLayer } from './sessionPickerView.js';
5
+ import { sameWorkspace, shortenWorkspacePath, workspaceDisplayName, formatWorkspaceSectionTitle } from './workspaceIdentity.js';
5
6
  // @ts-expect-error untyped local TUI theme
6
7
  import { GLYPHS } from './theme.js';
7
8
  import { safeDisplay } from './text.js';
@@ -44,28 +45,36 @@ function dateGroup(timestamp) {
44
45
  const yesterday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 1);
45
46
  return date.toDateString() === yesterday.toDateString() ? 'Yesterday' : date.toDateString();
46
47
  }
47
- function shortenPath(p) {
48
- if (!p)
49
- return '(default)';
50
- const home = process.env.HOME || '';
51
- if (home && p.startsWith(home)) {
52
- return '~' + p.slice(home.length);
53
- }
54
- return p.split('/').pop() || p;
48
+ function compareSessionsByDate(a, b) {
49
+ const aValid = Number.isFinite(a.updatedAt);
50
+ const bValid = Number.isFinite(b.updatedAt);
51
+ if (!aValid && !bValid)
52
+ return 0;
53
+ if (!aValid)
54
+ return 1;
55
+ if (!bValid)
56
+ return -1;
57
+ return b.updatedAt === a.updatedAt ? 0 : b.updatedAt > a.updatedAt ? 1 : -1;
55
58
  }
56
59
  /**
57
60
  * Build item list for SelectLayer modal.
58
- * The top item is always "+ New Session" to guarantee clean separation and quick reset.
61
+ * Ordering:
62
+ * 1. Pinned Actions (`+ New Session`, optional `Fork Current Session`)
63
+ * 2. Current workspace sessions (sorted newest-first and grouped by date)
64
+ * 3. All other sessions (sorted newest-first and grouped by date, strictly deduplicated)
59
65
  */
60
66
  export function buildSessionPickerItems(sessions, activeId, currentWorkspace) {
61
67
  const items = [];
68
+ const canonicalCache = new Map();
69
+ const currentWsName = workspaceDisplayName(currentWorkspace, canonicalCache);
62
70
  // Pinned item 0: Create new clean conversation
63
71
  items.push({
64
72
  id: '__NEW_SESSION__',
65
73
  label: '+ New Session (Start fresh conversation)',
66
74
  category: 'Actions',
67
- description: 'Begin a clean session in this workspace without previous context',
68
- searchText: 'new session fresh clear reset start',
75
+ section: 'actions',
76
+ description: `Begin a clean session in ${currentWsName} without previous context`,
77
+ searchText: `new session fresh clear reset start ${currentWsName}`,
69
78
  value: {
70
79
  type: 'new'
71
80
  }
@@ -79,6 +88,7 @@ export function buildSessionPickerItems(sessions, activeId, currentWorkspace) {
79
88
  id: '__FORK_SESSION__',
80
89
  label: `Branch / Fork Current Session ("${activeTitle}")`,
81
90
  category: 'Actions',
91
+ section: 'actions',
82
92
  description: 'Copy conversation history into a new branch without copying permissions',
83
93
  searchText: 'fork branch clone copy session fresh permissions',
84
94
  value: {
@@ -89,37 +99,36 @@ export function buildSessionPickerItems(sessions, activeId, currentWorkspace) {
89
99
  });
90
100
  }
91
101
  }
92
- const sortedSessions = [...sessions].sort((a, b) => {
93
- const aValid = Number.isFinite(a.updatedAt);
94
- const bValid = Number.isFinite(b.updatedAt);
95
- if (!aValid && !bValid)
96
- return 0;
97
- if (!aValid)
98
- return 1;
99
- if (!bValid)
100
- return -1;
101
- return b.updatedAt === a.updatedAt ? 0 : b.updatedAt > a.updatedAt ? 1 : -1;
102
- });
102
+ const sortedSessions = [...sessions].sort(compareSessionsByDate);
103
+ const seenIds = new Set();
104
+ const workspaceItems = [];
105
+ const otherItems = [];
103
106
  for (const s of sortedSessions) {
107
+ if (!s || typeof s.id !== 'string' || !s.id || seenIds.has(s.id))
108
+ continue;
104
109
  // A session without any turns has no conversation to resume. Keep the
105
110
  // active one available, but do not fill the picker with abandoned starts.
106
111
  const safeMessageCount = Number.isFinite(s.messageCount) ? Math.max(0, Math.floor(s.messageCount)) : 0;
107
112
  if (safeMessageCount === 0 && s.id !== activeId)
108
113
  continue;
114
+ seenIds.add(s.id);
109
115
  const isCurrent = s.id === activeId;
116
+ const inCurrentWorkspace = sameWorkspace(s.workspace, currentWorkspace, canonicalCache);
110
117
  const timeAgo = formatTimeAgo(s.updatedAt);
111
- const wsLabel = shortenPath(s.workspace);
118
+ const wsLabel = shortenWorkspacePath(s.workspace);
119
+ const wsName = s.workspace ? workspaceDisplayName(s.workspace, canonicalCache) : '';
112
120
  const msgCount = `${safeMessageCount} msg${safeMessageCount === 1 ? '' : 's'}`;
113
121
  const category = dateGroup(s.updatedAt);
114
122
  const mark = isCurrent ? `● ` : ` `;
115
123
  const tag = isCurrent ? ` [active]` : '';
116
124
  const title = cleanTitle(s.title);
117
- items.push({
125
+ const pickerItem = {
118
126
  id: s.id,
119
127
  label: `${mark}${title}${tag}`,
120
128
  category,
121
- description: `${msgCount} ${GLYPHS.dot} ${timeAgo} ${GLYPHS.dot} ${wsLabel}${s.workspace === currentWorkspace ? ' (current)' : ''}`,
122
- searchText: `${title} ${s.id} ${s.workspace || ''} ${category}`,
129
+ section: inCurrentWorkspace ? 'workspace' : 'all',
130
+ description: `${msgCount} ${GLYPHS.dot} ${timeAgo} ${GLYPHS.dot} ${wsLabel}${inCurrentWorkspace ? ' (current)' : ''}`,
131
+ searchText: `${title} ${s.id} ${s.workspace || ''} ${wsName} ${category}`,
123
132
  value: {
124
133
  type: 'switch',
125
134
  id: s.id,
@@ -129,18 +138,98 @@ export function buildSessionPickerItems(sessions, activeId, currentWorkspace) {
129
138
  updatedAt: s.updatedAt,
130
139
  isCurrent
131
140
  }
132
- });
141
+ };
142
+ if (inCurrentWorkspace) {
143
+ workspaceItems.push(pickerItem);
144
+ }
145
+ else {
146
+ otherItems.push(pickerItem);
147
+ }
133
148
  }
149
+ items.push(...workspaceItems, ...otherItems);
134
150
  return items;
135
151
  }
152
+ /**
153
+ * Format a plain-text `/sessions` report (for non-interactive or piped output)
154
+ * with the current workspace section first (or Empty) and deduplicated All Sessions below.
155
+ */
156
+ export function formatSessionsTextReport(sessions, activeId, currentWorkspace, limit = 20) {
157
+ const canonicalCache = new Map();
158
+ const sorted = [...sessions].sort(compareSessionsByDate);
159
+ const seenIds = new Set();
160
+ const workspaceRows = [];
161
+ const otherRows = [];
162
+ for (const s of sorted) {
163
+ if (!s || typeof s.id !== 'string' || !s.id || seenIds.has(s.id))
164
+ continue;
165
+ seenIds.add(s.id);
166
+ if (sameWorkspace(s.workspace, currentWorkspace, canonicalCache)) {
167
+ workspaceRows.push(s);
168
+ }
169
+ else {
170
+ otherRows.push(s);
171
+ }
172
+ }
173
+ const formatRow = (s) => {
174
+ const when = Number.isFinite(s.updatedAt)
175
+ ? new Date(s.updatedAt).toISOString().slice(0, 16).replace('T', ' ')
176
+ : 'unknown date';
177
+ const where = s.workspace ? shortenWorkspacePath(s.workspace) : '(no workspace)';
178
+ const mark = s.id === activeId ? '*' : ' ';
179
+ const count = Number.isFinite(s.messageCount) ? Math.max(0, Math.floor(s.messageCount)) : 0;
180
+ return ` ${mark} ${s.id} ${when} ${String(count).padStart(4)} msg ${where}\n ${cleanTitle(s.title)}`;
181
+ };
182
+ const totalCount = workspaceRows.length + otherRows.length;
183
+ const maxShown = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : 20;
184
+ const lines = [
185
+ `${totalCount} session${totalCount === 1 ? '' : 's'} (* = active):`,
186
+ '',
187
+ `${formatWorkspaceSectionTitle(currentWorkspace, workspaceRows.length, canonicalCache)} (${shortenWorkspacePath(currentWorkspace)}):`
188
+ ];
189
+ let remaining = maxShown;
190
+ if (workspaceRows.length === 0) {
191
+ lines.push(' Empty — no sessions in this workspace yet');
192
+ }
193
+ else {
194
+ let lastDate = null;
195
+ for (const row of workspaceRows.slice(0, remaining)) {
196
+ const group = dateGroup(row.updatedAt);
197
+ if (group !== lastDate) {
198
+ lines.push(` [${group}]`);
199
+ lastDate = group;
200
+ }
201
+ lines.push(formatRow(row));
202
+ }
203
+ remaining = Math.max(0, remaining - workspaceRows.length);
204
+ }
205
+ if (otherRows.length > 0 && remaining > 0) {
206
+ lines.push('');
207
+ lines.push(`ALL SESSIONS (${otherRows.length}):`);
208
+ let lastDate = null;
209
+ for (const row of otherRows.slice(0, remaining)) {
210
+ const group = dateGroup(row.updatedAt);
211
+ if (group !== lastDate) {
212
+ lines.push(` [${group}]`);
213
+ lastDate = group;
214
+ }
215
+ lines.push(formatRow(row));
216
+ }
217
+ }
218
+ lines.push('');
219
+ lines.push('Switch with /sessions switch <id>, fork with /fork [id], or run /sessions to open interactive modal picker.');
220
+ return lines.join('\n');
221
+ }
136
222
  /**
137
223
  * Launch the interactive Session Picker modal.
138
224
  * Single Enter switches session or creates a new one immediately.
139
225
  */
140
226
  export async function runInteractiveSessionPicker(prompt, options = {}) {
141
- const workspace = options.workspace || process.cwd();
227
+ const workspace = options.workspace
228
+ || options.loop?.workspaceRoot
229
+ || prompt.root
230
+ || process.cwd();
142
231
  const sessions = listSessions();
143
- const activeId = getActiveSessionId();
232
+ const activeId = options.loop?.memoryManager?.sessionId || getActiveSessionId();
144
233
  const items = buildSessionPickerItems(sessions, activeId, workspace);
145
234
  const cleanPrompt = () => {
146
235
  if (prompt.editor && typeof prompt.editor.clear === 'function') {
@@ -158,11 +247,19 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
158
247
  resolve(item || null);
159
248
  }
160
249
  });
161
- // Opening the picker should highlight a conversation, not an action that
162
- // creates a new one. Actions remain available above the dated list.
163
- const selected = items.findIndex(item => item.id === activeId);
164
- const firstConversation = items.findIndex(item => item.value.type === 'switch');
165
- layer.list.moveTo(selected >= 0 ? selected : Math.max(0, firstConversation), 15);
250
+ // Prefer the active session when it belongs to the current workspace,
251
+ // otherwise the newest conversation in the current workspace. When the
252
+ // current workspace is empty, keep focus at index 0 (+ New Session) so the
253
+ // workspace header and Empty indicator remain immediately visible on open.
254
+ const ordered = layer.list.all;
255
+ const activeWorkspaceIdx = ordered.findIndex(item => item.section === 'workspace' && item.id === activeId);
256
+ const firstWorkspaceIdx = ordered.findIndex(item => item.section === 'workspace');
257
+ const initialIndex = activeWorkspaceIdx >= 0
258
+ ? activeWorkspaceIdx
259
+ : firstWorkspaceIdx >= 0
260
+ ? firstWorkspaceIdx
261
+ : 0;
262
+ layer.list.moveTo(initialIndex, 15);
166
263
  prompt.openLayer(layer);
167
264
  });
168
265
  cleanPrompt();
@@ -225,7 +322,7 @@ export async function runInteractiveSessionPicker(prompt, options = {}) {
225
322
  }
226
323
  syncSessionSurface(newSession, []);
227
324
  cleanPrompt();
228
- return `Started new session: "${cleanTitle(newSession.title)}" (${newSession.id}) in ${shortenPath(workspace)}.`;
325
+ return `Started new session: "${cleanTitle(newSession.title)}" (${newSession.id}) in ${shortenWorkspacePath(workspace)}.`;
229
326
  }
230
327
  // Case 2: Fork session into a new branch without copying permissions
231
328
  if (picked.value.type === 'fork') {