@causyne/agent 1.20.91 → 1.20.94

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 (46) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +116 -26
  3. package/src/agentLoop.ts +121 -26
  4. package/src/contextManager.js +2 -0
  5. package/src/decideTools.js +9 -0
  6. package/src/decideTools.ts +9 -0
  7. package/src/decisionPolicy.js +119 -1
  8. package/src/decisionPolicy.ts +129 -1
  9. package/src/historyPruner.js +16 -1
  10. package/src/historyPruner.ts +13 -1
  11. package/src/sandbox.js +33 -7
  12. package/src/skills/skillResourceSafety.js +70 -0
  13. package/src/skills/skillResourceSafety.ts +77 -0
  14. package/src/smartToolsUse.js +28 -11
  15. package/src/smartToolsUse.ts +34 -11
  16. package/src/taskShape.js +28 -13
  17. package/src/taskShape.ts +31 -12
  18. package/src/tools/codeSearcher.js +349 -210
  19. package/src/tools/codeSearcher.ts +408 -0
  20. package/src/tools/codebaseSearch.js +182 -68
  21. package/src/tools/codebaseSearch.ts +221 -0
  22. package/src/tools/deferredMcpSearch.js +94 -40
  23. package/src/tools/deferredMcpSearch.ts +89 -30
  24. package/src/tools/fsFind.js +180 -115
  25. package/src/tools/fsFind.ts +228 -0
  26. package/src/tools/fsList.js +149 -69
  27. package/src/tools/fsList.ts +224 -0
  28. package/src/tools/fsSearch.js +192 -189
  29. package/src/tools/fsSearch.ts +241 -0
  30. package/src/tools/readNativeSkill.js +34 -42
  31. package/src/tools/readNativeSkill.ts +38 -36
  32. package/src/tools/searchRelevance.js +70 -0
  33. package/src/tools/searchRelevance.ts +72 -0
  34. package/src/tools/toolSelfRepair.js +56 -20
  35. package/src/tools/toolSelfRepair.ts +58 -19
  36. package/src/tools/walkerSafety.js +445 -0
  37. package/src/tools/walkerSafety.ts +516 -0
  38. package/src/tui/composerGeometry.js +45 -0
  39. package/src/tui/composerGeometry.ts +80 -0
  40. package/src/tui/homeView.js +10 -6
  41. package/src/tui/homeView.ts +10 -6
  42. package/src/tui/lineEditor.js +8 -0
  43. package/src/tui/prompt.js +9 -4
  44. package/src/userSkills.js +183 -203
  45. package/src/userSkills.ts +301 -0
  46. package/src/userSkills.d.ts +0 -26
@@ -0,0 +1,516 @@
1
+ import fsSync from 'node:fs';
2
+ import fs from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import {
6
+ isPhysicalPathAllowed,
7
+ isProtectedPhysicalPath,
8
+ isWithinPhysicalPath,
9
+ physicalPath
10
+ } from '../agent/workspaceBoundary.js';
11
+
12
+ export interface SearchExecutionContext {
13
+ signal?: AbortSignal | undefined;
14
+ workspacePaths?: readonly string[] | undefined;
15
+ grantAllAccess?: boolean | undefined;
16
+ parentLoop?: {
17
+ workspaceRoot?: string | undefined;
18
+ } | undefined;
19
+ }
20
+
21
+ export const DEFAULT_TIMEOUT_MS = 15_000;
22
+ export const DEFAULT_MAX_DIRS = 10_000;
23
+ export const DEFAULT_MAX_FILES = 25_000;
24
+ export const DEFAULT_MAX_DEPTH = 16;
25
+ export const MAX_FILE_BYTES = 2 * 1024 * 1024;
26
+ export const SNIFF_BYTES = 8192;
27
+ export const MAX_REGEX_LENGTH = 500;
28
+ export const MAX_QUANTIFIER_REPEAT = 1000;
29
+
30
+ export const HEAVY_DEV_EXCLUDES: ReadonlySet<string> = new Set([
31
+ 'node_modules', '.git', '.hg', '.svn', 'dist', 'build', 'out', 'target',
32
+ '.gradle', '.m2', '.idea', '.vscode', '.next', '.nuxt', '.cache', '__pycache__',
33
+ 'venv', '.venv', 'vendor', 'Pods', 'DerivedData', 'coverage', '.terraform',
34
+ '.causyne_trash', '.npm', '.nvm', '.pyenv', '.rustup', '.cargo', '.cocoapods',
35
+ '.pub-cache'
36
+ ]);
37
+
38
+ /**
39
+ * Heavy user-home folders skipped ONLY when they sit directly inside $HOME.
40
+ * Explicitly passing e.g. ~/Library/Logs or ~/.causyne/logs as searchPath still works.
41
+ */
42
+ export const HOME_NOISE_EXCLUDES: ReadonlySet<string> = new Set([
43
+ 'Library', '.Trash', 'Applications', 'Movies', 'Music', 'Pictures',
44
+ 'CloudStorage', 'CoreSimulator', '.causyne', '.opencode', '.local',
45
+ '.android', 'AppData', '$RECYCLE.BIN', 'System Volume Information'
46
+ ]);
47
+
48
+ export const BINARY_EXTENSIONS_RE =
49
+ /\.(png|jpe?g|webp|gif|svg|bmp|ico|woff2?|ttf|otf|eot|blend\d?|glb|gltf|wasm|zip|tar|gz|bz2|xz|7z|rar|mp4|mov|avi|mkv|webm|mp3|wav|ogg|flac|aac|m4a|pdf|exe|dll|dylib|so|jar|class|o|a|bin|iso|dmg|img|sqlite|db)$/i;
50
+
51
+ export function expandHomePath(raw: string): string {
52
+ const trimmed = raw.trim();
53
+ const home = os.homedir();
54
+ if (trimmed === '~') return home;
55
+ if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
56
+ return path.join(home, trimmed.slice(2));
57
+ }
58
+ return trimmed;
59
+ }
60
+
61
+ function defaultBaseDir(context?: SearchExecutionContext): string {
62
+ const fromLoop = context?.parentLoop?.workspaceRoot;
63
+ if (typeof fromLoop === 'string' && fromLoop.trim()) {
64
+ return path.resolve(expandHomePath(fromLoop));
65
+ }
66
+ const firstWs = context?.workspacePaths?.find(
67
+ (entry): entry is string => typeof entry === 'string' && entry.trim().length > 0
68
+ );
69
+ if (firstWs) {
70
+ return path.resolve(expandHomePath(firstWs));
71
+ }
72
+ return process.cwd();
73
+ }
74
+
75
+ export function resolveSearchRoot(rawPath: unknown, context?: SearchExecutionContext): string {
76
+ const baseDir = defaultBaseDir(context);
77
+ if (typeof rawPath === 'string' && rawPath.trim()) {
78
+ const expanded = expandHomePath(rawPath);
79
+ return path.resolve(baseDir, expanded);
80
+ }
81
+ return baseDir;
82
+ }
83
+
84
+ export interface SearchScopeResult {
85
+ allowed: boolean;
86
+ resolvedPath: string;
87
+ realPath: string | null;
88
+ error?: string | undefined;
89
+ }
90
+
91
+ export function checkSearchScope(
92
+ candidatePath: string,
93
+ context?: SearchExecutionContext
94
+ ): SearchScopeResult {
95
+ const expanded = expandHomePath(candidatePath);
96
+ const resolved = path.resolve(defaultBaseDir(context), expanded);
97
+ const real = physicalPath(resolved);
98
+
99
+ if (!real) {
100
+ return {
101
+ allowed: false,
102
+ resolvedPath: resolved,
103
+ realPath: null,
104
+ error: `Path is inaccessible or resolves through a broken/looping symlink: ${candidatePath}`
105
+ };
106
+ }
107
+
108
+ if (isProtectedPhysicalPath(resolved) || isProtectedPhysicalPath(real)) {
109
+ return {
110
+ allowed: false,
111
+ resolvedPath: resolved,
112
+ realPath: real,
113
+ error: `Cannot search protected system path: ${candidatePath}`
114
+ };
115
+ }
116
+
117
+ if (
118
+ Array.isArray(context?.workspacePaths) &&
119
+ context.workspacePaths.length > 0 &&
120
+ context.grantAllAccess !== true
121
+ ) {
122
+ const allowedRoots = context.workspacePaths
123
+ .filter((entry): entry is string => typeof entry === 'string' && entry.trim().length > 0)
124
+ .map(expandHomePath);
125
+ if (allowedRoots.length > 0 && !isPhysicalPathAllowed(resolved, allowedRoots, false)) {
126
+ return {
127
+ allowed: false,
128
+ resolvedPath: resolved,
129
+ realPath: real,
130
+ error: `Path outside allowed workspace: ${candidatePath}`
131
+ };
132
+ }
133
+ }
134
+
135
+ return {
136
+ allowed: true,
137
+ resolvedPath: resolved,
138
+ realPath: real
139
+ };
140
+ }
141
+
142
+ export function isSafeSymlinkTarget(
143
+ linkTargetReal: string,
144
+ rootReal: string,
145
+ context?: SearchExecutionContext
146
+ ): boolean {
147
+ if (isProtectedPhysicalPath(linkTargetReal)) return false;
148
+ if (!isWithinPhysicalPath(linkTargetReal, rootReal)) return false;
149
+ if (
150
+ Array.isArray(context?.workspacePaths) &&
151
+ context.workspacePaths.length > 0 &&
152
+ context.grantAllAccess !== true
153
+ ) {
154
+ const allowedRoots = context.workspacePaths
155
+ .filter((entry): entry is string => typeof entry === 'string' && entry.trim().length > 0)
156
+ .map(expandHomePath);
157
+ if (allowedRoots.length > 0 && !isPhysicalPathAllowed(linkTargetReal, allowedRoots, false)) {
158
+ return false;
159
+ }
160
+ }
161
+ return true;
162
+ }
163
+
164
+ export function normalizeComparePath(value: string): string {
165
+ const resolved = path.resolve(value);
166
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
167
+ }
168
+
169
+ function realHomeDir(): string {
170
+ const home = os.homedir();
171
+ try {
172
+ return fsSync.realpathSync.native(home);
173
+ } catch {
174
+ return path.resolve(home);
175
+ }
176
+ }
177
+
178
+ export function shouldExcludeChild(
179
+ currentDirReal: string,
180
+ childName: string,
181
+ ignorePatterns: readonly string[] = []
182
+ ): boolean {
183
+ if (HEAVY_DEV_EXCLUDES.has(childName)) return true;
184
+ if (
185
+ HOME_NOISE_EXCLUDES.has(childName) &&
186
+ normalizeComparePath(currentDirReal) === normalizeComparePath(realHomeDir())
187
+ ) {
188
+ return true;
189
+ }
190
+ for (const pattern of ignorePatterns) {
191
+ if (pattern === childName) return true;
192
+ if (pattern.startsWith('*') && childName.endsWith(pattern.slice(1))) return true;
193
+ if (pattern.endsWith('*') && childName.startsWith(pattern.slice(0, -1))) return true;
194
+ }
195
+ return false;
196
+ }
197
+
198
+ export async function loadGitIgnoreNames(rootDir: string): Promise<string[]> {
199
+ const patterns: string[] = [];
200
+ try {
201
+ const raw = await fs.readFile(path.join(rootDir, '.gitignore'), 'utf8');
202
+ for (const line of raw.split('\n')) {
203
+ const trimmed = line.trim();
204
+ if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('!')) continue;
205
+ let start = 0;
206
+ let end = trimmed.length;
207
+ while (start < end && trimmed[start] === '/') start++;
208
+ while (end > start && trimmed[end - 1] === '/') end--;
209
+ const cleaned = trimmed.slice(start, end);
210
+ if (cleaned) patterns.push(cleaned);
211
+ }
212
+ } catch {
213
+ // Missing or unreadable .gitignore is normal outside repos.
214
+ }
215
+ return patterns;
216
+ }
217
+
218
+ export async function looksBinaryFile(filePath: string): Promise<boolean> {
219
+ if (BINARY_EXTENSIONS_RE.test(filePath)) return true;
220
+ let handle: fs.FileHandle | undefined;
221
+ try {
222
+ handle = await fs.open(filePath, 'r');
223
+ const buffer = Buffer.alloc(SNIFF_BYTES);
224
+ const { bytesRead } = await handle.read(buffer, 0, SNIFF_BYTES, 0);
225
+ return buffer.subarray(0, bytesRead).includes(0);
226
+ } catch {
227
+ return true;
228
+ } finally {
229
+ if (handle) {
230
+ await handle.close().catch(() => {});
231
+ }
232
+ }
233
+ }
234
+
235
+ export interface TraversalGuardOptions {
236
+ maxDirs?: number | undefined;
237
+ maxFiles?: number | undefined;
238
+ maxDepth?: number | undefined;
239
+ timeoutMs?: number | undefined;
240
+ signal?: AbortSignal | undefined;
241
+ }
242
+
243
+ export type TraversalStopReason = 'aborted' | 'timeout' | 'max_dirs' | 'max_files' | null;
244
+
245
+ export class TraversalGuard {
246
+ readonly maxDirs: number;
247
+ readonly maxFiles: number;
248
+ readonly maxDepth: number;
249
+ readonly timeoutMs: number;
250
+ readonly signal: AbortSignal | undefined;
251
+ readonly startedAt: number;
252
+ dirsVisited = 0;
253
+ filesVisited = 0;
254
+ stopReason: TraversalStopReason = null;
255
+
256
+ constructor(options: TraversalGuardOptions = {}) {
257
+ this.maxDirs = options.maxDirs ?? DEFAULT_MAX_DIRS;
258
+ this.maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
259
+ this.maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;
260
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
261
+ this.signal = options.signal;
262
+ this.startedAt = Date.now();
263
+ }
264
+
265
+ checkStopped(): TraversalStopReason {
266
+ if (this.stopReason) return this.stopReason;
267
+ if (this.signal?.aborted) {
268
+ this.stopReason = 'aborted';
269
+ return this.stopReason;
270
+ }
271
+ if (Date.now() - this.startedAt >= this.timeoutMs) {
272
+ this.stopReason = 'timeout';
273
+ return this.stopReason;
274
+ }
275
+ return null;
276
+ }
277
+
278
+ enterDir(depth: number): boolean {
279
+ if (this.checkStopped()) return false;
280
+ if (depth > this.maxDepth) return false;
281
+ if (this.dirsVisited >= this.maxDirs) {
282
+ this.stopReason = 'max_dirs';
283
+ return false;
284
+ }
285
+ this.dirsVisited++;
286
+ return true;
287
+ }
288
+
289
+ countFile(): boolean {
290
+ if (this.checkStopped()) return false;
291
+ if (this.filesVisited >= this.maxFiles) {
292
+ this.stopReason = 'max_files';
293
+ return false;
294
+ }
295
+ this.filesVisited++;
296
+ return true;
297
+ }
298
+
299
+ stopNotice(): string {
300
+ switch (this.stopReason) {
301
+ case 'timeout':
302
+ return `stopped after ${this.timeoutMs}ms budget (narrow search path or filter to continue)`;
303
+ case 'max_dirs':
304
+ return `stopped after visiting ${this.dirsVisited} directories (narrow search path)`;
305
+ case 'max_files':
306
+ return `stopped after inspecting ${this.filesVisited} files (narrow search path)`;
307
+ case 'aborted':
308
+ return 'aborted';
309
+ default:
310
+ return '';
311
+ }
312
+ }
313
+ }
314
+
315
+ export function createTraversalGuard(options: TraversalGuardOptions = {}): TraversalGuard {
316
+ return new TraversalGuard(options);
317
+ }
318
+
319
+ interface ParenFrame {
320
+ hasMultiRepeat: boolean;
321
+ hasAlternation: boolean;
322
+ }
323
+
324
+ /**
325
+ * Linear-time O(n) character scanner that rejects pathological regex patterns
326
+ * (e.g. `(a+)+`, `(a|aa)+`, huge `{m,n}` counts, oversized patterns) without
327
+ * itself invoking any backtracking regular expression.
328
+ */
329
+ export function validateRegexSafety(pattern: string): string | null {
330
+ if (typeof pattern !== 'string' || pattern.length === 0) {
331
+ return 'Regular expression pattern must be a non-empty string.';
332
+ }
333
+ if (pattern.length > MAX_REGEX_LENGTH) {
334
+ return `Regular expression exceeds maximum length of ${MAX_REGEX_LENGTH} characters.`;
335
+ }
336
+
337
+ const stack: ParenFrame[] = [{ hasMultiRepeat: false, hasAlternation: false }];
338
+ let inCharClass = false;
339
+ let lastTokenWasQuantifiable = false;
340
+ let lastGroupFrame: ParenFrame | null = null;
341
+
342
+ for (let i = 0; i < pattern.length; i++) {
343
+ const ch = pattern[i]!;
344
+ if (ch === '\\') {
345
+ if (i + 1 >= pattern.length) {
346
+ return 'Trailing backslash in regular expression.';
347
+ }
348
+ const next = pattern[i + 1]!;
349
+ if (!inCharClass && next >= '1' && next <= '9') {
350
+ return 'Backreferences are disallowed in search regular expressions for ReDoS safety.';
351
+ }
352
+ i++;
353
+ lastTokenWasQuantifiable = true;
354
+ lastGroupFrame = null;
355
+ continue;
356
+ }
357
+
358
+ if (inCharClass) {
359
+ if (ch === ']') {
360
+ inCharClass = false;
361
+ lastTokenWasQuantifiable = true;
362
+ lastGroupFrame = null;
363
+ }
364
+ continue;
365
+ }
366
+
367
+ if (ch === '[') {
368
+ inCharClass = true;
369
+ lastTokenWasQuantifiable = false;
370
+ lastGroupFrame = null;
371
+ continue;
372
+ }
373
+
374
+ if (ch === '(') {
375
+ stack.push({ hasMultiRepeat: false, hasAlternation: false });
376
+ lastTokenWasQuantifiable = false;
377
+ lastGroupFrame = null;
378
+ continue;
379
+ }
380
+
381
+ if (ch === ')') {
382
+ if (stack.length <= 1) {
383
+ lastTokenWasQuantifiable = false;
384
+ lastGroupFrame = null;
385
+ continue;
386
+ }
387
+ const popped = stack.pop()!;
388
+ const parent = stack[stack.length - 1]!;
389
+ if (popped.hasMultiRepeat) parent.hasMultiRepeat = true;
390
+ lastGroupFrame = popped;
391
+ lastTokenWasQuantifiable = true;
392
+ continue;
393
+ }
394
+
395
+ if (ch === '|') {
396
+ const top = stack[stack.length - 1]!;
397
+ top.hasAlternation = true;
398
+ lastTokenWasQuantifiable = false;
399
+ lastGroupFrame = null;
400
+ continue;
401
+ }
402
+
403
+ let isMultiRepeat = false;
404
+ let isAnyQuantifier = false;
405
+ let jumpTo = i;
406
+
407
+ if (ch === '*' || ch === '+') {
408
+ isAnyQuantifier = true;
409
+ isMultiRepeat = true;
410
+ } else if (ch === '?') {
411
+ if (lastTokenWasQuantifiable) {
412
+ isAnyQuantifier = true;
413
+ isMultiRepeat = false;
414
+ }
415
+ } else if (ch === '{') {
416
+ let j = i + 1;
417
+ let first = '';
418
+ let second = '';
419
+ let seenComma = false;
420
+ let validBrace = false;
421
+ while (j < pattern.length) {
422
+ const c = pattern[j]!;
423
+ if (c >= '0' && c <= '9') {
424
+ if (seenComma) second += c;
425
+ else first += c;
426
+ j++;
427
+ } else if (c === ',' && !seenComma && first.length > 0) {
428
+ seenComma = true;
429
+ j++;
430
+ } else if (c === '}' && first.length > 0) {
431
+ validBrace = true;
432
+ break;
433
+ } else {
434
+ break;
435
+ }
436
+ }
437
+ if (validBrace) {
438
+ const minCount = Number.parseInt(first, 10);
439
+ const maxCount = seenComma
440
+ ? (second.length > 0 ? Number.parseInt(second, 10) : Infinity)
441
+ : minCount;
442
+ if (minCount > MAX_QUANTIFIER_REPEAT || (Number.isFinite(maxCount) && maxCount > MAX_QUANTIFIER_REPEAT)) {
443
+ return `Quantifier repetition count exceeds ${MAX_QUANTIFIER_REPEAT}.`;
444
+ }
445
+ isAnyQuantifier = true;
446
+ isMultiRepeat = maxCount > 1;
447
+ jumpTo = j;
448
+ }
449
+ }
450
+
451
+ if (isAnyQuantifier) {
452
+ i = jumpTo;
453
+ if (i + 1 < pattern.length && pattern[i + 1] === '?') {
454
+ i++; // lazy modifier
455
+ }
456
+ if (isMultiRepeat) {
457
+ const top = stack[stack.length - 1]!;
458
+ top.hasMultiRepeat = true;
459
+ if (lastGroupFrame && (lastGroupFrame.hasMultiRepeat || lastGroupFrame.hasAlternation)) {
460
+ return 'Nested quantifiers are disallowed to prevent catastrophic backtracking (ReDoS).';
461
+ }
462
+ }
463
+ lastTokenWasQuantifiable = false;
464
+ lastGroupFrame = null;
465
+ continue;
466
+ }
467
+
468
+ lastTokenWasQuantifiable = true;
469
+ lastGroupFrame = null;
470
+ }
471
+
472
+ return null;
473
+ }
474
+
475
+ export function compileSafeSearchRegex(
476
+ query: string,
477
+ options: { isRegex?: boolean | undefined; caseInsensitive?: boolean | undefined } = {}
478
+ ): { regex?: RegExp; error?: string } {
479
+ if (typeof query !== 'string' || query.length === 0) {
480
+ return { error: 'Query must be a non-empty string.' };
481
+ }
482
+ const flags = options.caseInsensitive ? 'i' : '';
483
+ if (!options.isRegex) {
484
+ const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
485
+ return { regex: new RegExp(escaped, flags) };
486
+ }
487
+ const unsafeReason = validateRegexSafety(query);
488
+ if (unsafeReason) {
489
+ return { error: unsafeReason };
490
+ }
491
+ try {
492
+ return { regex: new RegExp(query, flags) };
493
+ } catch (error: unknown) {
494
+ const msg = error instanceof Error ? error.message : String(error);
495
+ return { error: `Invalid regular expression: ${msg}` };
496
+ }
497
+ }
498
+
499
+ export function buildHomeGlobExcludes(): string[] {
500
+ const excludes: string[] = [];
501
+ for (const name of HEAVY_DEV_EXCLUDES) {
502
+ excludes.push(`!**/${name}/**`);
503
+ }
504
+ return excludes;
505
+ }
506
+
507
+ export function buildTopLevelHomeExcludes(targetRealPath: string): string[] {
508
+ if (normalizeComparePath(targetRealPath) !== normalizeComparePath(realHomeDir())) {
509
+ return [];
510
+ }
511
+ const excludes: string[] = [];
512
+ for (const name of HOME_NOISE_EXCLUDES) {
513
+ excludes.push(`!${name}/**`);
514
+ }
515
+ return excludes;
516
+ }
@@ -0,0 +1,45 @@
1
+ export function composerGeometry(requestedWidth, barColumns, gutterColumns) {
2
+ const width = Number.isFinite(requestedWidth)
3
+ ? Math.max(4, Math.trunc(requestedWidth))
4
+ : 80;
5
+ const boxWidth = width - 1; // never occupy the terminal's deferred-wrap cell
6
+ const glyph = Number.isFinite(barColumns) ? Math.max(0, Math.trunc(barColumns)) : 1;
7
+ const gutter = Number.isFinite(gutterColumns) ? Math.max(0, Math.trunc(gutterColumns)) : 1;
8
+ const inset = Math.min(glyph + gutter, Math.max(0, boxWidth - 2));
9
+ const bodyWidth = Math.max(1, boxWidth - inset);
10
+ const editorWidth = Math.max(1, bodyWidth - 1); // reserve a full cursor cell
11
+ return { boxWidth, inset, bodyWidth, editorWidth, maxCaretCol: boxWidth - 1 };
12
+ }
13
+ /**
14
+ * In a small terminal the editor is more important than the full brand banner.
15
+ * This helper never loses the caret or returns more rows than the Stage owns.
16
+ * The ordinary roomy Home composition is unchanged.
17
+ */
18
+ export function fitHomeContent(logoRows, promptRows, stageHeight, caretRow, requestedSpacer) {
19
+ const available = Number.isFinite(stageHeight)
20
+ ? Math.max(1, Math.trunc(stageHeight))
21
+ : 24;
22
+ const prompt = promptRows.length ? [...promptRows] : [''];
23
+ const caret = Number.isFinite(caretRow)
24
+ ? Math.max(0, Math.min(prompt.length - 1, Math.trunc(caretRow)))
25
+ : 0;
26
+ const promptCount = Math.min(available, prompt.length);
27
+ const start = prompt.length > available
28
+ ? Math.min(Math.max(0, caret - Math.floor(available / 2)), prompt.length - available)
29
+ : 0;
30
+ const visiblePrompt = prompt.slice(start, start + promptCount);
31
+ const remaining = available - visiblePrompt.length;
32
+ // A cropped rotor/wordmark looks broken. On cramped terminals, hide the
33
+ // banner as a whole rather than displaying an arbitrary bottom fragment.
34
+ const showLogo = logoRows.length > 0 && remaining >= logoRows.length;
35
+ const visibleLogo = showLogo ? [...logoRows] : [];
36
+ const spacer = showLogo
37
+ ? Math.min(Math.max(0, Number.isFinite(requestedSpacer) ? Math.trunc(requestedSpacer) : 0), remaining - logoRows.length)
38
+ : 0;
39
+ return {
40
+ logoRows: visibleLogo,
41
+ promptRows: visiblePrompt,
42
+ spacer,
43
+ caretRow: Math.max(0, Math.min(visiblePrompt.length - 1, caret - start))
44
+ };
45
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Causyne composer geometry. This module owns column arithmetic, never I/O.
3
+ *
4
+ * `barBlock` consumes the left bar + gutter. A painted block is exactly
5
+ * `boxWidth` cells, but the editing surface must reserve a caret cell so a
6
+ * full row cannot position the terminal cursor in the clipped right margin.
7
+ */
8
+ export interface ComposerGeometry {
9
+ boxWidth: number;
10
+ inset: number;
11
+ bodyWidth: number;
12
+ editorWidth: number;
13
+ maxCaretCol: number;
14
+ }
15
+
16
+ export function composerGeometry(
17
+ requestedWidth: number,
18
+ barColumns: number,
19
+ gutterColumns: number
20
+ ): ComposerGeometry {
21
+ const width = Number.isFinite(requestedWidth)
22
+ ? Math.max(4, Math.trunc(requestedWidth))
23
+ : 80;
24
+ const boxWidth = width - 1; // never occupy the terminal's deferred-wrap cell
25
+ const glyph = Number.isFinite(barColumns) ? Math.max(0, Math.trunc(barColumns)) : 1;
26
+ const gutter = Number.isFinite(gutterColumns) ? Math.max(0, Math.trunc(gutterColumns)) : 1;
27
+ const inset = Math.min(glyph + gutter, Math.max(0, boxWidth - 2));
28
+ const bodyWidth = Math.max(1, boxWidth - inset);
29
+ const editorWidth = Math.max(1, bodyWidth - 1); // reserve a full cursor cell
30
+ return { boxWidth, inset, bodyWidth, editorWidth, maxCaretCol: boxWidth - 1 };
31
+ }
32
+
33
+ export interface FittedHomeContent {
34
+ /** Full banner, or none when the terminal cannot show it without clipping. */
35
+ logoRows: string[];
36
+ /** Composer rows kept as a contiguous window around the editing caret. */
37
+ promptRows: string[];
38
+ spacer: number;
39
+ caretRow: number;
40
+ }
41
+
42
+ /**
43
+ * In a small terminal the editor is more important than the full brand banner.
44
+ * This helper never loses the caret or returns more rows than the Stage owns.
45
+ * The ordinary roomy Home composition is unchanged.
46
+ */
47
+ export function fitHomeContent(
48
+ logoRows: readonly string[],
49
+ promptRows: readonly string[],
50
+ stageHeight: number,
51
+ caretRow: number,
52
+ requestedSpacer: number
53
+ ): FittedHomeContent {
54
+ const available = Number.isFinite(stageHeight)
55
+ ? Math.max(1, Math.trunc(stageHeight))
56
+ : 24;
57
+ const prompt = promptRows.length ? [...promptRows] : [''];
58
+ const caret = Number.isFinite(caretRow)
59
+ ? Math.max(0, Math.min(prompt.length - 1, Math.trunc(caretRow)))
60
+ : 0;
61
+ const promptCount = Math.min(available, prompt.length);
62
+ const start = prompt.length > available
63
+ ? Math.min(Math.max(0, caret - Math.floor(available / 2)), prompt.length - available)
64
+ : 0;
65
+ const visiblePrompt = prompt.slice(start, start + promptCount);
66
+ const remaining = available - visiblePrompt.length;
67
+ // A cropped rotor/wordmark looks broken. On cramped terminals, hide the
68
+ // banner as a whole rather than displaying an arbitrary bottom fragment.
69
+ const showLogo = logoRows.length > 0 && remaining >= logoRows.length;
70
+ const visibleLogo = showLogo ? [...logoRows] : [];
71
+ const spacer = showLogo
72
+ ? Math.min(Math.max(0, Number.isFinite(requestedSpacer) ? Math.trunc(requestedSpacer) : 0), remaining - logoRows.length)
73
+ : 0;
74
+ return {
75
+ logoRows: visibleLogo,
76
+ promptRows: visiblePrompt,
77
+ spacer,
78
+ caretRow: Math.max(0, Math.min(visiblePrompt.length - 1, caret - start))
79
+ };
80
+ }
@@ -1,5 +1,6 @@
1
1
  import { sessionBanner } from './banner.js';
2
2
  import { centerRows } from './layout.js';
3
+ import { fitHomeContent } from './composerGeometry.js';
3
4
  import { panelRows } from './overlay.js';
4
5
  /** A modal before the first conversation belongs to the centered home view. */
5
6
  export function isStartupDialog(surface) {
@@ -45,17 +46,20 @@ export function placeHome(info, promptRows, columns, height, caretRow, caretCol)
45
46
  const available = Math.max(1, Math.floor(height));
46
47
  const logo = centerRows(sessionBanner(info, columns, { height: available }), columns).rows;
47
48
  const spacer = available >= 25 ? 2 : 1;
48
- const required = logo.length + spacer + promptRows.length;
49
+ // When the window is short, preserve the composer and editing caret first.
50
+ // The logo yields height; it must never push a wrapped draft off-screen.
51
+ const fitted = fitHomeContent(logo, promptRows, available, caretRow, spacer);
52
+ const required = fitted.logoRows.length + fitted.spacer + fitted.promptRows.length;
49
53
  const top = Math.max(0, Math.floor((available - required) / 2));
50
54
  const rows = [
51
55
  ...Array(top).fill(''),
52
- ...logo,
53
- ...Array(spacer).fill(''),
54
- ...promptRows
56
+ ...fitted.logoRows,
57
+ ...Array(fitted.spacer).fill(''),
58
+ ...fitted.promptRows
55
59
  ];
56
60
  return {
57
- rows: rows.slice(0, available),
58
- caretRow: Math.min(available - 1, top + logo.length + spacer + Math.max(0, caretRow)),
61
+ rows,
62
+ caretRow: top + fitted.logoRows.length + fitted.spacer + fitted.caretRow,
59
63
  caretCol: Math.max(0, Math.min(caretCol, columns - 2))
60
64
  };
61
65
  }