@causyne/agent 1.20.82 → 1.20.84

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.82",
3
+ "version": "1.20.84",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
@@ -1,9 +1,10 @@
1
1
  // Continuum TUI Picker: interactive modal dialog for browsing and adopting peer agent sessions.
2
2
  // Authorship: Strict TypeScript (Causyne Agent).
3
3
  // @ts-expect-error untyped local TUI dialogs
4
- import { SelectLayer, TextLayer } from '../../tui/dialogs.js';
4
+ import { TextLayer } from '../../tui/dialogs.js';
5
5
  // @ts-expect-error untyped local TUI theme
6
6
  import { GLYPHS } from '../../tui/theme.js';
7
+ import { ContinuumPickerLayer } from './continuumPickerView.js';
7
8
  import { ContinuumScanner } from '../scanner.js';
8
9
  import { adoptContinuumSession } from '../ingest.js';
9
10
  function formatTimeAgo(timestamp) {
@@ -43,16 +44,26 @@ export async function runInteractiveContinuum(prompt, options = {}) {
43
44
  }
44
45
  const items = buildContinuumItems(sessions);
45
46
  const pickedSession = await new Promise((resolve) => {
46
- const layer = new SelectLayer({
47
- title: `Continuum · Cross-Agent Sessions (${sessions.length})`,
48
- placeholder: 'search past agent conversations (antigravity, opencode, codex, claude)...',
49
- emptyText: 'no matching sessions found',
50
- width: 78,
51
- height: 20,
52
- footer: `enter adopt session ${GLYPHS.dot} esc cancel`,
53
- items,
54
- onPick: (item) => {
55
- resolve(item ? item.value : null);
47
+ const layer = new ContinuumPickerLayer({
48
+ sessions: items,
49
+ onPick: (item) => resolve(item?.value || null),
50
+ onPreview: (session) => {
51
+ void openContinuumPreview(session.id, prompt, scanner)
52
+ .then((opened) => {
53
+ if (!opened)
54
+ prompt.openLayer(new TextLayer({
55
+ title: 'Continuum · Preview unavailable',
56
+ lines: ['This session could not be loaded.', 'It may have moved or been deleted.'],
57
+ width: 72,
58
+ height: 9
59
+ }));
60
+ })
61
+ .catch(() => prompt.openLayer(new TextLayer({
62
+ title: 'Continuum · Preview unavailable',
63
+ lines: ['The source agent session could not be read.'],
64
+ width: 72,
65
+ height: 9
66
+ })));
56
67
  }
57
68
  });
58
69
  prompt.openLayer(layer);
@@ -2,9 +2,10 @@
2
2
  // Authorship: Strict TypeScript (Causyne Agent).
3
3
 
4
4
  // @ts-expect-error untyped local TUI dialogs
5
- import { SelectLayer, TextLayer } from '../../tui/dialogs.js';
5
+ import { TextLayer } from '../../tui/dialogs.js';
6
6
  // @ts-expect-error untyped local TUI theme
7
7
  import { GLYPHS } from '../../tui/theme.js';
8
+ import { ContinuumPickerLayer } from './continuumPickerView.js';
8
9
  import type { ContinuumSessionSummary } from '../types.js';
9
10
  import { ContinuumScanner } from '../scanner.js';
10
11
  import { adoptContinuumSession } from '../ingest.js';
@@ -63,16 +64,25 @@ export async function runInteractiveContinuum(
63
64
  const items = buildContinuumItems(sessions);
64
65
 
65
66
  const pickedSession = await new Promise<ContinuumSessionSummary | null>((resolve) => {
66
- const layer = new SelectLayer({
67
- title: `Continuum · Cross-Agent Sessions (${sessions.length})`,
68
- placeholder: 'search past agent conversations (antigravity, opencode, codex, claude)...',
69
- emptyText: 'no matching sessions found',
70
- width: 78,
71
- height: 20,
72
- footer: `enter adopt session ${GLYPHS.dot} esc cancel`,
73
- items,
74
- onPick: (item: { value: ContinuumSessionSummary } | null) => {
75
- resolve(item ? item.value : null);
67
+ const layer = new ContinuumPickerLayer({
68
+ sessions: items,
69
+ onPick: (item) => resolve(item?.value || null),
70
+ onPreview: (session) => {
71
+ void openContinuumPreview(session.id, prompt, scanner)
72
+ .then((opened) => {
73
+ if (!opened) prompt.openLayer(new TextLayer({
74
+ title: 'Continuum · Preview unavailable',
75
+ lines: ['This session could not be loaded.', 'It may have moved or been deleted.'],
76
+ width: 72,
77
+ height: 9
78
+ }));
79
+ })
80
+ .catch(() => prompt.openLayer(new TextLayer({
81
+ title: 'Continuum · Preview unavailable',
82
+ lines: ['The source agent session could not be read.'],
83
+ width: 72,
84
+ height: 9
85
+ })));
76
86
  }
77
87
  });
78
88
  prompt.openLayer(layer);
@@ -0,0 +1,259 @@
1
+ /**
2
+ * Causyne Continuum: provider-aware, keyboard-operated session browser.
3
+ * This is a presentation-only layer over the existing SelectLayer/SelectList.
4
+ * No adapter, journal, tool policy or adoption behavior is changed here.
5
+ */
6
+ // @ts-expect-error The existing dialog component is implemented in JavaScript.
7
+ import { SelectLayer } from '../../tui/dialogs.js';
8
+ // @ts-expect-error The existing theme is implemented in JavaScript.
9
+ import { bold, dim, paint, GLYPHS } from '../../tui/theme.js';
10
+ import { safeDisplay, truncate, visibleWidth } from '../../tui/text.js';
11
+ const MAX_PANEL_HEIGHT = 34;
12
+ const MIN_DETAIL_WIDTH = 46;
13
+ const SOURCE_ORDER = [
14
+ 'codex', 'antigravity', 'opencode', 'claude_code', 'causyne', 'cursor'
15
+ ];
16
+ const PLATFORM_NAMES = {
17
+ codex: 'Codex',
18
+ antigravity: 'Antigravity',
19
+ opencode: 'OpenCode',
20
+ claude_code: 'Claude Code',
21
+ causyne: 'Causyne',
22
+ cursor: 'Cursor'
23
+ };
24
+ function clean(value) {
25
+ // safeDisplay strips control sequences that could corrupt a terminal frame.
26
+ return safeDisplay(String(value ?? '')).replace(/\s+/g, ' ').trim();
27
+ }
28
+ function shortWorkspace(value) {
29
+ const path = clean(value).replace(/\\/g, '/').replace(/\/+$/, '');
30
+ if (!path)
31
+ return 'Unknown workspace';
32
+ const parts = path.split('/').filter(Boolean);
33
+ return parts.length > 2 ? `…/${parts.slice(-2).join('/')}` : path;
34
+ }
35
+ function relativeTime(timestamp, now) {
36
+ if (!Number.isFinite(timestamp) || timestamp <= 0)
37
+ return 'unknown';
38
+ const seconds = Math.max(0, Math.floor((now - timestamp) / 1000));
39
+ if (seconds < 60)
40
+ return 'now';
41
+ if (seconds < 3600)
42
+ return `${Math.floor(seconds / 60)}m`;
43
+ if (seconds < 86400)
44
+ return `${Math.floor(seconds / 3600)}h`;
45
+ if (seconds < 7 * 86400)
46
+ return `${Math.floor(seconds / 86400)}d`;
47
+ return `${Math.floor(seconds / (7 * 86400))}w`;
48
+ }
49
+ function countLabel(count) {
50
+ if (!Number.isFinite(count) || count < 0)
51
+ return '0 msgs';
52
+ return `${Math.floor(count).toLocaleString('en-US')} ${count === 1 ? 'msg' : 'msgs'}`;
53
+ }
54
+ /** Fit two pieces of styled text in one terminal row, retaining the left title. */
55
+ function pairedRow(left, right, columns) {
56
+ const width = Math.max(1, Math.floor(columns));
57
+ const rightWidth = visibleWidth(right);
58
+ if (!right || width < 45 || rightWidth > width - 20)
59
+ return truncate(left, width, '…');
60
+ const title = truncate(left, Math.max(1, width - rightWidth - 2), '…');
61
+ return title + ' '.repeat(Math.max(1, width - visibleWidth(title) - rightWidth)) + right;
62
+ }
63
+ function sourceName(value) {
64
+ return clean(value.sourceLabel) || PLATFORM_NAMES[value.sourcePlatform] || 'Other';
65
+ }
66
+ /**
67
+ * Group by agent with recency inside each source. A stable tie-breaker means
68
+ * the selected session never jumps unpredictably between redraws.
69
+ */
70
+ export function sortContinuumItems(items) {
71
+ const order = new Map(SOURCE_ORDER.map((platform, index) => [platform, index]));
72
+ return [...items].sort((a, b) => {
73
+ const groupA = order.get(a.value.sourcePlatform) ?? SOURCE_ORDER.length;
74
+ const groupB = order.get(b.value.sourcePlatform) ?? SOURCE_ORDER.length;
75
+ return groupA - groupB
76
+ || (Number(b.value.updatedAt) || 0) - (Number(a.value.updatedAt) || 0)
77
+ || a.value.id.localeCompare(b.value.id);
78
+ });
79
+ }
80
+ function renderedItem(item, selected, width, now) {
81
+ const title = clean(item.value.title) || 'Untitled session';
82
+ const prefix = selected ? ` ${paint('accent', '▸')} ` : ' ';
83
+ const stats = dim(`${countLabel(item.value.messageCount)} ${GLYPHS.dot} ${relativeTime(item.value.updatedAt, now)}`);
84
+ const headline = pairedRow(prefix + (selected ? bold(paint('ink', title)) : paint('ink', title)), stats, width);
85
+ const workspace = clean(item.value.workspacePath);
86
+ const sub = ` ${dim(shortWorkspace(workspace))}`;
87
+ return [truncate(headline, width, '…'), truncate(sub, width, '…')];
88
+ }
89
+ /**
90
+ * Render a viewport of category headings + TWO-row session entries.
91
+ * Headers never occupy the only remaining row; selected items stay visible.
92
+ */
93
+ export function renderContinuumWindow(entries, start, selected, width, budget, now = Date.now()) {
94
+ const rows = [];
95
+ const safeWidth = Math.max(1, Math.floor(width));
96
+ const allowed = Math.max(0, Math.floor(budget));
97
+ let lastIndex = start - 1;
98
+ let itemCount = 0;
99
+ let previousGroup = null;
100
+ for (let index = start; index < entries.length; index++) {
101
+ const item = entries[index]?.item;
102
+ if (!item)
103
+ continue;
104
+ const group = sourceName(item.value);
105
+ const needHeader = group !== previousGroup;
106
+ const needed = 2 + (needHeader ? 1 : 0);
107
+ if (rows.length + needed > allowed) {
108
+ // With only two rows remaining, show the item without an orphaned header.
109
+ if (!(needHeader && rows.length + 2 <= allowed))
110
+ break;
111
+ }
112
+ else if (needHeader) {
113
+ rows.push(dim(` ${truncate(group.toUpperCase(), Math.max(1, safeWidth - 5), '…')}`));
114
+ }
115
+ rows.push(...renderedItem(item, index === selected, safeWidth, now));
116
+ lastIndex = index;
117
+ itemCount++;
118
+ previousGroup = group;
119
+ }
120
+ return { rows, firstIndex: start, lastIndex, itemCount };
121
+ }
122
+ export class ContinuumPickerLayer extends SelectLayer {
123
+ items;
124
+ scopes;
125
+ onPreview;
126
+ scopeIndex = 0;
127
+ visibleItems = 5;
128
+ constructor(options) {
129
+ const items = sortContinuumItems(options.sessions);
130
+ super({
131
+ title: `Continuum · ${items.length} recent cross-agent sessions`,
132
+ width: 112,
133
+ height: MAX_PANEL_HEIGHT,
134
+ footer: `↑↓ move ${GLYPHS.dot} tab source ${GLYPHS.dot} F2 preview ${GLYPHS.dot} enter adopt ${GLYPHS.dot} esc close`,
135
+ placeholder: 'Search sessions, projects, or IDs',
136
+ emptyText: 'No matching sessions',
137
+ items,
138
+ onPick: options.onPick
139
+ });
140
+ this.items = items;
141
+ this.scopes = ['all', ...SOURCE_ORDER.filter(platform => items.some(item => item.value.sourcePlatform === platform))];
142
+ this.onPreview = options.onPreview;
143
+ }
144
+ get scope() { return this.scopes[this.scopeIndex] ?? 'all'; }
145
+ get availableScopes() { return this.scopes; }
146
+ preferredHeight() {
147
+ // No fixed 34-row empty frame when the machine has only a few sessions.
148
+ const items = this.list.filtered.length;
149
+ const categories = new Set(this.list.filtered.map(({ item }) => sourceName(item.value))).size;
150
+ return Math.min(MAX_PANEL_HEIGHT, Math.max(12, 3 + 4 + 2 + items * 2 + categories));
151
+ }
152
+ setScope(direction) {
153
+ const oldId = this.list.current?.value.id;
154
+ this.scopeIndex = (this.scopeIndex + direction + this.scopes.length) % this.scopes.length;
155
+ const scope = this.scope;
156
+ const chosen = scope === 'all' ? this.items :
157
+ this.items.filter(item => item.value.sourcePlatform === scope);
158
+ const query = this.list.query;
159
+ this.list.setItems(chosen);
160
+ this.list.query = query;
161
+ this.list.refilter();
162
+ const preserved = this.list.filtered.findIndex(({ item }) => item.value.id === oldId);
163
+ this.list.selected = preserved >= 0 ? preserved : 0;
164
+ this.list.offset = 0;
165
+ }
166
+ key(event) {
167
+ if (!event)
168
+ return null;
169
+ if (event.name === 'tab') {
170
+ this.setScope(event.shift ? -1 : 1);
171
+ return 'handled';
172
+ }
173
+ if (event.name === 'f2') {
174
+ const current = this.list.current;
175
+ if (current && this.onPreview)
176
+ this.onPreview(current.value);
177
+ return 'handled';
178
+ }
179
+ if (event.name === 'pageup' || event.name === 'pagedown') {
180
+ const direction = event.name === 'pageup' ? -1 : 1;
181
+ this.list.moveTo(this.list.selected + direction * Math.max(1, this.visibleItems - 1), Math.max(1, this.visibleItems));
182
+ return 'handled';
183
+ }
184
+ const query = this.list.query;
185
+ const result = super.key(event);
186
+ if (this.list.query !== query) {
187
+ this.list.selected = 0;
188
+ this.list.offset = 0;
189
+ }
190
+ return result;
191
+ }
192
+ body(width, height) {
193
+ const w = Math.max(8, Math.floor(width));
194
+ const h = Math.max(1, Math.floor(height));
195
+ const rows = [];
196
+ const scope = this.scope;
197
+ const label = scope === 'all' ? 'ALL SOURCES' : PLATFORM_NAMES[scope];
198
+ const filtered = this.list.filtered;
199
+ const count = filtered.length;
200
+ const total = this.items.length;
201
+ const narrow = w < MIN_DETAIL_WIDTH;
202
+ const sourceText = ` ${paint('accent', label.toUpperCase())}`;
203
+ rows.push(pairedRow(sourceText, w >= 49 ? dim(`${count} / ${total} sessions ${this.scopeIndex + 1}/${this.scopes.length} sources`) : '', w));
204
+ const lead = ` ${paint('accent', GLYPHS.arrow)} `;
205
+ const room = Math.max(1, w - visibleWidth(lead) - 1);
206
+ const query = clean(this.list.query);
207
+ let tail = query;
208
+ while (visibleWidth(tail) > room)
209
+ tail = [...tail].slice(1).join('');
210
+ const shown = tail || dim(narrow ? 'Search sessions...' : 'Search by title, project, provider, or ID...');
211
+ rows.push(lead + truncate(shown, room, '…'));
212
+ this.cursor = { x: Math.min(w - 1, visibleWidth(lead) + visibleWidth(tail)), y: 1 };
213
+ rows.push(paint('rule', '─'.repeat(w)));
214
+ // Small terminals favor visible list navigation over the detail inspector.
215
+ const details = h >= 18 ? 5 : h >= 12 ? 3 : h >= 9 ? 1 : 0;
216
+ const budget = Math.max(0, h - 3 - details);
217
+ if (budget > 0 && count === 0) {
218
+ rows.push('');
219
+ if (rows.length < h - details)
220
+ rows.push(dim(' No sessions match this filter.'));
221
+ if (rows.length < h - details)
222
+ rows.push(dim(' Tab changes source. Ctrl+U clears search.'));
223
+ }
224
+ else if (budget > 0) {
225
+ const selected = Math.min(Math.max(0, this.list.selected), count - 1);
226
+ let from = Math.min(Math.max(0, this.list.offset), selected);
227
+ let output = renderContinuumWindow(filtered, from, selected, w, budget);
228
+ while (output.lastIndex < selected && from < selected) {
229
+ from++;
230
+ output = renderContinuumWindow(filtered, from, selected, w, budget);
231
+ }
232
+ this.list.offset = from;
233
+ this.visibleItems = Math.max(1, output.itemCount);
234
+ this.list.lastItemRows = Math.max(1, this.visibleItems);
235
+ rows.push(...output.rows);
236
+ }
237
+ while (rows.length < h - details)
238
+ rows.push('');
239
+ const selected = this.list.current?.value;
240
+ if (details > 0) {
241
+ rows.push(paint('rule', '─'.repeat(w)));
242
+ }
243
+ if (details >= 3) {
244
+ const heading = selected ? ` ${sourceName(selected)}` : ' No session selected';
245
+ const countText = selected ? dim(countLabel(selected.messageCount)) : '';
246
+ rows.push(pairedRow(heading, countText, w));
247
+ rows.push(dim(' ' + truncate(selected ? shortWorkspace(selected.workspacePath) : 'Change the source or search query.', Math.max(1, w - 3), '…')));
248
+ }
249
+ if (details >= 5) {
250
+ const snippet = selected ? clean(selected.snippet) : '';
251
+ rows.push(dim(' ' + truncate(snippet || 'No excerpt available', Math.max(1, w - 3), '…')));
252
+ const id = selected ? clean(selected.id) : '';
253
+ rows.push(dim(' ' + truncate(id || 'No session ID', Math.max(1, w - 3), '…')));
254
+ }
255
+ while (rows.length < h)
256
+ rows.push('');
257
+ return rows.slice(0, h).map(row => truncate(row, w, '…'));
258
+ }
259
+ }
@@ -0,0 +1,321 @@
1
+ /**
2
+ * Causyne Continuum: provider-aware, keyboard-operated session browser.
3
+ * This is a presentation-only layer over the existing SelectLayer/SelectList.
4
+ * No adapter, journal, tool policy or adoption behavior is changed here.
5
+ */
6
+ // @ts-expect-error The existing dialog component is implemented in JavaScript.
7
+ import { SelectLayer } from '../../tui/dialogs.js';
8
+ // @ts-expect-error The existing theme is implemented in JavaScript.
9
+ import { bold, dim, paint, GLYPHS } from '../../tui/theme.js';
10
+ import { safeDisplay, truncate, visibleWidth } from '../../tui/text.js';
11
+ import type { AgentPlatform, ContinuumSessionSummary } from '../types.js';
12
+
13
+ export interface ContinuumPickerItem {
14
+ label: string;
15
+ category: string;
16
+ description: string;
17
+ searchText: string;
18
+ hint?: string;
19
+ value: ContinuumSessionSummary;
20
+ }
21
+
22
+ export interface ContinuumPickerViewOptions {
23
+ sessions: ContinuumPickerItem[];
24
+ onPick: (item: ContinuumPickerItem | null) => void;
25
+ onPreview?: (session: ContinuumSessionSummary) => void;
26
+ }
27
+
28
+ interface KeyEvent {
29
+ name?: string;
30
+ ctrl?: boolean;
31
+ shift?: boolean;
32
+ meta?: boolean;
33
+ sequence?: string;
34
+ text?: string;
35
+ }
36
+
37
+ interface FilteredEntry { item: ContinuumPickerItem; }
38
+ interface ListWindow {
39
+ rows: string[];
40
+ firstIndex: number;
41
+ lastIndex: number;
42
+ itemCount: number;
43
+ }
44
+
45
+ const MAX_PANEL_HEIGHT = 34;
46
+ const MIN_DETAIL_WIDTH = 46;
47
+ const SOURCE_ORDER: AgentPlatform[] = [
48
+ 'codex', 'antigravity', 'opencode', 'claude_code', 'causyne', 'cursor'
49
+ ];
50
+ const PLATFORM_NAMES: Record<AgentPlatform, string> = {
51
+ codex: 'Codex',
52
+ antigravity: 'Antigravity',
53
+ opencode: 'OpenCode',
54
+ claude_code: 'Claude Code',
55
+ causyne: 'Causyne',
56
+ cursor: 'Cursor'
57
+ };
58
+
59
+ type Scope = AgentPlatform | 'all';
60
+
61
+ function clean(value: unknown): string {
62
+ // safeDisplay strips control sequences that could corrupt a terminal frame.
63
+ return safeDisplay(String(value ?? '')).replace(/\s+/g, ' ').trim();
64
+ }
65
+
66
+ function shortWorkspace(value: string): string {
67
+ const path = clean(value).replace(/\\/g, '/').replace(/\/+$/, '');
68
+ if (!path) return 'Unknown workspace';
69
+ const parts = path.split('/').filter(Boolean);
70
+ return parts.length > 2 ? `…/${parts.slice(-2).join('/')}` : path;
71
+ }
72
+
73
+ function relativeTime(timestamp: number, now: number): string {
74
+ if (!Number.isFinite(timestamp) || timestamp <= 0) return 'unknown';
75
+ const seconds = Math.max(0, Math.floor((now - timestamp) / 1000));
76
+ if (seconds < 60) return 'now';
77
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m`;
78
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h`;
79
+ if (seconds < 7 * 86400) return `${Math.floor(seconds / 86400)}d`;
80
+ return `${Math.floor(seconds / (7 * 86400))}w`;
81
+ }
82
+
83
+ function countLabel(count: number): string {
84
+ if (!Number.isFinite(count) || count < 0) return '0 msgs';
85
+ return `${Math.floor(count).toLocaleString('en-US')} ${count === 1 ? 'msg' : 'msgs'}`;
86
+ }
87
+
88
+ /** Fit two pieces of styled text in one terminal row, retaining the left title. */
89
+ function pairedRow(left: string, right: string, columns: number): string {
90
+ const width = Math.max(1, Math.floor(columns));
91
+ const rightWidth = visibleWidth(right);
92
+ if (!right || width < 45 || rightWidth > width - 20) return truncate(left, width, '…');
93
+ const title = truncate(left, Math.max(1, width - rightWidth - 2), '…');
94
+ return title + ' '.repeat(Math.max(1, width - visibleWidth(title) - rightWidth)) + right;
95
+ }
96
+
97
+ function sourceName(value: ContinuumSessionSummary): string {
98
+ return clean(value.sourceLabel) || PLATFORM_NAMES[value.sourcePlatform] || 'Other';
99
+ }
100
+
101
+ /**
102
+ * Group by agent with recency inside each source. A stable tie-breaker means
103
+ * the selected session never jumps unpredictably between redraws.
104
+ */
105
+ export function sortContinuumItems(items: ContinuumPickerItem[]): ContinuumPickerItem[] {
106
+ const order = new Map(SOURCE_ORDER.map((platform, index) => [platform, index]));
107
+ return [...items].sort((a, b) => {
108
+ const groupA = order.get(a.value.sourcePlatform) ?? SOURCE_ORDER.length;
109
+ const groupB = order.get(b.value.sourcePlatform) ?? SOURCE_ORDER.length;
110
+ return groupA - groupB
111
+ || (Number(b.value.updatedAt) || 0) - (Number(a.value.updatedAt) || 0)
112
+ || a.value.id.localeCompare(b.value.id);
113
+ });
114
+ }
115
+
116
+ function renderedItem(
117
+ item: ContinuumPickerItem, selected: boolean, width: number, now: number
118
+ ): string[] {
119
+ const title = clean(item.value.title) || 'Untitled session';
120
+ const prefix = selected ? ` ${paint('accent', '▸')} ` : ' ';
121
+ const stats = dim(`${countLabel(item.value.messageCount)} ${GLYPHS.dot} ${relativeTime(item.value.updatedAt, now)}`);
122
+ const headline = pairedRow(
123
+ prefix + (selected ? bold(paint('ink', title)) : paint('ink', title)), stats, width
124
+ );
125
+ const workspace = clean(item.value.workspacePath);
126
+ const sub = ` ${dim(shortWorkspace(workspace))}`;
127
+ return [truncate(headline, width, '…'), truncate(sub, width, '…')];
128
+ }
129
+
130
+ /**
131
+ * Render a viewport of category headings + TWO-row session entries.
132
+ * Headers never occupy the only remaining row; selected items stay visible.
133
+ */
134
+ export function renderContinuumWindow(
135
+ entries: FilteredEntry[], start: number, selected: number,
136
+ width: number, budget: number, now = Date.now()
137
+ ): ListWindow {
138
+ const rows: string[] = [];
139
+ const safeWidth = Math.max(1, Math.floor(width));
140
+ const allowed = Math.max(0, Math.floor(budget));
141
+ let lastIndex = start - 1;
142
+ let itemCount = 0;
143
+ let previousGroup: string | null = null;
144
+ for (let index = start; index < entries.length; index++) {
145
+ const item = entries[index]?.item;
146
+ if (!item) continue;
147
+ const group = sourceName(item.value);
148
+ const needHeader = group !== previousGroup;
149
+ const needed = 2 + (needHeader ? 1 : 0);
150
+ if (rows.length + needed > allowed) {
151
+ // With only two rows remaining, show the item without an orphaned header.
152
+ if (!(needHeader && rows.length + 2 <= allowed)) break;
153
+ } else if (needHeader) {
154
+ rows.push(dim(` ${truncate(group.toUpperCase(), Math.max(1, safeWidth - 5), '…')}`));
155
+ }
156
+ rows.push(...renderedItem(item, index === selected, safeWidth, now));
157
+ lastIndex = index;
158
+ itemCount++;
159
+ previousGroup = group;
160
+ }
161
+ return { rows, firstIndex: start, lastIndex, itemCount };
162
+ }
163
+
164
+ export class ContinuumPickerLayer extends SelectLayer {
165
+ // Inherited instance fields from the existing JavaScript SelectLayer.
166
+ declare list: {
167
+ all: ContinuumPickerItem[];
168
+ filtered: FilteredEntry[];
169
+ selected: number;
170
+ offset: number;
171
+ query: string;
172
+ current: ContinuumPickerItem | null;
173
+ lastItemRows?: number;
174
+ setItems(items: ContinuumPickerItem[]): void;
175
+ moveTo(index: number, visibleRows: number): void;
176
+ refilter(): void;
177
+ };
178
+ declare cursor: { x: number; y: number } | null;
179
+ private readonly items: ContinuumPickerItem[];
180
+ private readonly scopes: Scope[];
181
+ private readonly onPreview: ((session: ContinuumSessionSummary) => void) | undefined;
182
+ private scopeIndex = 0;
183
+ private visibleItems = 5;
184
+
185
+ constructor(options: ContinuumPickerViewOptions) {
186
+ const items = sortContinuumItems(options.sessions);
187
+ super({
188
+ title: `Continuum · ${items.length} recent cross-agent sessions`,
189
+ width: 112,
190
+ height: MAX_PANEL_HEIGHT,
191
+ footer: `↑↓ move ${GLYPHS.dot} tab source ${GLYPHS.dot} F2 preview ${GLYPHS.dot} enter adopt ${GLYPHS.dot} esc close`,
192
+ placeholder: 'Search sessions, projects, or IDs',
193
+ emptyText: 'No matching sessions',
194
+ items,
195
+ onPick: options.onPick
196
+ });
197
+ this.items = items;
198
+ this.scopes = ['all', ...SOURCE_ORDER.filter(platform =>
199
+ items.some(item => item.value.sourcePlatform === platform))];
200
+ this.onPreview = options.onPreview;
201
+ }
202
+
203
+ get scope(): Scope { return this.scopes[this.scopeIndex] ?? 'all'; }
204
+ get availableScopes(): readonly Scope[] { return this.scopes; }
205
+
206
+ preferredHeight(): number {
207
+ // No fixed 34-row empty frame when the machine has only a few sessions.
208
+ const items = this.list.filtered.length;
209
+ const categories = new Set(this.list.filtered.map(({ item }: FilteredEntry) => sourceName(item.value))).size;
210
+ return Math.min(MAX_PANEL_HEIGHT, Math.max(12, 3 + 4 + 2 + items * 2 + categories));
211
+ }
212
+
213
+ private setScope(direction: number): void {
214
+ const oldId = this.list.current?.value.id;
215
+ this.scopeIndex = (this.scopeIndex + direction + this.scopes.length) % this.scopes.length;
216
+ const scope = this.scope;
217
+ const chosen = scope === 'all' ? this.items :
218
+ this.items.filter(item => item.value.sourcePlatform === scope);
219
+ const query = this.list.query;
220
+ this.list.setItems(chosen);
221
+ this.list.query = query;
222
+ this.list.refilter();
223
+ const preserved = this.list.filtered.findIndex(({ item }: FilteredEntry) => item.value.id === oldId);
224
+ this.list.selected = preserved >= 0 ? preserved : 0;
225
+ this.list.offset = 0;
226
+ }
227
+
228
+ key(event: KeyEvent | null): string | null {
229
+ if (!event) return null;
230
+ if (event.name === 'tab') {
231
+ this.setScope(event.shift ? -1 : 1);
232
+ return 'handled';
233
+ }
234
+ if (event.name === 'f2') {
235
+ const current = this.list.current;
236
+ if (current && this.onPreview) this.onPreview(current.value);
237
+ return 'handled';
238
+ }
239
+ if (event.name === 'pageup' || event.name === 'pagedown') {
240
+ const direction = event.name === 'pageup' ? -1 : 1;
241
+ this.list.moveTo(this.list.selected + direction * Math.max(1, this.visibleItems - 1),
242
+ Math.max(1, this.visibleItems));
243
+ return 'handled';
244
+ }
245
+ const query = this.list.query;
246
+ const result = super.key(event);
247
+ if (this.list.query !== query) {
248
+ this.list.selected = 0;
249
+ this.list.offset = 0;
250
+ }
251
+ return result;
252
+ }
253
+
254
+ body(width: number, height: number): string[] {
255
+ const w = Math.max(8, Math.floor(width));
256
+ const h = Math.max(1, Math.floor(height));
257
+ const rows: string[] = [];
258
+ const scope = this.scope;
259
+ const label = scope === 'all' ? 'ALL SOURCES' : PLATFORM_NAMES[scope];
260
+ const filtered = this.list.filtered;
261
+ const count = filtered.length;
262
+ const total = this.items.length;
263
+ const narrow = w < MIN_DETAIL_WIDTH;
264
+
265
+ const sourceText = ` ${paint('accent', label.toUpperCase())}`;
266
+ rows.push(pairedRow(sourceText,
267
+ w >= 49 ? dim(`${count} / ${total} sessions ${this.scopeIndex + 1}/${this.scopes.length} sources`) : '', w));
268
+
269
+ const lead = ` ${paint('accent', GLYPHS.arrow)} `;
270
+ const room = Math.max(1, w - visibleWidth(lead) - 1);
271
+ const query = clean(this.list.query);
272
+ let tail = query;
273
+ while (visibleWidth(tail) > room) tail = [...tail].slice(1).join('');
274
+ const shown = tail || dim(narrow ? 'Search sessions...' : 'Search by title, project, provider, or ID...');
275
+ rows.push(lead + truncate(shown, room, '…'));
276
+ this.cursor = { x: Math.min(w - 1, visibleWidth(lead) + visibleWidth(tail)), y: 1 };
277
+ rows.push(paint('rule', '─'.repeat(w)));
278
+
279
+ // Small terminals favor visible list navigation over the detail inspector.
280
+ const details = h >= 18 ? 5 : h >= 12 ? 3 : h >= 9 ? 1 : 0;
281
+ const budget = Math.max(0, h - 3 - details);
282
+ if (budget > 0 && count === 0) {
283
+ rows.push('');
284
+ if (rows.length < h - details) rows.push(dim(' No sessions match this filter.'));
285
+ if (rows.length < h - details) rows.push(dim(' Tab changes source. Ctrl+U clears search.'));
286
+ } else if (budget > 0) {
287
+ const selected = Math.min(Math.max(0, this.list.selected), count - 1);
288
+ let from = Math.min(Math.max(0, this.list.offset), selected);
289
+ let output = renderContinuumWindow(filtered, from, selected, w, budget);
290
+ while (output.lastIndex < selected && from < selected) {
291
+ from++;
292
+ output = renderContinuumWindow(filtered, from, selected, w, budget);
293
+ }
294
+ this.list.offset = from;
295
+ this.visibleItems = Math.max(1, output.itemCount);
296
+ this.list.lastItemRows = Math.max(1, this.visibleItems);
297
+ rows.push(...output.rows);
298
+ }
299
+ while (rows.length < h - details) rows.push('');
300
+
301
+ const selected = this.list.current?.value;
302
+ if (details > 0) {
303
+ rows.push(paint('rule', '─'.repeat(w)));
304
+ }
305
+ if (details >= 3) {
306
+ const heading = selected ? ` ${sourceName(selected)}` : ' No session selected';
307
+ const countText = selected ? dim(countLabel(selected.messageCount)) : '';
308
+ rows.push(pairedRow(heading, countText, w));
309
+ rows.push(dim(' ' + truncate(selected ? shortWorkspace(selected.workspacePath) : 'Change the source or search query.',
310
+ Math.max(1, w - 3), '…')));
311
+ }
312
+ if (details >= 5) {
313
+ const snippet = selected ? clean(selected.snippet) : '';
314
+ rows.push(dim(' ' + truncate(snippet || 'No excerpt available', Math.max(1, w - 3), '…')));
315
+ const id = selected ? clean(selected.id) : '';
316
+ rows.push(dim(' ' + truncate(id || 'No session ID', Math.max(1, w - 3), '…')));
317
+ }
318
+ while (rows.length < h) rows.push('');
319
+ return rows.slice(0, h).map(row => truncate(row, w, '…'));
320
+ }
321
+ }
@@ -1,6 +1,7 @@
1
1
  // Chatbox Clipboard Manager: surgical operations for copy, paste, and CRLF normalization.
2
2
  // Supports native terminal mouse selection, readline kill/yank, Alt+C/Alt+W/Alt+V, and /copy /paste commands.
3
3
  import { readClipboardSync, writeClipboardSync, emitOsc52Copy } from './clipboardSync.js';
4
+ import { stripAnsi } from './text.js';
4
5
  import { readClipboardImageSync, formatByteSize, loadLocalImageAttachment, extractPastedFilePath, isLocalImageFile } from './clipboardImage.js';
5
6
  export { loadLocalImageAttachment, extractPastedFilePath, isLocalImageFile };
6
7
  /**
@@ -10,10 +11,12 @@ export { loadLocalImageAttachment, extractPastedFilePath, isLocalImageFile };
10
11
  export function normalizeClipboardText(raw) {
11
12
  if (typeof raw !== 'string')
12
13
  return '';
13
- return raw
14
+ // Strip CSI/OSC *before* removing C0; deleting ESC first leaves `[31m`
15
+ // and mouse-control tails as user-visible text. Preserve LF and TAB.
16
+ return stripAnsi(raw)
14
17
  .replace(/\r\n/g, '\n')
15
18
  .replace(/\r/g, '\n')
16
- .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
19
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, '');
17
20
  }
18
21
  /**
19
22
  * Copy text to system clipboard and terminal emulator (via OSC 52).
@@ -48,7 +51,18 @@ export function copyChatboxInput(prompt) {
48
51
  * as well as drag-and-dropped local image file paths and empty bracketed pastes.
49
52
  */
50
53
  export function pasteIntoChatbox(prompt, fallbackText) {
54
+ const MAX_CHATBOX_BYTES = 2 * 1024 * 1024;
51
55
  const clean = normalizeClipboardText(fallbackText);
56
+ const fits = (text) => {
57
+ const existing = prompt.editor.getText();
58
+ if (Buffer.byteLength(existing, 'utf8') + Buffer.byteLength(text, 'utf8') <= MAX_CHATBOX_BYTES)
59
+ return true;
60
+ prompt.notice = 'Paste exceeds 2 MiB; input unchanged. Attach the file instead.';
61
+ prompt.scheduleDraw();
62
+ return false;
63
+ };
64
+ if (clean && !fits(clean))
65
+ return { success: false, notice: prompt.notice, text: '' };
52
66
  // 1. If fallbackText was provided (e.g. drag & drop or file paste), check if it's a local image file
53
67
  if (clean) {
54
68
  const filePath = extractPastedFilePath(clean);
@@ -96,13 +110,15 @@ export function pasteIntoChatbox(prompt, fallbackText) {
96
110
  if (typeof prompt.refreshCompletion === 'function') {
97
111
  prompt.refreshCompletion();
98
112
  }
99
- prompt.notice = 'pasted from clipboard';
113
+ prompt.notice = `pasted ${clean.split('\n').length} ${clean.includes('\n') ? 'lines' : 'line'} · ${Buffer.byteLength(clean, 'utf8').toLocaleString()} bytes`;
100
114
  prompt.scheduleDraw();
101
115
  return { success: true, notice: prompt.notice, text: clean, isImage: false };
102
116
  }
103
117
  // 4. No fallbackText provided and no clipboard image: read text from clipboard
104
118
  const clipText = normalizeClipboardText(readClipboardSync());
105
119
  if (clipText) {
120
+ if (!fits(clipText))
121
+ return { success: false, notice: prompt.notice, text: '' };
106
122
  const filePath = extractPastedFilePath(clipText);
107
123
  const localImg = loadLocalImageAttachment(filePath);
108
124
  if (localImg) {
@@ -124,7 +140,7 @@ export function pasteIntoChatbox(prompt, fallbackText) {
124
140
  if (typeof prompt.refreshCompletion === 'function') {
125
141
  prompt.refreshCompletion();
126
142
  }
127
- prompt.notice = 'pasted from clipboard';
143
+ prompt.notice = `pasted ${clipText.split('\n').length} ${clipText.includes('\n') ? 'lines' : 'line'} · ${Buffer.byteLength(clipText, 'utf8').toLocaleString()} bytes`;
128
144
  prompt.scheduleDraw();
129
145
  return { success: true, notice: prompt.notice, text: clipText, isImage: false };
130
146
  }
@@ -2,6 +2,7 @@
2
2
  // Supports native terminal mouse selection, readline kill/yank, Alt+C/Alt+W/Alt+V, and /copy /paste commands.
3
3
 
4
4
  import { readClipboardSync, writeClipboardSync, emitOsc52Copy } from './clipboardSync.js';
5
+ import { stripAnsi } from './text.js';
5
6
  import {
6
7
  readClipboardImageSync,
7
8
  formatByteSize,
@@ -59,10 +60,12 @@ export interface ChatboxCommandContext {
59
60
  */
60
61
  export function normalizeClipboardText(raw: unknown): string {
61
62
  if (typeof raw !== 'string') return '';
62
- return raw
63
+ // Strip CSI/OSC *before* removing C0; deleting ESC first leaves `[31m`
64
+ // and mouse-control tails as user-visible text. Preserve LF and TAB.
65
+ return stripAnsi(raw)
63
66
  .replace(/\r\n/g, '\n')
64
67
  .replace(/\r/g, '\n')
65
- .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '');
68
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g, '');
66
69
  }
67
70
 
68
71
  /**
@@ -102,7 +105,16 @@ export function pasteIntoChatbox(
102
105
  prompt: ChatboxPrompt,
103
106
  fallbackText?: string
104
107
  ): { success: boolean; notice: string; text: string; isImage?: boolean } {
108
+ const MAX_CHATBOX_BYTES = 2 * 1024 * 1024;
105
109
  const clean = normalizeClipboardText(fallbackText);
110
+ const fits = (text: string): boolean => {
111
+ const existing = prompt.editor.getText();
112
+ if (Buffer.byteLength(existing, 'utf8') + Buffer.byteLength(text, 'utf8') <= MAX_CHATBOX_BYTES) return true;
113
+ prompt.notice = 'Paste exceeds 2 MiB; input unchanged. Attach the file instead.';
114
+ prompt.scheduleDraw();
115
+ return false;
116
+ };
117
+ if (clean && !fits(clean)) return { success: false, notice: prompt.notice, text: '' };
106
118
 
107
119
  // 1. If fallbackText was provided (e.g. drag & drop or file paste), check if it's a local image file
108
120
  if (clean) {
@@ -153,7 +165,7 @@ export function pasteIntoChatbox(
153
165
  if (typeof prompt.refreshCompletion === 'function') {
154
166
  prompt.refreshCompletion();
155
167
  }
156
- prompt.notice = 'pasted from clipboard';
168
+ prompt.notice = `pasted ${clean.split('\n').length} ${clean.includes('\n') ? 'lines' : 'line'} · ${Buffer.byteLength(clean, 'utf8').toLocaleString()} bytes`;
157
169
  prompt.scheduleDraw();
158
170
  return { success: true, notice: prompt.notice, text: clean, isImage: false };
159
171
  }
@@ -161,6 +173,7 @@ export function pasteIntoChatbox(
161
173
  // 4. No fallbackText provided and no clipboard image: read text from clipboard
162
174
  const clipText = normalizeClipboardText(readClipboardSync());
163
175
  if (clipText) {
176
+ if (!fits(clipText)) return { success: false, notice: prompt.notice, text: '' };
164
177
  const filePath = extractPastedFilePath(clipText);
165
178
  const localImg = loadLocalImageAttachment(filePath);
166
179
  if (localImg) {
@@ -183,7 +196,7 @@ export function pasteIntoChatbox(
183
196
  if (typeof prompt.refreshCompletion === 'function') {
184
197
  prompt.refreshCompletion();
185
198
  }
186
- prompt.notice = 'pasted from clipboard';
199
+ prompt.notice = `pasted ${clipText.split('\n').length} ${clipText.includes('\n') ? 'lines' : 'line'} · ${Buffer.byteLength(clipText, 'utf8').toLocaleString()} bytes`;
187
200
  prompt.scheduleDraw();
188
201
  return { success: true, notice: prompt.notice, text: clipText, isImage: false };
189
202
  }
package/src/tui/keys.js CHANGED
@@ -82,6 +82,9 @@ export class KeyDecoder {
82
82
  this.pending = Buffer.alloc(0);
83
83
  this.inPaste = false;
84
84
  this.pasteBuffer = '';
85
+ this.pasteChunks = [];
86
+ this.pasteByteLength = 0;
87
+ this.pasteOverflow = false;
85
88
  }
86
89
 
87
90
  /** Feed a chunk; get back every complete key event it contained. */
@@ -103,6 +106,17 @@ export class KeyDecoder {
103
106
  return events;
104
107
  }
105
108
 
109
+ /** Clear an abandoned control sequence rather than swallowing later typing. */
110
+ drainIncomplete() {
111
+ if (this.inPaste || this.pending.length === 0) return [];
112
+ const tail = this.pending.toString('utf8');
113
+ this.pending = Buffer.alloc(0);
114
+ if (tail === '[<') return [makeKey('char', { text: '[', sequence: '[' }),
115
+ makeKey('char', { text: '<', sequence: '<' })];
116
+ if (tail === '[') return [makeKey('char', { text: '[', sequence: '[' })];
117
+ return [makeKey('unknown', { sequence: '' })];
118
+ }
119
+
106
120
  /** Decode one event at `offset`. Returns bytes consumed, or 0 if incomplete. */
107
121
  step(buffer, offset, events) {
108
122
  // Inside a paste, everything is literal text until the closing marker. The
@@ -113,22 +127,19 @@ export class KeyDecoder {
113
127
 
114
128
  if (byte === 0x1b) return this.stepEscape(buffer, offset, events);
115
129
 
116
- // Orphaned SGR mouse sequence: [ < b ; x ; y M|m
117
- // Occurs when \x1b is consumed on a chunk boundary or dropped over PTY.
118
- // Intercepting here prevents raw sequence strings like `[<64;119;43M` from
119
- // leaking into the prompt input box as literal character keystrokes.
120
- if (byte === 0x5b && buffer.length - offset >= 3 && buffer[offset + 1] === 0x3c) {
130
+ // Orphaned SGR report: `ESC` may be lost before `[<b;x;yM`.
131
+ // Only buffer strings that are valid partial reports. Ordinary code such
132
+ // as `[<div>` must remain typable and must not hang the editor.
133
+ if (byte === 0x5b && buffer[offset + 1] === 0x3c) {
121
134
  const text = buffer.toString('utf8', offset);
122
- if (!/[Mm]/.test(text)) return 0; // Incomplete sequence; wait for subsequent bytes in this.pending
123
- const match = /^\[<(\d+);(\d+);(\d+)([Mm])/.exec(text);
135
+ const match = /^\[<(\d{1,6});(\d{1,6});(\d{1,6})([Mm])/.exec(text);
124
136
  if (match) {
125
- const code = parseInt(match[1], 10);
126
- const col = parseInt(match[2], 10);
127
- const row = parseInt(match[3], 10);
128
- const pressed = match[4] === 'M';
129
- this.emitMouse([code, col, row], pressed, match[0], events);
137
+ this.emitMouse([Number(match[1]), Number(match[2]), Number(match[3])],
138
+ match[4] === 'M', match[0], events);
130
139
  return match[0].length;
131
140
  }
141
+ // Don't wait forever on malformed or nonmouse `[` + `<` input.
142
+ if (text.length <= 64 && /^\[<(?:\d{0,6}(?:;\d{0,6}){0,2})$/.test(text)) return 0;
132
143
  }
133
144
 
134
145
  if (byte === 0x0d || byte === 0x0a) {
@@ -162,28 +173,45 @@ export class KeyDecoder {
162
173
  }
163
174
 
164
175
  stepPaste(buffer, offset, events) {
165
- const text = buffer.toString('utf8', offset);
166
- const end = text.indexOf(PASTE_END);
167
-
168
- if (end === -1) {
169
- // No terminator yet. Keep whole UTF-8 characters, hold back a split tail.
170
- let safe = buffer.length;
171
- while (safe > offset && utf8Length(buffer, safe - 1) === 0) safe--;
172
- // A partial terminator at the tail must not be swallowed as content.
173
- const chunk = buffer.toString('utf8', offset, safe);
174
- const keep = partialSuffixLength(chunk, PASTE_END);
175
- const usable = chunk.slice(0, chunk.length - keep);
176
- if (!usable) return 0;
177
- this.pasteBuffer += usable;
178
- return Buffer.byteLength(usable, 'utf8');
176
+ // Bracketed paste can split in the middle of a UTF-8 code point OR CSI
177
+ // terminator. Accumulate *bytes*, then decode once. Decoding each chunk
178
+ // independently corrupts emoji and CJK, and can change user code silently.
179
+ const marker = Buffer.from(PASTE_END, 'ascii');
180
+ const end = buffer.indexOf(marker, offset);
181
+ const maxBytes = 2 * 1024 * 1024;
182
+ const append = (chunk) => {
183
+ this.pasteByteLength += chunk.length;
184
+ if (this.pasteByteLength > maxBytes) { this.pasteOverflow = true; return; }
185
+ if (!this.pasteOverflow && chunk.length) this.pasteChunks.push(Buffer.from(chunk));
186
+ };
187
+
188
+ if (end >= 0) {
189
+ append(buffer.subarray(offset, end));
190
+ const pasted = this.pasteOverflow ? '' : Buffer.concat(this.pasteChunks).toString('utf8');
191
+ const oversized = this.pasteOverflow;
192
+ this.inPaste = false;
193
+ this.pasteBuffer = '';
194
+ this.pasteChunks = [];
195
+ this.pasteByteLength = 0;
196
+ this.pasteOverflow = false;
197
+ if (oversized) events.push(makeKey('paste-too-large', { sequence: '' }));
198
+ else events.push(makeKey('paste', { text: pasted, sequence: pasted }));
199
+ return end - offset + marker.length;
179
200
  }
180
201
 
181
- this.pasteBuffer += text.slice(0, end);
182
- this.inPaste = false;
183
- const pasted = this.pasteBuffer;
184
- this.pasteBuffer = '';
185
- events.push(makeKey('paste', { text: pasted, sequence: pasted }));
186
- return Buffer.byteLength(text.slice(0, end), 'utf8') + PASTE_END.length;
202
+ // Keep only a suffix that might start the paste terminator. All other
203
+ // bytes can be committed immediately without corrupting Unicode.
204
+ let retain = 0;
205
+ for (let count = Math.min(marker.length - 1, buffer.length - offset); count > 0; count--) {
206
+ if (buffer.subarray(buffer.length - count).equals(marker.subarray(0, count))) {
207
+ retain = count;
208
+ break;
209
+ }
210
+ }
211
+ const safeEnd = buffer.length - retain;
212
+ if (safeEnd === offset) return 0;
213
+ append(buffer.subarray(offset, safeEnd));
214
+ return safeEnd - offset;
187
215
  }
188
216
 
189
217
  stepEscape(buffer, offset, events) {
@@ -262,13 +290,23 @@ export class KeyDecoder {
262
290
  if (text.startsWith(PASTE_START)) {
263
291
  this.inPaste = true;
264
292
  this.pasteBuffer = '';
293
+ this.pasteChunks = [];
294
+ this.pasteByteLength = 0;
295
+ this.pasteOverflow = false;
265
296
  return PASTE_START.length;
266
297
  }
267
298
 
268
299
  // A CSI sequence is ESC [ , parameters, then one final byte in @..~.
269
300
  let index = 2;
270
301
  while (index < text.length && !/[@-~]/.test(text[index])) index++;
271
- if (index >= text.length) return 0; // still arriving
302
+ if (index >= text.length) {
303
+ // A malformed CSI stream must not buffer an unbounded quantity of user input.
304
+ if (buffer.length - offset > 128) {
305
+ events.push(makeKey('unknown', { sequence: '' }));
306
+ return buffer.length - offset;
307
+ }
308
+ return 0; // still arriving
309
+ }
272
310
 
273
311
  const final = text[index];
274
312
  const params = text.slice(2, index);
package/src/tui/prompt.js CHANGED
@@ -18,6 +18,7 @@
18
18
  // Pure Node. No dependency, no shell.
19
19
 
20
20
  import { KeyDecoder, bracketedPaste } from './keys.js';
21
+ import { TerminalInputFramer, INPUT_PREFIX_TIMEOUT_MS, shouldTreatAsAtomicPaste } from './terminalInputFramer.js';
21
22
  import { LineEditor } from './lineEditor.js';
22
23
  import { PromptHistory } from './history.js';
23
24
  import { FileIndex, suggest, applyCompletion, detectTrigger, renderPicker, MAX_VISIBLE } from './completion.js';
@@ -120,6 +121,9 @@ export class ChatPrompt {
120
121
  this.history = options.history || new PromptHistory();
121
122
  this.index = new FileIndex(this.root);
122
123
  this.decoder = new KeyDecoder();
124
+ this.inputFramer = new TerminalInputFramer();
125
+ this.inputFrameTimer = null;
126
+ this.decoderRecoveryTimer = null;
123
127
 
124
128
  this.busy = false;
125
129
  this.active = false;
@@ -181,6 +185,7 @@ export class ChatPrompt {
181
185
  start() {
182
186
  if (this.active) return;
183
187
  this.active = true;
188
+ this.inputFramer.clear();
184
189
  this.input.setRawMode(true);
185
190
  this.input.resume();
186
191
  this.input.on('data', this.handleData);
@@ -195,6 +200,10 @@ export class ChatPrompt {
195
200
  if (!this.active) return;
196
201
  this.active = false;
197
202
  this.stopTick();
203
+ if (this.inputFrameTimer) { clearTimeout(this.inputFrameTimer); this.inputFrameTimer = null; }
204
+ if (this.decoderRecoveryTimer) { clearTimeout(this.decoderRecoveryTimer); this.decoderRecoveryTimer = null; }
205
+ this.inputFramer.clear();
206
+ this.decoder.pending = Buffer.alloc(0);
198
207
  if (this.resizeTimer) { clearTimeout(this.resizeTimer); this.resizeTimer = null; }
199
208
  this.erase();
200
209
  // The exit contract (UX-01 rev 2 clause d): the band collapses and the whole
@@ -254,30 +263,52 @@ export class ChatPrompt {
254
263
  };
255
264
 
256
265
  handleData = (chunk) => {
266
+ // KeyDecoder expects complete escape prefixes. A PTY may split ESC from
267
+ // `[<button;x;yM`; framing these bytes first prevents mouse coordinates
268
+ // from becoming chat content. Do not decode bulk paste before this step.
269
+ const frames = this.inputFramer.push(chunk);
270
+ for (const frame of frames) this.handleFramedData(frame);
271
+ if (this.inputFrameTimer) { clearTimeout(this.inputFrameTimer); this.inputFrameTimer = null; }
272
+ if (this.inputFramer.hasPending) {
273
+ this.inputFrameTimer = setTimeout(() => {
274
+ this.inputFrameTimer = null;
275
+ for (const frame of this.inputFramer.flush()) this.handleFramedData(frame);
276
+ }, INPUT_PREFIX_TIMEOUT_MS);
277
+ this.inputFrameTimer.unref?.();
278
+ }
279
+ };
280
+
281
+ handleFramedData = (chunk) => {
257
282
  let motionOnly = true;
258
283
  const str = typeof chunk === 'string' ? chunk : Buffer.isBuffer(chunk) ? chunk.toString('utf8') : '';
259
- // Unbracketed multi-line or bulk paste safeguard: when a multi-line or bulk block arrives
260
- // without bracketed paste (e.g. VS Code terminal, native clipboard paste, terminal ANSI logs,
261
- // or piped stream), handle it atomically as a paste event rather than executing multiple
262
- // spurious Enter submissions or freezing in per-character completion loops.
263
- const isBracketedPasteStart = str.startsWith('\x1b[200~');
264
- const isMouse = str.startsWith('\x1b[<') || str.startsWith('\x1b[M');
265
- const hasNewlines = str.includes('\n') || str.includes('\r');
266
- if (!this.layer && !this.decoder.inPaste && !isBracketedPasteStart && !isMouse && (
267
- (str.length > 2 && hasNewlines) ||
268
- (str.length >= 64 && !str.startsWith('\x1b'))
269
- )) {
270
- const clean = stripAnsi(str).replace(/\r\n/g, '\n').replace(/\r/g, '\n');
284
+ // Unbracketed bulk input remains atomic ONLY when no control sequence
285
+ // is still in flight. This fixes mixed mouse/typing chunks that previously
286
+ // bypassed KeyDecoder and leaked CSI tails into the composer.
287
+ if (!this.layer && shouldTreatAsAtomicPaste(chunk, this.decoder)) {
271
288
  try {
272
- this.handleKey({ name: 'paste', text: clean, sequence: clean });
273
- } catch (e) {
274
- process.stderr.write(`\n[tui] paste failed: ${e.message}\n`);
289
+ this.handleKey({ name: 'paste', text: str, sequence: '' });
290
+ } catch (error) {
291
+ this.notice = `paste failed: ${error instanceof Error ? error.message : String(error)}`;
292
+ this.scheduleDraw();
275
293
  }
276
294
  this.draw();
277
295
  return;
278
296
  }
279
297
 
280
298
  const keys = this.decoder.decode(chunk);
299
+ // A truncated CSI/X10 mouse report must not swallow the next user keystroke.
300
+ // Paste is exempt: its terminator may arrive across many chunks.
301
+ if (this.decoderRecoveryTimer) clearTimeout(this.decoderRecoveryTimer);
302
+ this.decoderRecoveryTimer = null;
303
+ if (!this.decoder.inPaste && this.decoder.pending.length > 0) {
304
+ this.decoderRecoveryTimer = setTimeout(() => {
305
+ this.decoderRecoveryTimer = null;
306
+ const recovered = this.decoder.drainIncomplete();
307
+ for (const event of recovered) this.handleKey(event);
308
+ if (recovered.length) this.scheduleDraw();
309
+ }, 180);
310
+ this.decoderRecoveryTimer.unref?.();
311
+ }
281
312
  let charBatch = '';
282
313
 
283
314
  for (let i = 0; i < keys.length; i++) {
@@ -302,7 +333,8 @@ export class ChatPrompt {
302
333
  } catch (e) {
303
334
  // A key handler must never take the session down. Say so once and
304
335
  // carry on, rather than dying silently the way the old catch(e){} did.
305
- process.stderr.write(`\n[tui] key "${key.name}" failed: ${e.message}\n`);
336
+ this.notice = `input error: ${e instanceof Error ? e.message : String(e)}`;
337
+ this.scheduleDraw();
306
338
  }
307
339
  }
308
340
 
@@ -410,8 +442,13 @@ export class ChatPrompt {
410
442
  const line = parts.join(dim(` ${GLYPHS.dot} `));
411
443
  const trailing = [status.provider, status.tier].filter(Boolean).join(' ');
412
444
  const base = trailing ? `${line} ${dim(trailing)}` : line;
445
+ const details = [];
446
+ if (this.queue.length) details.push(`${this.queue.length} queued`);
447
+ if (this.editor.lines.length > 1) details.push(`${this.editor.lines.length} lines`);
448
+ const extra = details.length ? dim(` ${GLYPHS.dot} ${details.join(' · ')}`) : '';
449
+ const withMeta = visibleWidth(base) + visibleWidth(extra) <= width ? base + extra : base;
413
450
  const hints = dim(' Ctrl+G mode · Alt+M model · Ctrl+T variant');
414
- const full = visibleWidth(base) + visibleWidth(hints) <= width ? base + hints : base;
451
+ const full = visibleWidth(withMeta) + visibleWidth(hints) <= width ? withMeta + hints : withMeta;
415
452
  return visibleWidth(full) > width ? truncate(full, width, GLYPHS.ellipsis) : full;
416
453
  }
417
454
 
@@ -757,6 +794,12 @@ export class ChatPrompt {
757
794
  submit() {
758
795
  const text = this.editor.getText();
759
796
  if (!text.trim()) return;
797
+ if (this.busy && this.queue.length >= 32
798
+ && text.trim() !== '/stop' && text.trim() !== '/interrupt') {
799
+ this.notice = '32 queued messages: wait for a turn to complete before adding another';
800
+ this.scheduleDraw();
801
+ return;
802
+ }
760
803
 
761
804
  this.erase();
762
805
  this.history.add(text);
@@ -908,6 +951,12 @@ export class ChatPrompt {
908
951
  else if (action !== 'passthrough') return;
909
952
  }
910
953
 
954
+ if (key.name === 'paste-too-large') {
955
+ this.notice = 'Paste exceeds 2 MiB; input unchanged. Attach a file or reduce the selection.';
956
+ this.scheduleDraw();
957
+ return;
958
+ }
959
+
911
960
  if (key.name === 'paste') {
912
961
  if (this.surface && typeof this.surface.captureMouse === 'function') {
913
962
  this.surface.captureMouse();
@@ -0,0 +1,98 @@
1
+ // Causyne TUI — terminal input framing and atomic unbracketed paste classification.
2
+ // Keep this module free of side effects so terminal sequences can be tested
3
+ // without a PTY. It does not decode keys, move the cursor, or execute commands.
4
+
5
+ export const INPUT_PREFIX_TIMEOUT_MS = 40;
6
+
7
+ /**
8
+ * Hold a trailing ESC or '[' long enough for a following stdin chunk to complete
9
+ * a CSI/mouse report. Without this, the original KeyDecoder treats standalone
10
+ * ESC as a key immediately; its following '[<...M' chunk can be pasted as text.
11
+ *
12
+ * Ordinary characters are released immediately, with at most one trailing
13
+ * byte delayed. The delay is deliberately bounded by ChatPrompt's timer.
14
+ */
15
+ export class TerminalInputFramer {
16
+ constructor() {
17
+ this.pending = Buffer.alloc(0);
18
+ }
19
+
20
+ get hasPending() {
21
+ return this.pending.length !== 0;
22
+ }
23
+
24
+ push(input) {
25
+ const incoming = Buffer.isBuffer(input) ? input : Buffer.from(String(input), 'utf8');
26
+ if (incoming.length === 0) return [];
27
+ const bytes = this.pending.length ? Buffer.concat([this.pending, incoming]) : incoming;
28
+ this.pending = Buffer.alloc(0);
29
+ const end = bytes[bytes.length - 1];
30
+ // '[' may be a literal character or the first byte of an orphaned SGR
31
+ // mouse report. Only one byte is held, so the editor is never blocked by
32
+ // a multi-kilobyte prefix buffer outside KeyDecoder.
33
+ if (end === 0x1b || end === 0x5b) {
34
+ const heldLength = end === 0x5b && bytes.length >= 2 && bytes[bytes.length - 2] === 0x1b ? 2 : 1;
35
+ this.pending = Buffer.from(bytes.subarray(-heldLength));
36
+ return bytes.length > heldLength ? [bytes.subarray(0, -heldLength)] : [];
37
+ }
38
+ return [bytes];
39
+ }
40
+
41
+ flush() {
42
+ const value = this.pending;
43
+ this.pending = Buffer.alloc(0);
44
+ // An incomplete ESC[ is not a printable character and should never be
45
+ // handed to KeyDecoder's CSI state forever after the timeout expires.
46
+ if (value.length === 2 && value[0] === 0x1b && value[1] === 0x5b) return [];
47
+ return value.length ? [value] : [];
48
+ }
49
+
50
+ clear() {
51
+ this.pending = Buffer.alloc(0);
52
+ }
53
+ }
54
+
55
+ const MOUSE_CSI = /\x1b\[<\d{1,6};\d{1,6};\d{1,6}[Mm]/;
56
+ const ORPHAN_MOUSE = /\[<\d{1,6};\d{1,6};\d{1,6}[Mm]/;
57
+ const MOUSE_TAIL = /(?:^|[Mm])<\d{1,6};\d{1,6};\d{1,6}[Mm]/;
58
+ const BRACKETED = /\x1b\[(?:200|201)~/;
59
+ // Only SGR color/control formatting is permitted in an ANSI log pasted as
60
+ // one atomic block; actual cursor and mouse sequences must go to KeyDecoder.
61
+ const SGR = /\x1b\[[0-9;]*m/g;
62
+
63
+ /**
64
+ * Avoid bypassing an incomplete key or mouse sequence with the 'large chunk =
65
+ * paste' heuristic. Allow bulk pasted ANSI-colored logs, which an existing
66
+ * regression test expects to arrive as a single multiline editor insertion.
67
+ */
68
+ export function shouldTreatAsAtomicPaste(raw, decoder) {
69
+ let text;
70
+ if (typeof raw === 'string') text = raw;
71
+ else {
72
+ // Classifying an incomplete UTF-8 byte stream as a bulk paste would
73
+ // replace a split emoji with U+FFFD. Let KeyDecoder buffer its tail.
74
+ try { text = new TextDecoder('utf-8', { fatal: true }).decode(raw); }
75
+ catch { return false; }
76
+ }
77
+ if (!text) return false;
78
+ if (decoder?.inPaste || (decoder?.pending?.length ?? 0) > 0) return false;
79
+ if (BRACKETED.test(text) || MOUSE_CSI.test(text) || ORPHAN_MOUSE.test(text) || MOUSE_TAIL.test(text)) return false;
80
+ const hasNewline = text.includes('\n') || text.includes('\r');
81
+ const big = text.length >= 64;
82
+ if (!big && !(hasNewline && text.length > 2)) return false;
83
+ if (text.includes('\x1b') || text.includes('\u009b')) {
84
+ // Colorized terminal output can be pasted without submitting each line.
85
+ // All control sequences must be complete SGR, with no other escapes.
86
+ const withoutColor = text.replace(SGR, '');
87
+ return hasNewline && !/[\x1b\u009b]/.test(withoutColor);
88
+ }
89
+ return hasNewline || big;
90
+ }
91
+
92
+ /** Display a short, non-sensitive paste notification (not the pasted content). */
93
+ export function pasteSummary(text) {
94
+ const lines = 1 + (text.match(/\n/g)?.length ?? 0);
95
+ const size = Buffer.byteLength(text, 'utf8');
96
+ const sizeLabel = size >= 1024 ? `${Math.round(size / 1024)} KiB` : `${size} B`;
97
+ return `pasted ${lines} ${lines === 1 ? 'line' : 'lines'} · ${sizeLabel}`;
98
+ }