@causyne/agent 1.20.103 → 1.20.105

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/src/observer.ts CHANGED
@@ -76,6 +76,17 @@ export function extractClaimedLocalUrls(text: string): string[] {
76
76
  return [...unique];
77
77
  }
78
78
 
79
+ function isWorkspaceArtifact(workspaceRoot: string, targetPath: string): boolean {
80
+ try {
81
+ const root = fs.realpathSync(workspaceRoot);
82
+ const target = fs.realpathSync(targetPath);
83
+ const relative = path.relative(root, target);
84
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
85
+ } catch {
86
+ return false;
87
+ }
88
+ }
89
+
79
90
  export class CausyneObserver {
80
91
  /**
81
92
  * Evaluates the current state of a task after a tool outcome or at a step boundary.
@@ -141,7 +152,8 @@ export class CausyneObserver {
141
152
 
142
153
  // Check if the agent claims completion
143
154
  if (context.agentClaim && context.agentClaim.trim()) {
144
- const claim = context.agentClaim.toLowerCase();
155
+ // Negative completion statements must not be promoted to verified outcomes.
156
+ const claim = context.agentClaim.toLowerCase().replace(/\b(?:not|never|isn't|wasn't|haven't|hasn't)\s+(?:(?:yet|fully|actually|successfully)\s+)?(?:done|complete|completed|finished|implemented|fixed|verified)\b/gi, '');
145
157
  const claimsCompletion = /\b(?:done|complete|completed|finished|implemented|fixed|verified)\b|\b(?:is\s+(?:running|live|available|listening|served)\s+(?:at|on)|application\s+is\s+running)\b/i.test(claim);
146
158
 
147
159
  if (claimsCompletion) {
@@ -149,10 +161,9 @@ export class CausyneObserver {
149
161
  const hasMutations = outcomes.some(o =>
150
162
  ['fs_write', 'fs_edit', 'MultiEdit', 'write_file', 'edit_file'].includes(o.tool)
151
163
  );
152
- const hasPassingVerification = outcomes.some(o =>
153
- o.success && (
164
+ const hasPassingVerification = outcomes.slice(outcomes.findLastIndex(o => ['fs_write', 'fs_edit', 'MultiEdit', 'write_file', 'edit_file'].includes(o.tool)) + 1).some(o =>
165
+ o.success && (o.exitCode == null || o.exitCode === 0) && (
154
166
  o.rendered === true ||
155
- o.tool === 'browser_act' ||
156
167
  o.tool === 'verify_local_web' ||
157
168
  (o.command && /\b(?:test|build|check|typecheck|vitest|jest|pytest)\b/i.test(o.command))
158
169
  )
@@ -192,6 +203,7 @@ export class CausyneObserver {
192
203
  * Deterministically verifies code deliverables (targeted test, build, syntax).
193
204
  */
194
205
  public verifyCode(req: CodeVerificationRequest): { verified: boolean; error?: string; evidence: string } {
206
+ if (!req.changedFiles?.length) return { verified: false, error: 'No code deliverables supplied.', evidence: 'no_files' };
195
207
  if (req.changedFiles && req.changedFiles.length > 0) {
196
208
  for (const file of req.changedFiles) {
197
209
  const fullPath = path.isAbsolute(file) ? file : path.join(req.workspaceRoot, file);
@@ -202,6 +214,12 @@ export class CausyneObserver {
202
214
  evidence: 'file_missing'
203
215
  };
204
216
  }
217
+ if (!isWorkspaceArtifact(req.workspaceRoot, fullPath)) {
218
+ return { verified: false, error: `Target deliverable ${file} is outside the workspace.`, evidence: 'outside_workspace' };
219
+ }
220
+ if (!fs.statSync(fullPath).isFile() || fs.statSync(fullPath).size === 0) {
221
+ return { verified: false, error: `Target deliverable ${file} is not a non-empty file.`, evidence: 'invalid_file' };
222
+ }
205
223
  }
206
224
  }
207
225
 
@@ -220,6 +238,8 @@ export class CausyneObserver {
220
238
  return { verified: false, missingHeadings: req.requiredHeadings || [] };
221
239
  }
222
240
 
241
+ if (!isWorkspaceArtifact(req.workspaceRoot, fullPath)) return { verified: false, missingHeadings: req.requiredHeadings || [] };
242
+ if (!fs.statSync(fullPath).isFile()) return { verified: false, missingHeadings: req.requiredHeadings || [] };
223
243
  const content = fs.readFileSync(fullPath, 'utf8');
224
244
  const missing: string[] = [];
225
245
 
@@ -245,8 +265,11 @@ export class CausyneObserver {
245
265
  return { verified: false, bytes: 0, error: `Media asset not found: ${req.artifactPath}` };
246
266
  }
247
267
 
268
+ if (!isWorkspaceArtifact(req.workspaceRoot, fullPath)) return { verified: false, bytes: 0, error: 'Media artifact is outside the workspace.' };
248
269
  const stat = fs.statSync(fullPath);
270
+ if (!stat.isFile()) return { verified: false, bytes: 0, error: 'Media artifact must be a regular file.' };
249
271
  const minBytes = req.minBytes ?? 100;
272
+ if (!Number.isSafeInteger(minBytes) || minBytes < 0) return { verified: false, bytes: stat.size, error: 'Invalid minimum artifact size.' };
250
273
  if (stat.size < minBytes) {
251
274
  return { verified: false, bytes: stat.size, error: `Media asset too small (${stat.size} bytes < ${minBytes} bytes)` };
252
275
  }
@@ -267,10 +290,17 @@ export class CausyneObserver {
267
290
  return;
268
291
  }
269
292
 
293
+ if (url.username || url.password) {
294
+ resolve({ verified: false, error: 'Local verification URL must not contain credentials.' });
295
+ return;
296
+ }
297
+
270
298
  const clientReq = http.get(req.endpoint, { timeout: req.timeoutMs ?? 3000 }, (res) => {
271
299
  res.resume();
272
300
  const expected = req.expectedStatus ?? 200;
273
- const ok = res.statusCode === expected || (res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 400);
301
+ const ok = req.expectedStatus === undefined
302
+ ? (res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 300)
303
+ : res.statusCode === expected;
274
304
  const result: { verified: boolean; statusCode?: number; error?: string } = { verified: Boolean(ok) };
275
305
  if (typeof res.statusCode === 'number') result.statusCode = res.statusCode;
276
306
  if (!ok) result.error = `HTTP ${res.statusCode ?? 'unknown'}`;
@@ -24,11 +24,15 @@ function record(value) {
24
24
  }
25
25
  function operationFamily(args) {
26
26
  const command = typeof args.command === 'string' ? args.command
27
- : typeof args.cmd === 'string' ? args.cmd : '';
27
+ : typeof args.cmd === 'string' ? args.cmd
28
+ : typeof args.CommandLine === 'string' ? args.CommandLine
29
+ : typeof args.commandLine === 'string' ? args.commandLine
30
+ : typeof args.script === 'string' ? args.script : '';
28
31
  if (!command) {
29
- if (typeof args.url === 'string') {
32
+ const endpoint = typeof args.url === 'string' ? args.url : typeof args.endpoint === 'string' ? args.endpoint : '';
33
+ if (endpoint) {
30
34
  try {
31
- return new URL(args.url).hostname.toLowerCase();
35
+ return new URL(endpoint).hostname.toLowerCase();
32
36
  }
33
37
  catch {
34
38
  return '';
@@ -46,15 +50,16 @@ function operationFamily(args) {
46
50
  }
47
51
  function issueKey(tool, args) {
48
52
  const family = operationFamily(args);
49
- const target = String(args.path ?? args.file_path ?? args.filePath ?? '');
53
+ const target = String(args.path ?? args.file_path ?? args.filePath ?? args.target ?? args.endpoint ?? args.url ?? '');
54
+ const workspace = String(args.cwd ?? '');
50
55
  // Changing error text/class does not buy another three attempts at the same
51
56
  // operation. Targets are hashed and never included in recovery messages.
52
- return createHash('sha256').update(`${tool}\0${family}\0${target}`).digest('hex');
57
+ return createHash('sha256').update(`${tool}\0${family}\0${target}\0${workspace}`).digest('hex');
53
58
  }
54
59
  function lastGoodTool(outcomes) {
55
60
  for (let index = outcomes.length - 1; index >= 0; index--) {
56
61
  const outcome = outcomes[index];
57
- if (outcome?.success)
62
+ if (outcome?.success && (outcome.exitCode == null || outcome.exitCode === 0) && !outcome.error?.trim())
58
63
  return outcome.tool;
59
64
  }
60
65
  return null;
@@ -91,7 +96,9 @@ export class TimeMachine {
91
96
  }
92
97
  observe(tool, args, result, outcomes = []) {
93
98
  const value = record(result);
94
- const failed = value.success === false || typeof value.error === 'string';
99
+ const failed = value.success === false || (typeof value.error === 'string' && value.error.trim().length > 0)
100
+ || (typeof value.exitCode === 'number' && (!Number.isFinite(value.exitCode) || value.exitCode !== 0))
101
+ || value.failureKind === 'site_refusal';
95
102
  const classification = failed ? failureClass(value) || 'failed' : '';
96
103
  const key = issueKey(tool, args);
97
104
  const good = lastGoodTool(outcomes);
@@ -117,7 +124,7 @@ export class TimeMachine {
117
124
  }
118
125
  const error = typeof value.error === 'string' ? value.error : '';
119
126
  const needsHuman = classification === 'permission' || /user denied|approval required|authentication required/i.test(error);
120
- const attempt = (this.failures.get(key) || 0) + 1;
127
+ const attempt = Math.min(TIME_MACHINE_MAX_ATTEMPTS, (this.failures.get(key) || 0) + 1);
121
128
  this.failures.set(key, attempt);
122
129
  const checkpoint = good ? ` Last successful tool: ${good}.` : '';
123
130
  if (needsHuman) {
@@ -142,6 +149,11 @@ export class TimeMachine {
142
149
  failureClass: classification, lastGoodTool: good,
143
150
  guidance: `Further attempts were not approved. Stop this task. Give a brief evidence-based report and state what remains unresolved.${checkpoint}` };
144
151
  }
152
+ if (classification === 'rate_limited' && attempt < TIME_MACHINE_CONSENT_AT) {
153
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
154
+ failureClass: classification, lastGoodTool: good,
155
+ guidance: `Rate limit reached. Respect the provider's retry/reset window; do not immediately resend the same request.${checkpoint}` };
156
+ }
145
157
  if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
146
158
  return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
147
159
  failureClass: classification, lastGoodTool: good,
@@ -43,10 +43,14 @@ function record(value: unknown): Record<string, unknown> {
43
43
 
44
44
  function operationFamily(args: Record<string, unknown>): string {
45
45
  const command = typeof args.command === 'string' ? args.command
46
- : typeof args.cmd === 'string' ? args.cmd : '';
46
+ : typeof args.cmd === 'string' ? args.cmd
47
+ : typeof args.CommandLine === 'string' ? args.CommandLine
48
+ : typeof args.commandLine === 'string' ? args.commandLine
49
+ : typeof args.script === 'string' ? args.script : '';
47
50
  if (!command) {
48
- if (typeof args.url === 'string') {
49
- try { return new URL(args.url).hostname.toLowerCase(); } catch { return ''; }
51
+ const endpoint = typeof args.url === 'string' ? args.url : typeof args.endpoint === 'string' ? args.endpoint : '';
52
+ if (endpoint) {
53
+ try { return new URL(endpoint).hostname.toLowerCase(); } catch { return ''; }
50
54
  }
51
55
  return '';
52
56
  }
@@ -61,16 +65,17 @@ function operationFamily(args: Record<string, unknown>): string {
61
65
 
62
66
  function issueKey(tool: string, args: Record<string, unknown>): string {
63
67
  const family = operationFamily(args);
64
- const target = String(args.path ?? args.file_path ?? args.filePath ?? '');
68
+ const target = String(args.path ?? args.file_path ?? args.filePath ?? args.target ?? args.endpoint ?? args.url ?? '');
69
+ const workspace = String(args.cwd ?? '');
65
70
  // Changing error text/class does not buy another three attempts at the same
66
71
  // operation. Targets are hashed and never included in recovery messages.
67
- return createHash('sha256').update(`${tool}\0${family}\0${target}`).digest('hex');
72
+ return createHash('sha256').update(`${tool}\0${family}\0${target}\0${workspace}`).digest('hex');
68
73
  }
69
74
 
70
75
  function lastGoodTool(outcomes: readonly ToolOutcome[]): string | null {
71
76
  for (let index = outcomes.length - 1; index >= 0; index--) {
72
77
  const outcome = outcomes[index];
73
- if (outcome?.success) return outcome.tool;
78
+ if (outcome?.success && (outcome.exitCode == null || outcome.exitCode === 0) && !outcome.error?.trim()) return outcome.tool;
74
79
  }
75
80
  return null;
76
81
  }
@@ -112,7 +117,9 @@ export class TimeMachine {
112
117
  observe(tool: string, args: Record<string, unknown>, result: unknown,
113
118
  outcomes: readonly ToolOutcome[] = []): RecoveryDecision {
114
119
  const value = record(result);
115
- const failed = value.success === false || typeof value.error === 'string';
120
+ const failed = value.success === false || (typeof value.error === 'string' && value.error.trim().length > 0)
121
+ || (typeof value.exitCode === 'number' && (!Number.isFinite(value.exitCode) || value.exitCode !== 0))
122
+ || value.failureKind === 'site_refusal';
116
123
  const classification = failed ? failureClass(value) || 'failed' : '';
117
124
  const key = issueKey(tool, args);
118
125
  const good = lastGoodTool(outcomes);
@@ -140,7 +147,7 @@ export class TimeMachine {
140
147
 
141
148
  const error = typeof value.error === 'string' ? value.error : '';
142
149
  const needsHuman = classification === 'permission' || /user denied|approval required|authentication required/i.test(error);
143
- const attempt = (this.failures.get(key) || 0) + 1;
150
+ const attempt = Math.min(TIME_MACHINE_MAX_ATTEMPTS, (this.failures.get(key) || 0) + 1);
144
151
  this.failures.set(key, attempt);
145
152
  const checkpoint = good ? ` Last successful tool: ${good}.` : '';
146
153
 
@@ -167,6 +174,11 @@ export class TimeMachine {
167
174
  failureClass: classification, lastGoodTool: good,
168
175
  guidance: `Further attempts were not approved. Stop this task. Give a brief evidence-based report and state what remains unresolved.${checkpoint}` };
169
176
  }
177
+ if (classification === 'rate_limited' && attempt < TIME_MACHINE_CONSENT_AT) {
178
+ return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
179
+ failureClass: classification, lastGoodTool: good,
180
+ guidance: `Rate limit reached. Respect the provider's retry/reset window; do not immediately resend the same request.${checkpoint}` };
181
+ }
170
182
  if (value.failureKind === 'site_refusal' && attempt < TIME_MACHINE_MAX_ATTEMPTS) {
171
183
  return { kind: 'replan', attempt, maxAttempts: TIME_MACHINE_MAX_ATTEMPTS, issueKey: key,
172
184
  failureClass: classification, lastGoodTool: good,
@@ -1,7 +1,46 @@
1
- import { exec } from 'child_process';
2
- import os from 'os';
1
+ import { execFile } from 'node:child_process';
2
+ import os from 'node:os';
3
3
  import { currentToolAutonomyMode } from '../approvalPolicy.js';
4
4
 
5
+ /**
6
+ * Parse the documented Git subcommand syntax without invoking a shell.
7
+ * Quoted commit messages and filenames are preserved as single arguments.
8
+ */
9
+ export function parseGitArguments(raw) {
10
+ if (typeof raw !== 'string' || !raw.trim()) throw new Error('A Git subcommand is required.');
11
+ const argv = [];
12
+ let token = '';
13
+ let quote = null;
14
+ let started = false;
15
+ for (let i = 0; i < raw.length; i++) {
16
+ const char = raw.charAt(i);
17
+ const next = raw.charAt(i + 1);
18
+ if (char === '\\' && quote !== "'" && next && /[\\\s"'\\]/.test(next)) {
19
+ token += next;
20
+ started = true;
21
+ i++;
22
+ continue;
23
+ }
24
+ if (char === '"' || char === "'") {
25
+ if (!quote) { quote = char; started = true; continue; }
26
+ if (quote === char) { quote = null; continue; }
27
+ }
28
+ if (!quote && /[;&|><`$()\r\n]/.test(char)) {
29
+ throw new Error('Git commands must contain one subcommand, without shell operators or substitution.');
30
+ }
31
+ if (!quote && /\s/.test(char)) {
32
+ if (started) { argv.push(token); token = ''; started = false; }
33
+ continue;
34
+ }
35
+ token += char;
36
+ started = true;
37
+ }
38
+ if (quote) throw new Error('Unterminated quote in Git command.');
39
+ if (started) argv.push(token);
40
+ if (!argv.length) throw new Error('A Git subcommand is required.');
41
+ return argv;
42
+ }
43
+
5
44
  export const gitExec = {
6
45
  schema: {
7
46
  name: 'gitOp',
@@ -16,39 +55,40 @@ export const gitExec = {
16
55
  }
17
56
  },
18
57
  async execute(args) {
19
- const cwd = (args.cwd || process.cwd()).replace(/^~\//, os.homedir() + '/');
20
- let cmdString = args.command;
21
-
22
- // Phase 5 AGI Upgrade: Boundary Conditions
23
- if (cmdString.includes('-i') || cmdString.includes('interactive')) {
24
- return { success: false, error: 'Interactive workflows (e.g., rebase -i) are strictly forbidden in AGI automation. Use precise non-interactive commands.' };
25
- }
26
-
27
- if ((cmdString.includes('push -f') || cmdString.includes('push --force') || cmdString.includes('branch -D'))
28
- && currentToolAutonomyMode() === undefined) {
58
+ const cwd = String(args?.cwd || process.cwd()).replace(/^~\//, os.homedir() + '/');
59
+ let argv;
60
+ try {
61
+ argv = parseGitArguments(args?.command);
62
+ } catch (error) {
63
+ return { success: false, error: error.message };
64
+ }
65
+
66
+ const subcommand = argv[0];
67
+ if (subcommand === 'rebase' && argv.some(arg => arg === '-i' || arg === '--interactive')) {
68
+ return { success: false, error: 'Interactive Git rebase is not supported. Use precise non-interactive commands.' };
69
+ }
70
+ const forcingPush = subcommand === 'push' && argv.slice(1).some(arg => arg === '-f' || arg === '--force' || arg.startsWith('--force-with-lease'));
71
+ const forcingBranch = subcommand === 'branch' && argv.includes('-D');
72
+ if ((forcingPush || forcingBranch) && currentToolAutonomyMode() === undefined) {
29
73
  return { success: false, error: 'Destructive Git action requires the agent session approval and sandbox policy.' };
30
74
  }
31
75
 
32
- const command = `git ${cmdString}`;
33
-
34
- return new Promise((resolve) => {
35
- exec(command, { cwd, maxBuffer: 5 * 1024 * 1024 }, (error, stdout, stderr) => {
76
+ return new Promise(resolve => {
77
+ // Never use a shell here: gitOp is a structured tool, not an arbitrary shell.
78
+ execFile('git', argv, { cwd, maxBuffer: 5 * 1024 * 1024 }, (error, stdout, stderr) => {
36
79
  const fullOutput = (stdout || '') + '\n' + (stderr || '');
37
-
38
- // Phase 5 AGI Upgrade: Autonomous Conflict Detection
39
80
  if (fullOutput.includes('CONFLICT (content): Merge conflict')) {
40
- resolve({
41
- success: false,
42
- error: `[AUTONOMOUS CONFLICT DETECTED]\nGit merge conflict occurred. DO NOT PANIC.\n1. Use fs.read to read the conflicted files.\n2. Analyze the <<<<<<< HEAD markers.\n3. Use fs.edit to surgically resolve the conflict.\n4. Run git add and git commit.`,
43
- output: fullOutput
81
+ resolve({
82
+ success: false,
83
+ error: '[AUTONOMOUS CONFLICT DETECTED] Git merge conflict occurred. Inspect conflicted files, resolve exact markers and verify before continuing.',
84
+ output: fullOutput
44
85
  });
45
86
  return;
46
87
  }
47
-
48
88
  if (error) {
49
89
  resolve({ success: false, output: stdout, error: stderr || error.message, exitCode: error.code });
50
90
  } else {
51
- resolve({ success: true, output: stdout || stderr, exitCode: 0 });
91
+ resolve({ success: true, output: stdout || stderr, exitCode: 0 });
52
92
  }
53
93
  });
54
94
  });
@@ -84,14 +84,18 @@ function renderMarkdown(text, width) {
84
84
  continue;
85
85
  }
86
86
  if (inFence) {
87
- lines.push(paint('accent', ' ' + truncate(line, width - 2, '')));
87
+ for (const codeRow of wrapBlock(' ' + line, Math.max(8, width), { hang: 0 })) {
88
+ lines.push(paint('accent', codeRow));
89
+ }
88
90
  continue;
89
91
  }
90
92
 
91
93
  const heading = line.match(/^(#{1,6})\s+(.*)$/);
92
94
  if (heading) {
93
95
  lines.push('');
94
- lines.push(bold(paint('ink', heading[2])));
96
+ for (const headingRow of wrap(heading[2], Math.max(8, width))) {
97
+ lines.push(bold(paint('ink', headingRow)));
98
+ }
95
99
  continue;
96
100
  }
97
101
 
@@ -138,8 +142,10 @@ function renderMarkdown(text, width) {
138
142
 
139
143
  const tableRow = line.match(/^\s*\|(.+)\|\s*$/);
140
144
  if (tableRow) {
141
- const cells = tableRow[1].split('|').map(c => inline(c.trim()));
142
- lines.push(' ' + cells.join(paint('muted', ' │ ')));
145
+ const cells = tableRow[1].split('|').map(c => c.trim());
146
+ for (const tableLine of wrapBlock(' ' + cells.join(' │ '), Math.max(8, width), { hang: 0 })) {
147
+ lines.push(inline(tableLine));
148
+ }
143
149
  continue;
144
150
  }
145
151
 
@@ -824,9 +830,11 @@ export class ChatRenderer {
824
830
 
825
831
  formatAssistantMessage(content, { streaming = false } = {}) {
826
832
  const width = this.measure();
827
- this.write();
833
+ // The frame already ends with a blank separator. A leading blank row on the
834
+ // first assistant response leaves a visible void in compact chat view.
828
835
  this.write(`${paint('agent', GLYPHS.arrow)} ${bold(paint('agent', 'Causyne'))}${streaming ? ' ' + dim('…') : ''}`);
829
- for (const line of renderMarkdown(content, width - 2)) {
836
+ // Reserve the transcript's three-column inset and final safety cell.
837
+ for (const line of renderMarkdown(content, Math.max(8, width - 4))) {
830
838
  this.write(line ? ' ' + line : '');
831
839
  }
832
840
  this.write();
@@ -3,30 +3,32 @@ import { padEnd, safeDisplay, truncate } from './text.js';
3
3
  // @ts-expect-error theme.js has no TypeScript declaration yet.
4
4
  import { bold, dim, fill, paint } from './theme.js';
5
5
  export const SIDEBAR_WIDTH = 42;
6
- export const SIDEBAR_THRESHOLD = 120;
6
+ // A 42-column sidebar is only useful if the conversation retains a readable width.
7
+ // Narrow IDE terminals should prioritize the user's complete message over metadata.
8
+ export const SIDEBAR_THRESHOLD = 160;
7
9
  /** A side panel is useful only when a readable conversation column remains. */
8
- export function sidebarVisible(columns, home = false) {
9
- if (typeof process !== 'undefined' && process.env) {
10
- const setting = String(process.env.CAUSYNE_SIDEBAR ?? '').trim().toLowerCase();
10
+ export function sidebarVisible(columns, home = false, env = typeof process !== 'undefined' ? process.env : {}) {
11
+ if (env) {
12
+ const setting = String(env.CAUSYNE_SIDEBAR ?? '').trim().toLowerCase();
11
13
  if (setting === 'off' || setting === '0' || setting === 'false')
12
14
  return false;
13
15
  }
14
16
  return !home && Number.isFinite(columns) && columns > SIDEBAR_THRESHOLD;
15
17
  }
16
18
  /** Reserve the last terminal column so a wide row cannot wrap the stage. */
17
- export function sessionMainWidth(columns, home = false) {
19
+ export function sessionMainWidth(columns, home = false, env = typeof process !== 'undefined' ? process.env : {}) {
18
20
  const width = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
19
- return sidebarVisible(width, home) ? width - SIDEBAR_WIDTH - 1 : width;
21
+ return sidebarVisible(width, home, env) ? width - SIDEBAR_WIDTH - 1 : width;
20
22
  }
21
23
  /** The session input uses the available conversation column, with a small inset. */
22
24
  export function sessionComposerWidth(columns) {
23
25
  const available = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
24
26
  if (available <= 112) {
25
- return Math.max(20, available - 3);
27
+ return Math.max(20, available - 4);
26
28
  }
27
29
  // Dynamic readable measure scaling on wide terminals:
28
30
  const readableMeasure = Math.round(109 + 20 * Math.log2(available / 112));
29
- return Math.min(available - 3, Math.max(20, readableMeasure));
31
+ return Math.min(available - 4, Math.max(20, readableMeasure));
30
32
  }
31
33
  /** Render only facts the runtime can actually report. */
32
34
  export function sessionSidebarRows(facts, height) {
@@ -57,7 +59,13 @@ export function sessionSidebarRows(facts, height) {
57
59
  }
58
60
  line();
59
61
  styled(bold('Model'));
60
- line([facts.provider, facts.model].filter(Boolean).join(' / ') || 'Not configured');
62
+ if (height >= 24 && facts.provider && facts.model) {
63
+ line(facts.provider);
64
+ line(facts.model);
65
+ }
66
+ else {
67
+ line([facts.provider, facts.model].filter(Boolean).join(' / ') || 'Not configured');
68
+ }
61
69
  line();
62
70
  styled(bold('Workspace'));
63
71
  line(facts.cwd || 'Unknown');
@@ -68,7 +76,7 @@ export function sessionSidebarRows(facts, height) {
68
76
  if (skillId) {
69
77
  line();
70
78
  styled(bold('Active Skill'));
71
- styled(paint('accent', `✦ ${truncate(skillId, inner - 4, '…')}`));
79
+ styled(paint('accent', `✦ ${truncate(safeDisplay(skillId), inner - 4, '…')}`));
72
80
  if (skillDesc) {
73
81
  line(truncate(skillDesc, inner, '…'));
74
82
  }
@@ -78,17 +86,22 @@ export function sessionSidebarRows(facts, height) {
78
86
  const completed = facts.plan.filter(item => item.status === 'completed').length;
79
87
  line();
80
88
  styled(bold(`Plan ${completed}/${facts.plan.length}`));
81
- const planItems = facts.plan.length <= 6 ? facts.plan : [
82
- ...facts.plan.filter(item => item.status === 'in_progress').slice(0, 2),
83
- ...facts.plan.filter(item => item.status !== 'in_progress' && item.status !== 'completed').slice(0, 3),
84
- ...facts.plan.filter(item => item.status === 'completed').slice(-2)
85
- ].slice(0, 6);
89
+ // Keep plan steps in execution order and keep the active step in view.
90
+ const maxSteps = Math.max(2, Math.min(10, Math.floor(height) - 14));
91
+ const activeIndex = facts.plan.findIndex(item => item.status === 'in_progress');
92
+ const pendingIndex = facts.plan.findIndex(item => item.status !== 'completed');
93
+ const focus = activeIndex >= 0 ? activeIndex : pendingIndex >= 0 ? pendingIndex : facts.plan.length - 1;
94
+ const start = Math.max(0, Math.min(focus - 2, facts.plan.length - maxSteps));
95
+ const planItems = facts.plan.slice(start, start + maxSteps);
96
+ if (start > 0)
97
+ line(`${start} earlier plan steps`);
86
98
  for (const item of planItems) {
87
99
  const mark = item.status === 'completed' ? '✓' : item.status === 'in_progress' ? '▸' : '·';
88
100
  line(`${mark} ${item.text || item.step || item.content || ''}`);
89
101
  }
90
- if (facts.plan.length > planItems.length)
91
- line(`${facts.plan.length - planItems.length} additional plan steps`);
102
+ const remaining = facts.plan.length - start - planItems.length;
103
+ if (remaining > 0)
104
+ line(`${remaining} later plan steps`);
92
105
  }
93
106
  const count = Number.isFinite(height) ? Math.max(1, Math.floor(height)) : 1;
94
107
  const visible = rows.slice(0, count);
@@ -4,7 +4,9 @@ import { padEnd, safeDisplay, truncate } from './text.js';
4
4
  import { bold, dim, fill, paint } from './theme.js';
5
5
 
6
6
  export const SIDEBAR_WIDTH = 42;
7
- export const SIDEBAR_THRESHOLD = 120;
7
+ // A 42-column sidebar is only useful if the conversation retains a readable width.
8
+ // Narrow IDE terminals should prioritize the user's complete message over metadata.
9
+ export const SIDEBAR_THRESHOLD = 160;
8
10
 
9
11
  export interface SidebarFacts {
10
12
  title?: string;
@@ -19,29 +21,29 @@ export interface SidebarFacts {
19
21
  }
20
22
 
21
23
  /** A side panel is useful only when a readable conversation column remains. */
22
- export function sidebarVisible(columns: number, home = false): boolean {
23
- if (typeof process !== 'undefined' && process.env) {
24
- const setting = String(process.env.CAUSYNE_SIDEBAR ?? '').trim().toLowerCase();
24
+ export function sidebarVisible(columns: number, home = false, env: { CAUSYNE_SIDEBAR?: string } = typeof process !== 'undefined' ? process.env : {}): boolean {
25
+ if (env) {
26
+ const setting = String(env.CAUSYNE_SIDEBAR ?? '').trim().toLowerCase();
25
27
  if (setting === 'off' || setting === '0' || setting === 'false') return false;
26
28
  }
27
29
  return !home && Number.isFinite(columns) && columns > SIDEBAR_THRESHOLD;
28
30
  }
29
31
 
30
32
  /** Reserve the last terminal column so a wide row cannot wrap the stage. */
31
- export function sessionMainWidth(columns: number, home = false): number {
33
+ export function sessionMainWidth(columns: number, home = false, env: { CAUSYNE_SIDEBAR?: string } = typeof process !== 'undefined' ? process.env : {}): number {
32
34
  const width = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
33
- return sidebarVisible(width, home) ? width - SIDEBAR_WIDTH - 1 : width;
35
+ return sidebarVisible(width, home, env) ? width - SIDEBAR_WIDTH - 1 : width;
34
36
  }
35
37
 
36
38
  /** The session input uses the available conversation column, with a small inset. */
37
39
  export function sessionComposerWidth(columns: number): number {
38
40
  const available = Number.isFinite(columns) ? Math.max(20, Math.floor(columns)) : 80;
39
41
  if (available <= 112) {
40
- return Math.max(20, available - 3);
42
+ return Math.max(20, available - 4);
41
43
  }
42
44
  // Dynamic readable measure scaling on wide terminals:
43
45
  const readableMeasure = Math.round(109 + 20 * Math.log2(available / 112));
44
- return Math.min(available - 3, Math.max(20, readableMeasure));
46
+ return Math.min(available - 4, Math.max(20, readableMeasure));
45
47
  }
46
48
 
47
49
  /** Render only facts the runtime can actually report. */
@@ -72,7 +74,12 @@ export function sessionSidebarRows(facts: SidebarFacts, height: number): string[
72
74
  }
73
75
  line();
74
76
  styled(bold('Model'));
75
- line([facts.provider, facts.model].filter(Boolean).join(' / ') || 'Not configured');
77
+ if (height >= 24 && facts.provider && facts.model) {
78
+ line(facts.provider);
79
+ line(facts.model);
80
+ } else {
81
+ line([facts.provider, facts.model].filter(Boolean).join(' / ') || 'Not configured');
82
+ }
76
83
  line();
77
84
  styled(bold('Workspace'));
78
85
  line(facts.cwd || 'Unknown');
@@ -84,7 +91,7 @@ export function sessionSidebarRows(facts: SidebarFacts, height: number): string[
84
91
  if (skillId) {
85
92
  line();
86
93
  styled(bold('Active Skill'));
87
- styled(paint('accent', `✦ ${truncate(skillId, inner - 4, '…')}`));
94
+ styled(paint('accent', `✦ ${truncate(safeDisplay(skillId), inner - 4, '…')}`));
88
95
  if (skillDesc) {
89
96
  line(truncate(skillDesc, inner, '…'));
90
97
  }
@@ -95,16 +102,20 @@ export function sessionSidebarRows(facts: SidebarFacts, height: number): string[
95
102
  const completed = facts.plan.filter(item => item.status === 'completed').length;
96
103
  line();
97
104
  styled(bold(`Plan ${completed}/${facts.plan.length}`));
98
- const planItems = facts.plan.length <= 6 ? facts.plan : [
99
- ...facts.plan.filter(item => item.status === 'in_progress').slice(0, 2),
100
- ...facts.plan.filter(item => item.status !== 'in_progress' && item.status !== 'completed').slice(0, 3),
101
- ...facts.plan.filter(item => item.status === 'completed').slice(-2)
102
- ].slice(0, 6);
105
+ // Keep plan steps in execution order and keep the active step in view.
106
+ const maxSteps = Math.max(2, Math.min(10, Math.floor(height) - 14));
107
+ const activeIndex = facts.plan.findIndex(item => item.status === 'in_progress');
108
+ const pendingIndex = facts.plan.findIndex(item => item.status !== 'completed');
109
+ const focus = activeIndex >= 0 ? activeIndex : pendingIndex >= 0 ? pendingIndex : facts.plan.length - 1;
110
+ const start = Math.max(0, Math.min(focus - 2, facts.plan.length - maxSteps));
111
+ const planItems = facts.plan.slice(start, start + maxSteps);
112
+ if (start > 0) line(`${start} earlier plan steps`);
103
113
  for (const item of planItems) {
104
114
  const mark = item.status === 'completed' ? '✓' : item.status === 'in_progress' ? '▸' : '·';
105
115
  line(`${mark} ${item.text || item.step || item.content || ''}`);
106
116
  }
107
- if (facts.plan.length > planItems.length) line(`${facts.plan.length - planItems.length} additional plan steps`);
117
+ const remaining = facts.plan.length - start - planItems.length;
118
+ if (remaining > 0) line(`${remaining} later plan steps`);
108
119
  }
109
120
 
110
121
  const count = Number.isFinite(height) ? Math.max(1, Math.floor(height)) : 1;