@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
@@ -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') {
@@ -3,6 +3,12 @@
3
3
  // Source-available under BUSL-1.1.
4
4
 
5
5
  import { SessionPickerLayer } from './sessionPickerView.js';
6
+ import {
7
+ sameWorkspace,
8
+ shortenWorkspacePath,
9
+ workspaceDisplayName,
10
+ formatWorkspaceSectionTitle
11
+ } from './workspaceIdentity.js';
6
12
  // @ts-expect-error untyped local TUI theme
7
13
  import { GLYPHS } from './theme.js';
8
14
  import { safeDisplay } from './text.js';
@@ -31,10 +37,13 @@ export interface SessionPickerItemValue {
31
37
  isCurrent?: boolean | undefined;
32
38
  }
33
39
 
40
+ export type SessionPickerSection = 'actions' | 'workspace' | 'all';
41
+
34
42
  export interface SessionPickerItem {
35
43
  id: string;
36
44
  label: string;
37
45
  category: string;
46
+ section?: SessionPickerSection | undefined;
38
47
  description: string;
39
48
  searchText?: string;
40
49
  value: SessionPickerItemValue;
@@ -42,6 +51,7 @@ export interface SessionPickerItem {
42
51
 
43
52
  export interface InteractiveSessionPickerOptions {
44
53
  loop?: {
54
+ workspaceRoot?: string | undefined;
45
55
  taskId?: string;
46
56
  messages?: Array<{ role: string; content?: unknown }>;
47
57
  tokenTracker?: { reset?: () => void; sessionTokens?: number };
@@ -87,18 +97,24 @@ function dateGroup(timestamp: number): string {
87
97
  return date.toDateString() === yesterday.toDateString() ? 'Yesterday' : date.toDateString();
88
98
  }
89
99
 
90
- function shortenPath(p: string | undefined): string {
91
- if (!p) return '(default)';
92
- const home = process.env.HOME || '';
93
- if (home && p.startsWith(home)) {
94
- return '~' + p.slice(home.length);
95
- }
96
- return p.split('/').pop() || p;
100
+ function compareSessionsByDate(
101
+ a: { updatedAt: number },
102
+ b: { updatedAt: number }
103
+ ): number {
104
+ const aValid = Number.isFinite(a.updatedAt);
105
+ const bValid = Number.isFinite(b.updatedAt);
106
+ if (!aValid && !bValid) return 0;
107
+ if (!aValid) return 1;
108
+ if (!bValid) return -1;
109
+ return b.updatedAt === a.updatedAt ? 0 : b.updatedAt > a.updatedAt ? 1 : -1;
97
110
  }
98
111
 
99
112
  /**
100
113
  * Build item list for SelectLayer modal.
101
- * The top item is always "+ New Session" to guarantee clean separation and quick reset.
114
+ * Ordering:
115
+ * 1. Pinned Actions (`+ New Session`, optional `Fork Current Session`)
116
+ * 2. Current workspace sessions (sorted newest-first and grouped by date)
117
+ * 3. All other sessions (sorted newest-first and grouped by date, strictly deduplicated)
102
118
  */
103
119
  export function buildSessionPickerItems(
104
120
  sessions: Array<Omit<SessionRecord, 'messages'> & { messageCount: number }>,
@@ -106,14 +122,17 @@ export function buildSessionPickerItems(
106
122
  currentWorkspace: string
107
123
  ): SessionPickerItem[] {
108
124
  const items: SessionPickerItem[] = [];
125
+ const canonicalCache = new Map<string, string>();
126
+ const currentWsName = workspaceDisplayName(currentWorkspace, canonicalCache);
109
127
 
110
128
  // Pinned item 0: Create new clean conversation
111
129
  items.push({
112
130
  id: '__NEW_SESSION__',
113
131
  label: '+ New Session (Start fresh conversation)',
114
132
  category: 'Actions',
115
- description: 'Begin a clean session in this workspace without previous context',
116
- searchText: 'new session fresh clear reset start',
133
+ section: 'actions',
134
+ description: `Begin a clean session in ${currentWsName} without previous context`,
135
+ searchText: `new session fresh clear reset start ${currentWsName}`,
117
136
  value: {
118
137
  type: 'new'
119
138
  }
@@ -128,6 +147,7 @@ export function buildSessionPickerItems(
128
147
  id: '__FORK_SESSION__',
129
148
  label: `Branch / Fork Current Session ("${activeTitle}")`,
130
149
  category: 'Actions',
150
+ section: 'actions',
131
151
  description: 'Copy conversation history into a new branch without copying permissions',
132
152
  searchText: 'fork branch clone copy session fresh permissions',
133
153
  value: {
@@ -139,37 +159,38 @@ export function buildSessionPickerItems(
139
159
  }
140
160
  }
141
161
 
142
- const sortedSessions = [...sessions].sort((a, b) => {
143
- const aValid = Number.isFinite(a.updatedAt);
144
- const bValid = Number.isFinite(b.updatedAt);
145
- if (!aValid && !bValid) return 0;
146
- if (!aValid) return 1;
147
- if (!bValid) return -1;
148
- return b.updatedAt === a.updatedAt ? 0 : b.updatedAt > a.updatedAt ? 1 : -1;
149
- });
162
+ const sortedSessions = [...sessions].sort(compareSessionsByDate);
163
+ const seenIds = new Set<string>();
164
+ const workspaceItems: SessionPickerItem[] = [];
165
+ const otherItems: SessionPickerItem[] = [];
150
166
 
151
167
  for (const s of sortedSessions) {
168
+ if (!s || typeof s.id !== 'string' || !s.id || seenIds.has(s.id)) continue;
152
169
  // A session without any turns has no conversation to resume. Keep the
153
170
  // active one available, but do not fill the picker with abandoned starts.
154
171
  const safeMessageCount = Number.isFinite(s.messageCount) ? Math.max(0, Math.floor(s.messageCount)) : 0;
155
172
  if (safeMessageCount === 0 && s.id !== activeId) continue;
173
+ seenIds.add(s.id);
174
+
156
175
  const isCurrent = s.id === activeId;
176
+ const inCurrentWorkspace = sameWorkspace(s.workspace, currentWorkspace, canonicalCache);
157
177
  const timeAgo = formatTimeAgo(s.updatedAt);
158
- const wsLabel = shortenPath(s.workspace);
178
+ const wsLabel = shortenWorkspacePath(s.workspace);
179
+ const wsName = s.workspace ? workspaceDisplayName(s.workspace, canonicalCache) : '';
159
180
  const msgCount = `${safeMessageCount} msg${safeMessageCount === 1 ? '' : 's'}`;
160
-
161
181
  const category = dateGroup(s.updatedAt);
162
182
 
163
183
  const mark = isCurrent ? `● ` : ` `;
164
184
  const tag = isCurrent ? ` [active]` : '';
165
185
  const title = cleanTitle(s.title);
166
186
 
167
- items.push({
187
+ const pickerItem: SessionPickerItem = {
168
188
  id: s.id,
169
189
  label: `${mark}${title}${tag}`,
170
190
  category,
171
- description: `${msgCount} ${GLYPHS.dot} ${timeAgo} ${GLYPHS.dot} ${wsLabel}${s.workspace === currentWorkspace ? ' (current)' : ''}`,
172
- searchText: `${title} ${s.id} ${s.workspace || ''} ${category}`,
191
+ section: inCurrentWorkspace ? 'workspace' : 'all',
192
+ description: `${msgCount} ${GLYPHS.dot} ${timeAgo} ${GLYPHS.dot} ${wsLabel}${inCurrentWorkspace ? ' (current)' : ''}`,
193
+ searchText: `${title} ${s.id} ${s.workspace || ''} ${wsName} ${category}`,
173
194
  value: {
174
195
  type: 'switch',
175
196
  id: s.id,
@@ -179,12 +200,98 @@ export function buildSessionPickerItems(
179
200
  updatedAt: s.updatedAt,
180
201
  isCurrent
181
202
  }
182
- });
203
+ };
204
+
205
+ if (inCurrentWorkspace) {
206
+ workspaceItems.push(pickerItem);
207
+ } else {
208
+ otherItems.push(pickerItem);
209
+ }
183
210
  }
184
211
 
212
+ items.push(...workspaceItems, ...otherItems);
185
213
  return items;
186
214
  }
187
215
 
216
+ /**
217
+ * Format a plain-text `/sessions` report (for non-interactive or piped output)
218
+ * with the current workspace section first (or Empty) and deduplicated All Sessions below.
219
+ */
220
+ export function formatSessionsTextReport(
221
+ sessions: Array<Omit<SessionRecord, 'messages'> & { messageCount: number }>,
222
+ activeId: string | null,
223
+ currentWorkspace: string,
224
+ limit = 20
225
+ ): string {
226
+ const canonicalCache = new Map<string, string>();
227
+ const sorted = [...sessions].sort(compareSessionsByDate);
228
+ const seenIds = new Set<string>();
229
+ const workspaceRows: Array<Omit<SessionRecord, 'messages'> & { messageCount: number }> = [];
230
+ const otherRows: Array<Omit<SessionRecord, 'messages'> & { messageCount: number }> = [];
231
+
232
+ for (const s of sorted) {
233
+ if (!s || typeof s.id !== 'string' || !s.id || seenIds.has(s.id)) continue;
234
+ seenIds.add(s.id);
235
+ if (sameWorkspace(s.workspace, currentWorkspace, canonicalCache)) {
236
+ workspaceRows.push(s);
237
+ } else {
238
+ otherRows.push(s);
239
+ }
240
+ }
241
+
242
+ const formatRow = (s: Omit<SessionRecord, 'messages'> & { messageCount: number }): string => {
243
+ const when = Number.isFinite(s.updatedAt)
244
+ ? new Date(s.updatedAt).toISOString().slice(0, 16).replace('T', ' ')
245
+ : 'unknown date';
246
+ const where = s.workspace ? shortenWorkspacePath(s.workspace) : '(no workspace)';
247
+ const mark = s.id === activeId ? '*' : ' ';
248
+ const count = Number.isFinite(s.messageCount) ? Math.max(0, Math.floor(s.messageCount)) : 0;
249
+ return ` ${mark} ${s.id} ${when} ${String(count).padStart(4)} msg ${where}\n ${cleanTitle(s.title)}`;
250
+ };
251
+
252
+ const totalCount = workspaceRows.length + otherRows.length;
253
+ const maxShown = Number.isFinite(limit) && limit > 0 ? Math.floor(limit) : 20;
254
+ const lines: string[] = [
255
+ `${totalCount} session${totalCount === 1 ? '' : 's'} (* = active):`,
256
+ '',
257
+ `${formatWorkspaceSectionTitle(currentWorkspace, workspaceRows.length, canonicalCache)} (${shortenWorkspacePath(currentWorkspace)}):`
258
+ ];
259
+
260
+ let remaining = maxShown;
261
+ if (workspaceRows.length === 0) {
262
+ lines.push(' Empty — no sessions in this workspace yet');
263
+ } else {
264
+ let lastDate: string | null = null;
265
+ for (const row of workspaceRows.slice(0, remaining)) {
266
+ const group = dateGroup(row.updatedAt);
267
+ if (group !== lastDate) {
268
+ lines.push(` [${group}]`);
269
+ lastDate = group;
270
+ }
271
+ lines.push(formatRow(row));
272
+ }
273
+ remaining = Math.max(0, remaining - workspaceRows.length);
274
+ }
275
+
276
+ if (otherRows.length > 0 && remaining > 0) {
277
+ lines.push('');
278
+ lines.push(`ALL SESSIONS (${otherRows.length}):`);
279
+ let lastDate: string | null = null;
280
+ for (const row of otherRows.slice(0, remaining)) {
281
+ const group = dateGroup(row.updatedAt);
282
+ if (group !== lastDate) {
283
+ lines.push(` [${group}]`);
284
+ lastDate = group;
285
+ }
286
+ lines.push(formatRow(row));
287
+ }
288
+ }
289
+
290
+ lines.push('');
291
+ lines.push('Switch with /sessions switch <id>, fork with /fork [id], or run /sessions to open interactive modal picker.');
292
+ return lines.join('\n');
293
+ }
294
+
188
295
  /**
189
296
  * Launch the interactive Session Picker modal.
190
297
  * Single Enter switches session or creates a new one immediately.
@@ -192,6 +299,7 @@ export function buildSessionPickerItems(
192
299
  export async function runInteractiveSessionPicker(
193
300
  prompt: {
194
301
  openLayer: (layer: unknown) => void;
302
+ root?: string | undefined;
195
303
  editor?: { clear: () => void };
196
304
  scheduleDraw?: () => void;
197
305
  updateModel?: (provider?: string, model?: string) => void;
@@ -199,9 +307,12 @@ export async function runInteractiveSessionPicker(
199
307
  },
200
308
  options: InteractiveSessionPickerOptions = {}
201
309
  ): Promise<string> {
202
- const workspace = options.workspace || process.cwd();
310
+ const workspace = options.workspace
311
+ || options.loop?.workspaceRoot
312
+ || prompt.root
313
+ || process.cwd();
203
314
  const sessions = listSessions();
204
- const activeId = getActiveSessionId();
315
+ const activeId = options.loop?.memoryManager?.sessionId || getActiveSessionId();
205
316
 
206
317
  const items = buildSessionPickerItems(sessions, activeId, workspace);
207
318
 
@@ -221,11 +332,21 @@ export async function runInteractiveSessionPicker(
221
332
  resolve(item || null);
222
333
  }
223
334
  });
224
- // Opening the picker should highlight a conversation, not an action that
225
- // creates a new one. Actions remain available above the dated list.
226
- const selected = items.findIndex(item => item.id === activeId);
227
- const firstConversation = items.findIndex(item => item.value.type === 'switch');
228
- layer.list.moveTo(selected >= 0 ? selected : Math.max(0, firstConversation), 15);
335
+ // Prefer the active session when it belongs to the current workspace,
336
+ // otherwise the newest conversation in the current workspace. When the
337
+ // current workspace is empty, keep focus at index 0 (+ New Session) so the
338
+ // workspace header and Empty indicator remain immediately visible on open.
339
+ const ordered = layer.list.all;
340
+ const activeWorkspaceIdx = ordered.findIndex(
341
+ item => item.section === 'workspace' && item.id === activeId
342
+ );
343
+ const firstWorkspaceIdx = ordered.findIndex(item => item.section === 'workspace');
344
+ const initialIndex = activeWorkspaceIdx >= 0
345
+ ? activeWorkspaceIdx
346
+ : firstWorkspaceIdx >= 0
347
+ ? firstWorkspaceIdx
348
+ : 0;
349
+ layer.list.moveTo(initialIndex, 15);
229
350
  prompt.openLayer(layer);
230
351
  });
231
352
 
@@ -294,7 +415,7 @@ export async function runInteractiveSessionPicker(
294
415
  syncSessionSurface(newSession, []);
295
416
 
296
417
  cleanPrompt();
297
- return `Started new session: "${cleanTitle(newSession.title)}" (${newSession.id}) in ${shortenPath(workspace)}.`;
418
+ return `Started new session: "${cleanTitle(newSession.title)}" (${newSession.id}) in ${shortenWorkspacePath(workspace)}.`;
298
419
  }
299
420
 
300
421
  // Case 2: Fork session into a new branch without copying permissions