@causyne/agent 1.20.0 → 1.20.7

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 (130) hide show
  1. package/README.md +13 -9
  2. package/SECURITY.md +1 -4
  3. package/package.json +1 -1
  4. package/src/acp/client.js +176 -26
  5. package/src/acp/client.ts +167 -25
  6. package/src/acp/protocol.js +116 -0
  7. package/src/acp/protocol.ts +163 -0
  8. package/src/acp/server.js +5 -6
  9. package/src/acp/server.ts +4 -6
  10. package/src/agentLoop.d.ts +1 -0
  11. package/src/agentLoop.js +681 -245
  12. package/src/agentLoop.ts +708 -262
  13. package/src/agentPolicy.js +9 -0
  14. package/src/agentPolicy.ts +9 -0
  15. package/src/approvalPolicy.js +55 -0
  16. package/src/approvalPolicy.ts +66 -0
  17. package/src/browser/browserRuntime.js +217 -14
  18. package/src/browser/browserRuntime.ts +255 -14
  19. package/src/browser/causyneBrowser.js +1215 -68
  20. package/src/browser/causyneBrowser.ts +1340 -72
  21. package/src/cliMode.js +52 -29
  22. package/src/commands.js +141 -17
  23. package/src/config.js +22 -12
  24. package/src/continuum/ui/continuumPicker.js +18 -1
  25. package/src/continuum/ui/continuumPicker.ts +19 -1
  26. package/src/dynamicCatalogue.js +87 -20
  27. package/src/dynamicCatalogue.ts +85 -15
  28. package/src/launchIntent.js +40 -0
  29. package/src/launchIntent.ts +49 -0
  30. package/src/memoryManager.js +26 -2
  31. package/src/modelCatalogue.js +2 -0
  32. package/src/planCache.js +320 -11
  33. package/src/planCache.ts +402 -13
  34. package/src/providers/acp.js +173 -18
  35. package/src/providers/acp.ts +169 -19
  36. package/src/providers/antigravity.d.ts +5 -1
  37. package/src/providers/antigravity.js +674 -34
  38. package/src/providers/antigravity.ts +707 -35
  39. package/src/providers/base.d.ts +10 -0
  40. package/src/providers/factory.js +2 -0
  41. package/src/providers/pi.js +161 -0
  42. package/src/providers/pi.ts +148 -0
  43. package/src/provisioning/capabilityProvisioner.js +17 -0
  44. package/src/provisioning/capabilityTools.js +1 -1
  45. package/src/sandbox.js +30 -39
  46. package/src/sessionJournal.js +53 -10
  47. package/src/sessionJournal.ts +64 -10
  48. package/src/taskShape.js +9 -9
  49. package/src/taskShape.ts +9 -9
  50. package/src/timeMachine.js +124 -0
  51. package/src/timeMachine.ts +141 -0
  52. package/src/toolPacks.js +4 -10
  53. package/src/tools/archive.js +196 -59
  54. package/src/tools/archive.ts +220 -0
  55. package/src/tools/browserAutomator.js +78 -9
  56. package/src/tools/browserAutomator.ts +90 -9
  57. package/src/tools/desktopOpen.js +114 -31
  58. package/src/tools/desktopOpen.ts +144 -0
  59. package/src/tools/gitExec.js +5 -3
  60. package/src/tools/nativeEngine.js +4 -3
  61. package/src/tools/nativeEngine.ts +5 -3
  62. package/src/tools/openSourceToolProvisioner.js +5 -4
  63. package/src/tools/openSourceToolProvisioner.ts +5 -4
  64. package/src/tools/registry.js +3 -0
  65. package/src/tools/screenshot.js +55 -71
  66. package/src/tools/screenshot.ts +70 -0
  67. package/src/tools/sysRun.js +284 -117
  68. package/src/tools/sysRun.ts +347 -0
  69. package/src/tools/toolSelfRepair.js +109 -2
  70. package/src/tools/toolSelfRepair.ts +100 -2
  71. package/src/tools/updatePlan.js +49 -1
  72. package/src/tools/updatePlan.ts +43 -1
  73. package/src/tools/viewImage.js +93 -78
  74. package/src/tools/viewImage.ts +116 -0
  75. package/src/tools/webFetch.js +20 -6
  76. package/src/tools/webFetch.ts +26 -6
  77. package/src/tui/activityLayout.js +9 -0
  78. package/src/tui/activityLayout.ts +10 -0
  79. package/src/tui/block.d.ts +1 -0
  80. package/src/tui/chatRenderer.d.ts +23 -0
  81. package/src/tui/chatRenderer.js +49 -49
  82. package/src/tui/clipboardSync.js +28 -1
  83. package/src/tui/clipboardSync.ts +26 -1
  84. package/src/tui/codeProgress.js +299 -0
  85. package/src/tui/codeProgress.ts +304 -0
  86. package/src/tui/codeStreamRenderer.js +132 -0
  87. package/src/tui/codeStreamRenderer.ts +141 -0
  88. package/src/tui/commandPresentation.js +11 -0
  89. package/src/tui/commandPresentation.ts +18 -0
  90. package/src/tui/completion.js +45 -13
  91. package/src/tui/composerControls.js +131 -0
  92. package/src/tui/composerControls.ts +184 -0
  93. package/src/tui/diff.d.ts +2 -0
  94. package/src/tui/home.js +4 -2
  95. package/src/tui/homeTransition.js +21 -0
  96. package/src/tui/homeTransition.ts +27 -0
  97. package/src/tui/homeView.js +62 -0
  98. package/src/tui/homeView.ts +91 -0
  99. package/src/tui/layout.js +46 -0
  100. package/src/tui/layout.ts +52 -0
  101. package/src/tui/messageActionPlacement.js +16 -0
  102. package/src/tui/messageActionPlacement.ts +25 -0
  103. package/src/tui/messageInteraction.js +221 -0
  104. package/src/tui/messageInteraction.ts +275 -0
  105. package/src/tui/modelPicker.js +4 -24
  106. package/src/tui/modelPicker.ts +4 -20
  107. package/src/tui/mouseHover.js +6 -0
  108. package/src/tui/mouseHover.ts +5 -0
  109. package/src/tui/prompt.js +175 -101
  110. package/src/tui/resizeRecovery.js +15 -0
  111. package/src/tui/resizeRecovery.ts +27 -0
  112. package/src/tui/scrollInteraction.js +97 -0
  113. package/src/tui/scrollInteraction.ts +189 -0
  114. package/src/tui/sessionLayout.js +12 -0
  115. package/src/tui/sessionLayout.ts +12 -0
  116. package/src/tui/sessionPicker.js +111 -16
  117. package/src/tui/sessionPicker.ts +121 -16
  118. package/src/tui/sessionSidebar.js +78 -0
  119. package/src/tui/sessionSidebar.ts +95 -0
  120. package/src/tui/setup.js +1 -1
  121. package/src/tui/setup.ts +1 -1
  122. package/src/tui/stageSurface.js +120 -58
  123. package/src/tui/text.d.ts +6 -0
  124. package/src/tui/textLayout.js +23 -0
  125. package/src/tui/textLayout.ts +28 -0
  126. package/src/tui/viewport.js +204 -279
  127. package/src/tui/viewport.ts +326 -0
  128. package/src/types/contracts.ts +54 -0
  129. package/src/utils/paths.js +5 -4
  130. package/src/utils/paths.ts +5 -5
@@ -0,0 +1,304 @@
1
+ import { panel } from './block.js';
2
+ import { safeDisplay, truncate, padEnd } from './text.js';
3
+ // The terminal theme is still a standalone JavaScript module in the TS migration.
4
+ // @ts-expect-error theme.js has no TypeScript declaration yet.
5
+ import { COLOR_DEPTH, IS_LIGHT, paint } from './theme.js';
6
+ import { diffLines } from './diff.js';
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ export type CodePhase = 'draft' | 'working' | 'done' | 'failed';
11
+
12
+ export interface CodeProgressEvent {
13
+ [key: string]: unknown;
14
+ type: 'code_progress';
15
+ id: string;
16
+ phase: CodePhase;
17
+ operation: string;
18
+ path?: string;
19
+ description: string;
20
+ code?: string;
21
+ before?: string;
22
+ codeTruncated?: boolean;
23
+ source: 'model' | 'tool' | 'provider';
24
+ }
25
+
26
+ export const CODE_PANEL_LINES = 10;
27
+ const MAX_STREAM_PREVIEW_CHARS = 256_000;
28
+
29
+ const FILE_TOOLS: Record<string, string> = {
30
+ fs_write: 'Creating', fs_edit: 'Editing', MultiEdit: 'Editing',
31
+ 'fs.write': 'Creating', 'fs.edit': 'Editing',
32
+ fs_delete: 'Removing', fs_move: 'Moving',
33
+ write_file: 'Creating', edit_file: 'Editing', delete_file: 'Removing',
34
+ replace_file_content: 'Editing', multi_replace_file_content: 'Editing',
35
+ WriteFile: 'Creating', EditFile: 'Editing', DeleteFile: 'Removing',
36
+ ReplaceFileContent: 'Editing', MultiReplaceFileContent: 'Editing'
37
+ };
38
+
39
+ function stringField(value: unknown): string {
40
+ return typeof value === 'string' ? value : '';
41
+ }
42
+
43
+ function codeFromArgs(args: Record<string, unknown>): string {
44
+ const direct = args.content ?? args.Content ?? args.CodeContent ?? args.code ?? args.new_string ?? args.newText ?? args.replaceContent ?? args.ReplacementContent;
45
+ if (typeof direct === 'string') return direct;
46
+ const edits = args.edits ?? args.ReplacementChunks;
47
+ if (Array.isArray(edits)) {
48
+ return edits.map((item: unknown) => {
49
+ if (!item || typeof item !== 'object') return '';
50
+ const entry = item as Record<string, unknown>;
51
+ return stringField(entry.new_string ?? entry.newText ?? entry.replaceContent ?? entry.ReplacementContent ?? entry.content);
52
+ }).join('\n');
53
+ }
54
+ return '';
55
+ }
56
+
57
+ function previousCodeFromArgs(args: Record<string, unknown>): string | undefined {
58
+ const direct = args.old_string ?? args.oldText ?? args.searchContent ?? args.SearchContent;
59
+ if (typeof direct === 'string') return direct;
60
+ const edits = args.edits ?? args.ReplacementChunks;
61
+ if (!Array.isArray(edits)) return undefined;
62
+ const previous = edits.map((item: unknown) => {
63
+ if (!item || typeof item !== 'object') return undefined;
64
+ const entry = item as Record<string, unknown>;
65
+ const value = entry.old_string ?? entry.oldText ?? entry.searchContent ?? entry.SearchContent;
66
+ return typeof value === 'string' ? value : undefined;
67
+ });
68
+ return previous.length && previous.every(value => value !== undefined) ? previous.join('\n') : undefined;
69
+ }
70
+
71
+ export function codeProgressFromAction(
72
+ tool: string,
73
+ args: Record<string, unknown>,
74
+ id: string,
75
+ phase: CodePhase = 'working',
76
+ source: CodeProgressEvent['source'] = 'tool'
77
+ ): CodeProgressEvent | null {
78
+ const operation = FILE_TOOLS[tool];
79
+ if (!operation) return null;
80
+ const path = stringField(args.path ?? args.Path ?? args.file_path ?? args.FilePath ?? args.AbsolutePath ?? args.TargetFile ?? args.source);
81
+ const destination = stringField(args.destination);
82
+ const label = path ? path.split(/[/\\]/).pop() || path : 'file';
83
+ const description = operation === 'Moving' && destination
84
+ ? `Moving ${label} to ${destination}`
85
+ : `${operation} ${label}`;
86
+ const before = previousCodeFromArgs(args);
87
+ const code = codeFromArgs(args);
88
+ return {
89
+ type: 'code_progress', id, phase, operation,
90
+ ...(path ? { path } : {}), description,
91
+ ...(code || before !== undefined ? { code } : {}), ...(before !== undefined ? { before } : {}), source
92
+ };
93
+ }
94
+
95
+ export class StreamingCodePreview {
96
+ private buffer = '';
97
+ private lastCode = '';
98
+ private lastSentAt = 0;
99
+ private truncated = false;
100
+
101
+ accept(chunk: string, now = Date.now()): CodeProgressEvent | null {
102
+ if (!chunk) return null;
103
+ this.buffer += chunk;
104
+ if (this.buffer.length > MAX_STREAM_PREVIEW_CHARS) {
105
+ this.buffer = this.buffer.slice(-MAX_STREAM_PREVIEW_CHARS);
106
+ this.truncated = true;
107
+ }
108
+ if (now - this.lastSentAt < 100 && !chunk.includes('\n')) return null;
109
+ const code = this.draftCode();
110
+ if (!code.trim() || code === this.lastCode) return null;
111
+ this.lastCode = code;
112
+ this.lastSentAt = now;
113
+ return { type: 'code_progress', id: 'model-draft', phase: 'draft',
114
+ operation: 'Drafting', description: 'Writing code from the model stream', code,
115
+ ...(this.truncated ? { codeTruncated: true } : {}), source: 'model' };
116
+ }
117
+
118
+ flush(): CodeProgressEvent | null {
119
+ const code = this.draftCode();
120
+ if (!code.trim() || code === this.lastCode) return null;
121
+ this.lastCode = code;
122
+ return { type: 'code_progress', id: 'model-draft', phase: 'draft',
123
+ operation: 'Drafting', description: 'Writing code from the model stream', code,
124
+ ...(this.truncated ? { codeTruncated: true } : {}), source: 'model' };
125
+ }
126
+
127
+ private draftCode(): string {
128
+ const fences = [...this.buffer.matchAll(/(?:^|\n)```[^\n]*\n([\s\S]*?)(?=\n```|$)/g)];
129
+ const fenced = fences.at(-1)?.[1] || '';
130
+ if (fenced.trim()) return fenced;
131
+ const start = this.buffer.lastIndexOf('<tool_call>');
132
+ if (start < 0) return '';
133
+ const call = this.buffer.slice(start);
134
+ if (!/"name"\s*:\s*"(?:fs_write|fs_edit|MultiEdit|write_file|edit_file|create_file)"/.test(call)) return '';
135
+ const field = /"(?:content|new_string|replaceContent|newText)"\s*:\s*"/.exec(call);
136
+ if (!field || field.index === undefined) return '';
137
+ const raw = call.slice(field.index + field[0].length);
138
+ let escaped = false;
139
+ let end = raw.length;
140
+ for (let i = 0; i < raw.length; i++) {
141
+ if (escaped) { escaped = false; continue; }
142
+ if (raw[i] === '\\') { escaped = true; continue; }
143
+ if (raw[i] === '"') { end = i; break; }
144
+ }
145
+ const partial = raw.slice(0, end).replace(/\\$/u, '');
146
+ try { return JSON.parse(`"${partial}"`); }
147
+ catch { return partial.replace(/\\n/g, '\n'); }
148
+ }
149
+ }
150
+
151
+ /** Observe only a file named by a native edit action. No model calls are made. */
152
+ export class NativeCodeObserver {
153
+ private readonly workspaceRoot: string;
154
+ private readonly emit: (event: CodeProgressEvent) => void;
155
+ private active = new Map<string, {
156
+ event: CodeProgressEvent;
157
+ path: string;
158
+ previous: string | null;
159
+ lastShown: string | null;
160
+ timer: NodeJS.Timeout;
161
+ }>();
162
+
163
+ constructor(workspaceRoot: string, emit: (event: CodeProgressEvent) => void) {
164
+ this.workspaceRoot = workspaceRoot;
165
+ this.emit = emit;
166
+ }
167
+
168
+ handle(event: CodeProgressEvent): void {
169
+ if (!event.path || !['Creating', 'Editing'].includes(event.operation)) return;
170
+ if (event.code !== undefined || event.phase === 'failed') {
171
+ this.stop(event.id);
172
+ return;
173
+ }
174
+ const target = path.resolve(this.workspaceRoot, event.path);
175
+ if (event.phase === 'working') {
176
+ this.stop(event.id);
177
+ const previous = this.read(target);
178
+ const timer = setInterval(() => this.poll(event.id), 100);
179
+ timer.unref();
180
+ this.active.set(event.id, { event, path: target, previous, lastShown: null, timer });
181
+ return;
182
+ }
183
+ if (event.phase === 'done') {
184
+ this.poll(event.id);
185
+ const entry = this.active.get(event.id);
186
+ const current = this.read(target);
187
+ if (current !== null && (current !== entry?.previous || event.operation === 'Creating')) {
188
+ this.emit({ ...event, code: current, ...(entry?.previous !== null && entry?.previous !== undefined ? { before: entry.previous } : {}) });
189
+ }
190
+ }
191
+ this.stop(event.id);
192
+ }
193
+
194
+ poll(id: string): void {
195
+ const entry = this.active.get(id);
196
+ if (!entry) return;
197
+ const current = this.read(entry.path);
198
+ if (current === null || current === entry.previous || current === entry.lastShown) return;
199
+ entry.lastShown = current;
200
+ this.emit({ ...entry.event, code: current, ...(entry.previous !== null ? { before: entry.previous } : {}) });
201
+ }
202
+
203
+ dispose(): void {
204
+ for (const id of this.active.keys()) this.stop(id);
205
+ }
206
+
207
+ private stop(id: string): void {
208
+ const entry = this.active.get(id);
209
+ if (entry) clearInterval(entry.timer);
210
+ this.active.delete(id);
211
+ }
212
+
213
+ private read(file: string): string | null {
214
+ try {
215
+ const name = path.basename(file).toLowerCase();
216
+ if (/^(\.env(?:\.|$)|.*\.(?:pem|key|p12|pfx)$)/u.test(name)) return null;
217
+ const stat = fs.lstatSync(file);
218
+ if (!stat.isFile() || stat.size > 256_000) return null;
219
+ const bytes = fs.readFileSync(file);
220
+ if (bytes.includes(0)) return null;
221
+ return bytes.toString('utf8');
222
+ } catch {
223
+ return null;
224
+ }
225
+ }
226
+ }
227
+
228
+ type PreviewLine = { kind: 'add' | 'del' | 'ctx'; text: string };
229
+
230
+ function splitCodeLines(code: string): string[] {
231
+ if (!code) return [];
232
+ const lines = code.replace(/\r\n?/g, '\n').split('\n');
233
+ if (lines.at(-1) === '') lines.pop();
234
+ return lines;
235
+ }
236
+
237
+ function previewLines(event: CodeProgressEvent): PreviewLine[] {
238
+ if (event.code === undefined) return [];
239
+ if (event.before !== undefined) {
240
+ const oldLines = splitCodeLines(event.before);
241
+ const newLines = splitCodeLines(event.code);
242
+ let prefix = 0;
243
+ while (prefix < oldLines.length && prefix < newLines.length && oldLines[prefix] === newLines[prefix]) prefix++;
244
+ let suffix = 0;
245
+ while (suffix < oldLines.length - prefix && suffix < newLines.length - prefix
246
+ && oldLines[oldLines.length - suffix - 1] === newLines[newLines.length - suffix - 1]) suffix++;
247
+ const changedOld = oldLines.slice(prefix, oldLines.length - suffix);
248
+ const changedNew = newLines.slice(prefix, newLines.length - suffix);
249
+ const result = diffLines(changedOld.join('\n'), changedNew.join('\n'));
250
+ // Diff only the changed middle so a small edit in a long file stays fast.
251
+ // A partial middle diff could mislabel lines, so leave that case neutral.
252
+ if (result.truncated) return newLines.map(text => ({ kind: 'ctx', text }));
253
+ return [
254
+ ...oldLines.slice(0, prefix).map(text => ({ kind: 'ctx' as const, text })),
255
+ ...result.ops,
256
+ ...oldLines.slice(oldLines.length - suffix).map(text => ({ kind: 'ctx' as const, text }))
257
+ ];
258
+ }
259
+ const kind = event.operation === 'Removing' ? 'del'
260
+ : event.operation === 'Creating' || event.operation === 'Drafting' ? 'add' : 'ctx';
261
+ return splitCodeLines(event.code).map(text => ({ kind, text }));
262
+ }
263
+
264
+ export function codePreviewLineCount(event: CodeProgressEvent): number {
265
+ return previewLines(event).length;
266
+ }
267
+
268
+ function highlightCode(kind: PreviewLine['kind'], text: string, width: number): string {
269
+ const marker = kind === 'add' ? '+' : kind === 'del' ? '-' : ' ';
270
+ const role = kind === 'add' ? 'success' : kind === 'del' ? 'danger' : 'muted';
271
+ const body = padEnd(truncate(safeDisplay(text), Math.max(1, width - 2)), Math.max(1, width - 2));
272
+ if (kind === 'ctx' || COLOR_DEPTH < 256) return paint(role, marker) + ' ' + body;
273
+ // A low-contrast tint one step above the panel surface. The colored marker
274
+ // remains readable even when a terminal can only approximate the tint.
275
+ const background = COLOR_DEPTH >= 16777216
276
+ ? kind === 'add' ? (IS_LIGHT ? '48;2;231;239;220' : '48;2;32;42;32')
277
+ : (IS_LIGHT ? '48;2;245;230;230' : '48;2;47;32;34')
278
+ : kind === 'add' ? (IS_LIGHT ? '48;5;194' : '48;5;22')
279
+ : (IS_LIGHT ? '48;5;224' : '48;5;52');
280
+ return paint(role, marker) + `\x1b[${background}m ${body}\x1b[49m`;
281
+ }
282
+
283
+ /** Render a bounded, resize-safe panel. The terminal theme supplies rounded corners. */
284
+ export function renderCodeProgress(event: CodeProgressEvent, width: number, modelNote = '', startLine?: number): string[] {
285
+ const safeWidth = Math.max(12, Math.floor(width) || 80);
286
+ const inner = safeWidth - 4;
287
+ const title = `${event.phase === 'done' ? '✓ ' : event.phase === 'failed' ? '× ' : ''}code · ${event.operation.toLowerCase()}`;
288
+ const rows = [truncate(safeDisplay(event.description), inner)];
289
+ if (event.path) rows.push(truncate(safeDisplay(event.path), inner));
290
+ if (modelNote) rows.push(truncate(`model note: ${safeDisplay(modelNote)}`, inner));
291
+ const codeLines = previewLines(event);
292
+ const maxStart = Math.max(0, codeLines.length - CODE_PANEL_LINES);
293
+ const start = startLine === undefined ? maxStart : Math.max(0, Math.min(Math.floor(startLine), maxStart));
294
+ const visible = codeLines.slice(start, start + CODE_PANEL_LINES);
295
+ if (visible.length) {
296
+ rows.push('');
297
+ for (const line of visible) rows.push(highlightCode(line.kind, line.text, inner));
298
+ if (codeLines.length > CODE_PANEL_LINES) {
299
+ rows.push(truncate(`lines ${start + 1}-${start + visible.length} of ${codeLines.length} · scroll over code`, inner));
300
+ }
301
+ if (event.codeTruncated) rows.push(truncate('Earlier draft content exceeded the preview limit', inner));
302
+ }
303
+ return panel(rows, { width: safeWidth, title, role: event.phase === 'failed' ? 'danger' : 'rule' });
304
+ }
@@ -0,0 +1,132 @@
1
+ import { ChatRenderer } from './chatRenderer.js';
2
+ import { CODE_PANEL_LINES, codePreviewLineCount, renderCodeProgress } from './codeProgress.js';
3
+ function lastStart(event) {
4
+ return Math.max(0, codePreviewLineCount(event) - CODE_PANEL_LINES);
5
+ }
6
+ /** Adds a live code panel to the existing transcript without changing its other frames. */
7
+ export class CodeStreamRenderer extends ChatRenderer {
8
+ activeCode = null;
9
+ modelNote = '';
10
+ lastReasoning = '';
11
+ codePanels = new WeakMap();
12
+ /** Scroll only the code beneath the pointer; leave the chat viewport alone. */
13
+ scrollCodePanel(key, surface) {
14
+ const wheel = key.wheel;
15
+ if (key.name !== 'wheel' || !wheel || !surface || !['up', 'down'].includes(wheel.direction))
16
+ return false;
17
+ const transcript = this.transcript;
18
+ if (!transcript || !Number.isFinite(surface.out.rows) || !Number.isFinite(wheel.x) || !Number.isFinite(wheel.y))
19
+ return false;
20
+ const viewport = surface.viewport;
21
+ const screenTop = surface.out.rows - surface.stage.height;
22
+ const localY = wheel.y - screenTop;
23
+ if (localY < 0 || localY >= viewport.viewHeight || wheel.x < 0 || wheel.x >= Math.min(viewport.viewWidth, this.measure()))
24
+ return false;
25
+ const { markers } = transcript.flatten(viewport.viewWidth);
26
+ const absoluteY = viewport.scrollTop + localY;
27
+ const markerIndex = markers.findIndex((marker, index) => marker.row <= absoluteY
28
+ && (index + 1 === markers.length || absoluteY < markers[index + 1].row));
29
+ if (markerIndex < 0)
30
+ return false;
31
+ const marker = markers[markerIndex];
32
+ const frame = transcript.frames.find(item => item.id === marker.id);
33
+ const state = frame && this.codePanels.get(frame);
34
+ if (!frame || !state || absoluteY >= marker.row + (frame.rows?.length || 0))
35
+ return false;
36
+ const limit = lastStart(state.event);
37
+ if (limit === 0)
38
+ return false;
39
+ const next = Math.max(0, Math.min(limit, state.start + (wheel.direction === 'up' ? -3 : 3)));
40
+ if (next === state.start)
41
+ return false;
42
+ state.start = next;
43
+ state.followTail = next === limit;
44
+ frame.rows = null;
45
+ frame.renderedWidth = -1;
46
+ transcript.cache = null;
47
+ transcript.revision++;
48
+ transcript.changed();
49
+ return true;
50
+ }
51
+ resetTurn() {
52
+ this._activeReasoning = false;
53
+ this.activeCode = null;
54
+ this.modelNote = '';
55
+ this.lastReasoning = '';
56
+ super.resetTurn();
57
+ }
58
+ handle(message) {
59
+ if (message?.type === 'notice' && message.nativeStep === true) {
60
+ this.stepCount = (this.stepCount || 0) + 1;
61
+ }
62
+ if (message?.type === 'code_progress') {
63
+ this.onCodeProgress(message);
64
+ return true;
65
+ }
66
+ if (message?.type === 'agent_reasoning') {
67
+ const content = typeof message.content === 'string' ? message.content : '';
68
+ if (content)
69
+ this.lastReasoning = content;
70
+ const transcript = this.transcript;
71
+ const tailIsReasoning = transcript?.frames.at(-1)?.meta?.reasoning === true;
72
+ if (this._activeReasoning && transcript && !tailIsReasoning) {
73
+ this._activeReasoning = false;
74
+ }
75
+ if (this.activeCode && this.transcript) {
76
+ const note = content.trim().split('\n').at(-1) || '';
77
+ this.modelNote = note.slice(-140);
78
+ this.paintCodePanel(this.activeCode);
79
+ return true;
80
+ }
81
+ }
82
+ if (['agent_message', 'step_start', 'task_complete', 'error'].includes(message?.type || '')) {
83
+ this._activeReasoning = false;
84
+ this.activeCode = null;
85
+ this.modelNote = '';
86
+ if (message.type === 'task_complete' || message.type === 'error')
87
+ this.lastReasoning = '';
88
+ }
89
+ return super.handle(message);
90
+ }
91
+ onCodeProgress(event) {
92
+ if (!event || typeof event.id !== 'string' || typeof event.operation !== 'string'
93
+ || typeof event.description !== 'string' || !['draft', 'working', 'done', 'failed'].includes(event.phase))
94
+ return;
95
+ if (!this.transcript && event.phase === 'draft')
96
+ return;
97
+ if (this.lastReasoning && !this.modelNote) {
98
+ this.modelNote = (this.lastReasoning.trim().split('\n').at(-1) || '').slice(-140);
99
+ }
100
+ if (this._activeReasoning) {
101
+ super.onAgentReasoning({ content: this.lastReasoning, streaming: false });
102
+ }
103
+ this.lastReasoning = '';
104
+ this.activeCode = event;
105
+ this.paintCodePanel(event);
106
+ if (event.phase === 'done' || event.phase === 'failed') {
107
+ this.activeCode = null;
108
+ this.modelNote = '';
109
+ }
110
+ }
111
+ paintCodePanel(event) {
112
+ const transcript = this.transcript;
113
+ const last = transcript?.frames.at(-1);
114
+ const samePanel = last?.meta?.codePreview === true && last.meta.id === event.id;
115
+ const state = samePanel && last ? this.codePanels.get(last) : undefined;
116
+ const panelState = state || { event, modelNote: this.modelNote, start: lastStart(event), followTail: true };
117
+ panelState.event = event;
118
+ panelState.modelNote = this.modelNote;
119
+ panelState.start = panelState.followTail ? lastStart(event) : Math.min(panelState.start, lastStart(event));
120
+ const produce = () => {
121
+ for (const row of renderCodeProgress(panelState.event, this.measure(), panelState.modelNote, panelState.start))
122
+ this.write(row);
123
+ };
124
+ if (samePanel)
125
+ this.updateTailFrame('step', produce, { codePreview: true, id: event.id, phase: event.phase });
126
+ else
127
+ this.frame('step', produce, { codePreview: true, id: event.id, phase: event.phase });
128
+ const current = transcript?.frames.at(-1);
129
+ if (current)
130
+ this.codePanels.set(current, panelState);
131
+ }
132
+ }
@@ -0,0 +1,141 @@
1
+ import { ChatRenderer } from './chatRenderer.js';
2
+ import { CODE_PANEL_LINES, codePreviewLineCount, renderCodeProgress, type CodeProgressEvent } from './codeProgress.js';
3
+
4
+ type RendererEvent = { type: string; [key: string]: unknown };
5
+ type CodePanelState = { event: CodeProgressEvent; modelNote: string; start: number; followTail: boolean };
6
+ type CodeFrame = { id: number; meta?: Record<string, unknown> | null; rows?: string[] | null; renderedWidth?: number };
7
+ type CodeTranscript = {
8
+ frames: CodeFrame[];
9
+ cache: unknown;
10
+ revision: number;
11
+ flatten(width: number): { markers: Array<{ id: number; row: number }> };
12
+ changed(): void;
13
+ };
14
+ type CodeSurface = {
15
+ out: { rows?: number };
16
+ stage: { height: number };
17
+ viewport: { viewWidth: number; viewHeight: number; scrollTop: number };
18
+ };
19
+ type CodeWheel = { name: string; wheel?: { direction: string; x: number; y: number } };
20
+
21
+ function lastStart(event: CodeProgressEvent): number {
22
+ return Math.max(0, codePreviewLineCount(event) - CODE_PANEL_LINES);
23
+ }
24
+
25
+ /** Adds a live code panel to the existing transcript without changing its other frames. */
26
+ export class CodeStreamRenderer extends ChatRenderer {
27
+ private activeCode: CodeProgressEvent | null = null;
28
+ private modelNote = '';
29
+ private lastReasoning = '';
30
+ private readonly codePanels = new WeakMap<CodeFrame, CodePanelState>();
31
+
32
+ /** Scroll only the code beneath the pointer; leave the chat viewport alone. */
33
+ scrollCodePanel(key: CodeWheel, surface: CodeSurface | null): boolean {
34
+ const wheel = key.wheel;
35
+ if (key.name !== 'wheel' || !wheel || !surface || !['up', 'down'].includes(wheel.direction)) return false;
36
+ const transcript = this.transcript as unknown as CodeTranscript | null;
37
+ if (!transcript || !Number.isFinite(surface.out.rows) || !Number.isFinite(wheel.x) || !Number.isFinite(wheel.y)) return false;
38
+ const viewport = surface.viewport;
39
+ const screenTop = (surface.out.rows as number) - surface.stage.height;
40
+ const localY = wheel.y - screenTop;
41
+ if (localY < 0 || localY >= viewport.viewHeight || wheel.x < 0 || wheel.x >= Math.min(viewport.viewWidth, this.measure())) return false;
42
+ const { markers } = transcript.flatten(viewport.viewWidth);
43
+ const absoluteY = viewport.scrollTop + localY;
44
+ const markerIndex = markers.findIndex((marker, index) => marker.row <= absoluteY
45
+ && (index + 1 === markers.length || absoluteY < markers[index + 1]!.row));
46
+ if (markerIndex < 0) return false;
47
+ const marker = markers[markerIndex]!;
48
+ const frame = transcript.frames.find(item => item.id === marker.id);
49
+ const state = frame && this.codePanels.get(frame);
50
+ if (!frame || !state || absoluteY >= marker.row + (frame.rows?.length || 0)) return false;
51
+ const limit = lastStart(state.event);
52
+ if (limit === 0) return false;
53
+ const next = Math.max(0, Math.min(limit, state.start + (wheel.direction === 'up' ? -3 : 3)));
54
+ if (next === state.start) return false;
55
+ state.start = next;
56
+ state.followTail = next === limit;
57
+ frame.rows = null;
58
+ frame.renderedWidth = -1;
59
+ transcript.cache = null;
60
+ transcript.revision++;
61
+ transcript.changed();
62
+ return true;
63
+ }
64
+
65
+ override resetTurn(): void {
66
+ this._activeReasoning = false;
67
+ this.activeCode = null;
68
+ this.modelNote = '';
69
+ this.lastReasoning = '';
70
+ super.resetTurn();
71
+ }
72
+
73
+ override handle(message: RendererEvent): boolean {
74
+ if (message?.type === 'notice' && message.nativeStep === true) {
75
+ this.stepCount = (this.stepCount || 0) + 1;
76
+ }
77
+ if (message?.type === 'code_progress') {
78
+ this.onCodeProgress(message as unknown as CodeProgressEvent);
79
+ return true;
80
+ }
81
+ if (message?.type === 'agent_reasoning') {
82
+ const content = typeof message.content === 'string' ? message.content : '';
83
+ if (content) this.lastReasoning = content;
84
+ const transcript = this.transcript as unknown as CodeTranscript | null;
85
+ const tailIsReasoning = transcript?.frames.at(-1)?.meta?.reasoning === true;
86
+ if (this._activeReasoning && transcript && !tailIsReasoning) {
87
+ this._activeReasoning = false;
88
+ }
89
+ if (this.activeCode && this.transcript) {
90
+ const note = content.trim().split('\n').at(-1) || '';
91
+ this.modelNote = note.slice(-140);
92
+ this.paintCodePanel(this.activeCode);
93
+ return true;
94
+ }
95
+ }
96
+ if (['agent_message', 'step_start', 'task_complete', 'error'].includes(message?.type || '')) {
97
+ this._activeReasoning = false;
98
+ this.activeCode = null;
99
+ this.modelNote = '';
100
+ if (message.type === 'task_complete' || message.type === 'error') this.lastReasoning = '';
101
+ }
102
+ return super.handle(message);
103
+ }
104
+
105
+ private onCodeProgress(event: CodeProgressEvent): void {
106
+ if (!event || typeof event.id !== 'string' || typeof event.operation !== 'string'
107
+ || typeof event.description !== 'string' || !['draft', 'working', 'done', 'failed'].includes(event.phase)) return;
108
+ if (!this.transcript && event.phase === 'draft') return;
109
+ if (this.lastReasoning && !this.modelNote) {
110
+ this.modelNote = (this.lastReasoning.trim().split('\n').at(-1) || '').slice(-140);
111
+ }
112
+ if (this._activeReasoning) {
113
+ super.onAgentReasoning({ content: this.lastReasoning, streaming: false });
114
+ }
115
+ this.lastReasoning = '';
116
+ this.activeCode = event;
117
+ this.paintCodePanel(event);
118
+ if (event.phase === 'done' || event.phase === 'failed') {
119
+ this.activeCode = null;
120
+ this.modelNote = '';
121
+ }
122
+ }
123
+
124
+ private paintCodePanel(event: CodeProgressEvent): void {
125
+ const transcript = this.transcript as unknown as CodeTranscript | null;
126
+ const last = transcript?.frames.at(-1);
127
+ const samePanel = last?.meta?.codePreview === true && last.meta.id === event.id;
128
+ const state = samePanel && last ? this.codePanels.get(last) : undefined;
129
+ const panelState: CodePanelState = state || { event, modelNote: this.modelNote, start: lastStart(event), followTail: true };
130
+ panelState.event = event;
131
+ panelState.modelNote = this.modelNote;
132
+ panelState.start = panelState.followTail ? lastStart(event) : Math.min(panelState.start, lastStart(event));
133
+ const produce = (): void => {
134
+ for (const row of renderCodeProgress(panelState.event, this.measure(), panelState.modelNote, panelState.start)) this.write(row);
135
+ };
136
+ if (samePanel) this.updateTailFrame('step', produce, { codePreview: true, id: event.id, phase: event.phase });
137
+ else this.frame('step', produce, { codePreview: true, id: event.id, phase: event.phase });
138
+ const current = transcript?.frames.at(-1);
139
+ if (current) this.codePanels.set(current, panelState);
140
+ }
141
+ }
@@ -0,0 +1,11 @@
1
+ /** Local session and MCP feedback belongs in a dialog, never a chat turn. */
2
+ export function commandDialog(input, result) {
3
+ const command = /^\/(sessions?|mcp)(?:\s|$)/iu.exec(input.trim())?.[1]?.toLowerCase();
4
+ if (!command || ['silent', 'pick-session', 'pick-mcp', 'invoke-skill', 'exit'].includes(result.effect || ''))
5
+ return null;
6
+ return {
7
+ title: result.title || (command === 'mcp' ? 'MCP servers' : 'Sessions'),
8
+ text: result.output || '',
9
+ danger: result.ok === false
10
+ };
11
+ }
@@ -0,0 +1,18 @@
1
+ export interface CommandPresentationResult {
2
+ ok?: boolean;
3
+ effect?: string;
4
+ output?: string;
5
+ title?: string;
6
+ }
7
+
8
+ /** Local session and MCP feedback belongs in a dialog, never a chat turn. */
9
+ export function commandDialog(input: string, result: CommandPresentationResult):
10
+ { title: string; text: string; danger: boolean } | null {
11
+ const command = /^\/(sessions?|mcp)(?:\s|$)/iu.exec(input.trim())?.[1]?.toLowerCase();
12
+ if (!command || ['silent', 'pick-session', 'pick-mcp', 'invoke-skill', 'exit'].includes(result.effect || '')) return null;
13
+ return {
14
+ title: result.title || (command === 'mcp' ? 'MCP servers' : 'Sessions'),
15
+ text: result.output || '',
16
+ danger: result.ok === false
17
+ };
18
+ }
@@ -117,24 +117,56 @@ const ARGUMENT_LIMIT = 500;
117
117
  // ---------------------------------------------------------------------------
118
118
 
119
119
  function commandItems() {
120
- const commands = listCommands('terminal')
121
- .filter((command) => isTerminalSafe(command.name))
122
- .map((command) => ({
123
- value: '/' + command.name,
124
- match: command.name,
125
- label: '/' + command.name,
126
- description: sanitize(command.description || '')
127
- }));
120
+ // Suggested/high-frequency commands prioritized at the top on a bare '/' (OpenCode architecture)
121
+ const SUGGESTED_ORDER = ['model', 'sessions', 'new', 'clear', 'continuum', 'help', 'status', 'setup', 'mcp'];
122
+ const allCommands = listCommands('terminal');
123
+
124
+ const sorted = allCommands.slice().sort((a, b) => {
125
+ const idxA = SUGGESTED_ORDER.indexOf(a.name);
126
+ const idxB = SUGGESTED_ORDER.indexOf(b.name);
127
+ const scoreA = idxA === -1 ? 999 : idxA;
128
+ const scoreB = idxB === -1 ? 999 : idxB;
129
+ return scoreA - scoreB;
130
+ });
131
+
132
+ const commands = [];
133
+ const seenLabels = new Set();
134
+
135
+ for (const command of sorted) {
136
+ if (!isTerminalSafe(command.name)) continue;
137
+ const primaryLabel = '/' + command.name;
138
+ if (!seenLabels.has(primaryLabel)) {
139
+ seenLabels.add(primaryLabel);
140
+ commands.push({
141
+ value: primaryLabel,
142
+ match: command.name,
143
+ label: primaryLabel,
144
+ description: sanitize(command.description || '')
145
+ });
146
+ }
147
+
148
+ // Include aliases (e.g. /models, /session, /reset) so they match cleanly and resolve to canonical command
149
+ if (Array.isArray(command.aliases)) {
150
+ for (const alias of command.aliases) {
151
+ if (!isTerminalSafe(alias)) continue;
152
+ const aliasLabel = '/' + alias;
153
+ if (!seenLabels.has(aliasLabel)) {
154
+ seenLabels.add(aliasLabel);
155
+ commands.push({
156
+ value: primaryLabel,
157
+ match: alias,
158
+ label: aliasLabel,
159
+ description: sanitize(command.description || '')
160
+ });
161
+ }
162
+ }
163
+ }
164
+ }
128
165
 
129
166
  // Skills answer to the slash menu directly, the way claude-code surfaces a
130
167
  // skill as a command you simply type. `/docker` finds the Docker skill
131
168
  // without the user knowing it lives under `devops`, or that `/skills` exists
132
169
  // at all — which is the whole difficulty with a hundred-entry library.
133
- //
134
- // Ranked against the skill NAME first so the name is what matches, and
135
- // resolved to the canonical `/skills <domain>/<id>` on accept, so there is
136
- // still exactly one execution path and no second command namespace to collide
137
- // with the real commands.
138
170
  const skills = listSkillsForCompletion().map((skill) => ({
139
171
  value: `/skills ${skill.domain}/${skill.id}`,
140
172
  match: `${skill.id} ${skill.domain}`,