@causyne/agent 1.20.100 → 1.20.103

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.
@@ -1,107 +1,119 @@
1
- import fs from 'fs/promises';
2
- import os from 'os';
3
-
4
- // Phase 3 AGI Upgrade: Fast Levenshtein Distance for Fuzzy Matching
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { atomicWriteFileSync } from '../infra/atomicWriter.js';
5
5
  function getLevenshteinDistance(a, b) {
6
- const matrix = Array(a.length + 1).fill(null).map(() => Array(b.length + 1).fill(null));
7
-
8
- for (let i = 0; i <= a.length; i++) matrix[i][0] = i;
9
- for (let j = 0; j <= b.length; j++) matrix[0][j] = j;
10
-
11
- for (let i = 1; i <= a.length; i++) {
12
- for (let j = 1; j <= b.length; j++) {
13
- const indicator = a[i - 1] === b[j - 1] ? 0 : 1;
14
- matrix[i][j] = Math.min(
15
- matrix[i - 1][j] + 1, // deletion
16
- matrix[i][j - 1] + 1, // insertion
17
- matrix[i - 1][j - 1] + indicator // substitution
18
- );
6
+ const matrix = Array(a.length + 1)
7
+ .fill(null)
8
+ .map(() => Array(b.length + 1).fill(0));
9
+ for (let i = 0; i <= a.length; i++)
10
+ matrix[i][0] = i;
11
+ for (let j = 0; j <= b.length; j++)
12
+ matrix[0][j] = j;
13
+ for (let i = 1; i <= a.length; i++) {
14
+ for (let j = 1; j <= b.length; j++) {
15
+ const indicator = a[i - 1] === b[j - 1] ? 0 : 1;
16
+ matrix[i][j] = Math.min(matrix[i - 1][j] + 1, // deletion
17
+ matrix[i][j - 1] + 1, // insertion
18
+ matrix[i - 1][j - 1] + indicator // substitution
19
+ );
20
+ }
19
21
  }
20
- }
21
- return matrix[a.length][b.length];
22
+ return matrix[a.length][b.length];
22
23
  }
23
-
24
24
  function calculateConfidence(original, match) {
25
- const dist = getLevenshteinDistance(original, match);
26
- const maxLen = Math.max(original.length, match.length);
27
- if (maxLen === 0) return 100;
28
- return ((maxLen - dist) / maxLen) * 100;
25
+ const dist = getLevenshteinDistance(original, match);
26
+ const maxLen = Math.max(original.length, match.length);
27
+ if (maxLen === 0)
28
+ return 100;
29
+ return ((maxLen - dist) / maxLen) * 100;
29
30
  }
30
-
31
31
  export const multiEdit = {
32
- schema: {
33
- name: 'MultiEdit',
34
- description: 'Make multiple edits to a single file atomically. Replaces old_string with new_string. If exact match fails, uses fuzzy matching (requires 90% confidence). Includes atomic rollback.',
35
- parameters: {
36
- type: 'object',
37
- properties: {
38
- file_path: { type: 'string' },
39
- edits: {
40
- type: 'array',
41
- items: {
32
+ schema: {
33
+ name: 'MultiEdit',
34
+ description: 'Make multiple edits to a single file atomically. Replaces old_string with new_string. If exact match fails, uses fuzzy matching (requires 90% confidence). Includes atomic rollback.',
35
+ parameters: {
42
36
  type: 'object',
43
37
  properties: {
44
- old_string: { type: 'string' },
45
- new_string: { type: 'string' }
38
+ file_path: { type: 'string' },
39
+ edits: {
40
+ type: 'array',
41
+ items: {
42
+ type: 'object',
43
+ properties: {
44
+ old_string: { type: 'string' },
45
+ new_string: { type: 'string' }
46
+ },
47
+ required: ['old_string', 'new_string']
48
+ },
49
+ minItems: 1
50
+ }
46
51
  },
47
- required: ['old_string', 'new_string']
48
- },
49
- minItems: 1
50
- }
51
- },
52
- required: ['file_path', 'edits']
53
- }
54
- },
55
- async execute(args) {
56
- try {
57
- const target = args.file_path.replace(/^~\//, os.homedir() + '/');
58
- let originalContent = await fs.readFile(target, 'utf8');
59
- let workingContent = originalContent; // Phase 3 AGI Upgrade: Atomic Rollback prep
60
-
61
- let replacements = 0;
62
- for (let i = 0; i < args.edits.length; i++) {
63
- const edit = args.edits[i];
64
-
65
- // Try exact match first
66
- if (workingContent.includes(edit.old_string)) {
67
- workingContent = workingContent.replace(edit.old_string, edit.new_string);
68
- replacements++;
69
- continue;
52
+ required: ['file_path', 'edits']
70
53
  }
71
-
72
- // Phase 3 AGI Upgrade: Fuzzy Match Fallback
73
- // Find the best sliding window match (simplified for performance: split by line, scan chunks)
74
- const lines = workingContent.split('\n');
75
- const oldLines = edit.old_string.split('\n');
76
- let bestMatch = null;
77
- let highestConfidence = 0;
78
-
79
- for (let j = 0; j <= lines.length - oldLines.length; j++) {
80
- const chunk = lines.slice(j, j + oldLines.length).join('\n');
81
- const conf = calculateConfidence(edit.old_string, chunk);
82
- if (conf > highestConfidence) {
83
- highestConfidence = conf;
84
- bestMatch = chunk;
85
- }
54
+ },
55
+ async execute(args) {
56
+ try {
57
+ if (!args || typeof args !== 'object') {
58
+ return { success: false, error: 'MultiEdit requires an object with file_path and edits array.' };
59
+ }
60
+ if (typeof args.file_path !== 'string' || !args.file_path.trim()) {
61
+ return { success: false, error: 'MultiEdit requires a non-empty string file_path.' };
62
+ }
63
+ if (!Array.isArray(args.edits) || args.edits.length === 0) {
64
+ return { success: false, error: 'MultiEdit requires a non-empty edits array.' };
65
+ }
66
+ const rawPath = args.file_path.trim();
67
+ const target = rawPath.startsWith('~/') || rawPath.startsWith('~\\')
68
+ ? path.join(os.homedir(), rawPath.slice(2))
69
+ : path.resolve(rawPath);
70
+ const originalContent = await fs.readFile(target, 'utf8');
71
+ let workingContent = originalContent;
72
+ let replacements = 0;
73
+ for (let i = 0; i < args.edits.length; i++) {
74
+ const edit = args.edits[i];
75
+ if (!edit || typeof edit.old_string !== 'string' || typeof edit.new_string !== 'string') {
76
+ return {
77
+ success: false,
78
+ error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid old_string or new_string. Rollback complete.`
79
+ };
80
+ }
81
+ // Try exact match first
82
+ if (workingContent.includes(edit.old_string)) {
83
+ workingContent = workingContent.replace(edit.old_string, edit.new_string);
84
+ replacements++;
85
+ continue;
86
+ }
87
+ // Fuzzy Match Fallback
88
+ const lines = workingContent.split('\n');
89
+ const oldLines = edit.old_string.split('\n');
90
+ let bestMatch = null;
91
+ let highestConfidence = 0;
92
+ for (let j = 0; j <= lines.length - oldLines.length; j++) {
93
+ const chunk = lines.slice(j, j + oldLines.length).join('\n');
94
+ const conf = calculateConfidence(edit.old_string, chunk);
95
+ if (conf > highestConfidence) {
96
+ highestConfidence = conf;
97
+ bestMatch = chunk;
98
+ }
99
+ }
100
+ if (highestConfidence >= 90 && bestMatch) {
101
+ workingContent = workingContent.replace(bestMatch, edit.new_string);
102
+ replacements++;
103
+ }
104
+ else {
105
+ return {
106
+ success: false,
107
+ error: `ATOMIC ROLLBACK: Edit index ${i} failed. Exact match not found, and fuzzy match confidence was too low (${highestConfidence.toFixed(2)}% < 90%). Previous edits in this batch were rolled back.`
108
+ };
109
+ }
110
+ }
111
+ // Commit the transaction atomically
112
+ atomicWriteFileSync(target, workingContent, { encoding: 'utf8' });
113
+ return { success: true, output: `Transaction Success: ${replacements} atomic edits applied to ${args.file_path}` };
86
114
  }
87
-
88
- if (highestConfidence >= 90 && bestMatch) {
89
- workingContent = workingContent.replace(bestMatch, edit.new_string);
90
- replacements++;
91
- } else {
92
- // Atomic Rollback
93
- return {
94
- success: false,
95
- error: `ATOMIC ROLLBACK: Edit index ${i} failed. Exact match not found, and fuzzy match confidence was too low (${highestConfidence.toFixed(2)}% < 90%). Previous edits in this batch were rolled back.`
96
- };
115
+ catch (e) {
116
+ return { success: false, error: e instanceof Error ? e.message : String(e) };
97
117
  }
98
- }
99
-
100
- // Commit the transaction
101
- await fs.writeFile(target, workingContent, 'utf8');
102
- return { success: true, output: `Transaction Success: ${replacements} atomic edits applied to ${args.file_path}` };
103
- } catch (e) {
104
- return { success: false, error: e.message };
105
118
  }
106
- }
107
119
  };
@@ -0,0 +1,145 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { atomicWriteFileSync } from '../infra/atomicWriter.js';
5
+
6
+ export interface MultiEditItem {
7
+ old_string: string;
8
+ new_string: string;
9
+ }
10
+
11
+ export interface MultiEditArgs {
12
+ file_path: string;
13
+ edits: MultiEditItem[];
14
+ }
15
+
16
+ export interface MultiEditResult {
17
+ success: boolean;
18
+ output?: string;
19
+ error?: string;
20
+ }
21
+
22
+ function getLevenshteinDistance(a: string, b: string): number {
23
+ const matrix: number[][] = Array(a.length + 1)
24
+ .fill(null)
25
+ .map(() => Array(b.length + 1).fill(0));
26
+
27
+ for (let i = 0; i <= a.length; i++) matrix[i]![0] = i;
28
+ for (let j = 0; j <= b.length; j++) matrix[0]![j] = j;
29
+
30
+ for (let i = 1; i <= a.length; i++) {
31
+ for (let j = 1; j <= b.length; j++) {
32
+ const indicator = a[i - 1] === b[j - 1] ? 0 : 1;
33
+ matrix[i]![j] = Math.min(
34
+ matrix[i - 1]![j]! + 1, // deletion
35
+ matrix[i]![j - 1]! + 1, // insertion
36
+ matrix[i - 1]![j - 1]! + indicator // substitution
37
+ );
38
+ }
39
+ }
40
+ return matrix[a.length]![b.length]!;
41
+ }
42
+
43
+ function calculateConfidence(original: string, match: string): number {
44
+ const dist = getLevenshteinDistance(original, match);
45
+ const maxLen = Math.max(original.length, match.length);
46
+ if (maxLen === 0) return 100;
47
+ return ((maxLen - dist) / maxLen) * 100;
48
+ }
49
+
50
+ export const multiEdit = {
51
+ schema: {
52
+ name: 'MultiEdit',
53
+ description: 'Make multiple edits to a single file atomically. Replaces old_string with new_string. If exact match fails, uses fuzzy matching (requires 90% confidence). Includes atomic rollback.',
54
+ parameters: {
55
+ type: 'object',
56
+ properties: {
57
+ file_path: { type: 'string' },
58
+ edits: {
59
+ type: 'array',
60
+ items: {
61
+ type: 'object',
62
+ properties: {
63
+ old_string: { type: 'string' },
64
+ new_string: { type: 'string' }
65
+ },
66
+ required: ['old_string', 'new_string']
67
+ },
68
+ minItems: 1
69
+ }
70
+ },
71
+ required: ['file_path', 'edits']
72
+ }
73
+ },
74
+
75
+ async execute(args: MultiEditArgs): Promise<MultiEditResult> {
76
+ try {
77
+ if (!args || typeof args !== 'object') {
78
+ return { success: false, error: 'MultiEdit requires an object with file_path and edits array.' };
79
+ }
80
+ if (typeof args.file_path !== 'string' || !args.file_path.trim()) {
81
+ return { success: false, error: 'MultiEdit requires a non-empty string file_path.' };
82
+ }
83
+ if (!Array.isArray(args.edits) || args.edits.length === 0) {
84
+ return { success: false, error: 'MultiEdit requires a non-empty edits array.' };
85
+ }
86
+
87
+ const rawPath = args.file_path.trim();
88
+ const target = rawPath.startsWith('~/') || rawPath.startsWith('~\\')
89
+ ? path.join(os.homedir(), rawPath.slice(2))
90
+ : path.resolve(rawPath);
91
+
92
+ const originalContent = await fs.readFile(target, 'utf8');
93
+ let workingContent = originalContent;
94
+ let replacements = 0;
95
+
96
+ for (let i = 0; i < args.edits.length; i++) {
97
+ const edit = args.edits[i];
98
+ if (!edit || typeof edit.old_string !== 'string' || typeof edit.new_string !== 'string') {
99
+ return {
100
+ success: false,
101
+ error: `ATOMIC ROLLBACK: Edit index ${i} is missing valid old_string or new_string. Rollback complete.`
102
+ };
103
+ }
104
+
105
+ // Try exact match first
106
+ if (workingContent.includes(edit.old_string)) {
107
+ workingContent = workingContent.replace(edit.old_string, edit.new_string);
108
+ replacements++;
109
+ continue;
110
+ }
111
+
112
+ // Fuzzy Match Fallback
113
+ const lines = workingContent.split('\n');
114
+ const oldLines = edit.old_string.split('\n');
115
+ let bestMatch: string | null = null;
116
+ let highestConfidence = 0;
117
+
118
+ for (let j = 0; j <= lines.length - oldLines.length; j++) {
119
+ const chunk = lines.slice(j, j + oldLines.length).join('\n');
120
+ const conf = calculateConfidence(edit.old_string, chunk);
121
+ if (conf > highestConfidence) {
122
+ highestConfidence = conf;
123
+ bestMatch = chunk;
124
+ }
125
+ }
126
+
127
+ if (highestConfidence >= 90 && bestMatch) {
128
+ workingContent = workingContent.replace(bestMatch, edit.new_string);
129
+ replacements++;
130
+ } else {
131
+ return {
132
+ success: false,
133
+ error: `ATOMIC ROLLBACK: Edit index ${i} failed. Exact match not found, and fuzzy match confidence was too low (${highestConfidence.toFixed(2)}% < 90%). Previous edits in this batch were rolled back.`
134
+ };
135
+ }
136
+ }
137
+
138
+ // Commit the transaction atomically
139
+ atomicWriteFileSync(target, workingContent, { encoding: 'utf8' });
140
+ return { success: true, output: `Transaction Success: ${replacements} atomic edits applied to ${args.file_path}` };
141
+ } catch (e: unknown) {
142
+ return { success: false, error: e instanceof Error ? e.message : String(e) };
143
+ }
144
+ }
145
+ };
@@ -1,13 +1,9 @@
1
- import { setStageConsoleGuardActive } from './consoleGuard.js';
2
1
  /**
3
2
  * Terminal-wide motion reports (?1003h) allow hover feedback, but hijack native mouse selection.
4
3
  * Disabled by default so users can freely select, drag, and copy text in the terminal.
5
4
  * Opt-in via CAUSYNE_MOUSE_HOVER=1.
6
5
  */
7
6
  export function mouseHoverTracking(enabled, env = process.env) {
8
- if (env === process.env) {
9
- setStageConsoleGuardActive(enabled);
10
- }
11
7
  if (String(env.CAUSYNE_MOUSE_HOVER ?? '0') !== '1')
12
8
  return '';
13
9
  return enabled ? '\x1b[?1003h' : '\x1b[?1003l';
@@ -1,4 +1,3 @@
1
- import { setStageConsoleGuardActive } from './consoleGuard.js';
2
1
 
3
2
  /**
4
3
  * Terminal-wide motion reports (?1003h) allow hover feedback, but hijack native mouse selection.
@@ -6,9 +5,6 @@ import { setStageConsoleGuardActive } from './consoleGuard.js';
6
5
  * Opt-in via CAUSYNE_MOUSE_HOVER=1.
7
6
  */
8
7
  export function mouseHoverTracking(enabled: boolean, env: NodeJS.ProcessEnv = process.env): string {
9
- if (env === process.env) {
10
- setStageConsoleGuardActive(enabled);
11
- }
12
8
  if (String(env.CAUSYNE_MOUSE_HOVER ?? '0') !== '1') return '';
13
9
  return enabled ? '\x1b[?1003h' : '\x1b[?1003l';
14
10
  }
package/src/tui/prompt.js CHANGED
@@ -131,6 +131,7 @@ export class ChatPrompt {
131
131
 
132
132
  this.busy = false;
133
133
  this.active = false;
134
+ this.exitHook = null;
134
135
  this.drawnRows = 0;
135
136
  this.usageCard = null;
136
137
 
@@ -194,6 +195,13 @@ export class ChatPrompt {
194
195
  this.input.resume();
195
196
  this.input.on('data', this.handleData);
196
197
  this.out.write(bracketedPaste(true));
198
+ // Node's normal exit does not guarantee ChatPrompt.stop() is called.
199
+ // Always restore bracketed paste and raw stdin when the process exits.
200
+ this.exitHook = () => {
201
+ try { this.out.write(bracketedPaste(false)); } catch { /* terminal already closed */ }
202
+ try { this.input.setRawMode(false); } catch { /* stdin already closed */ }
203
+ };
204
+ process.once('exit', this.exitHook);
197
205
  // Rows are laid out against the terminal width; without this they stay stale
198
206
  // until the next keystroke, and a narrowed terminal wraps rows that erase()
199
207
  // is still counting as one.
@@ -219,6 +227,10 @@ export class ChatPrompt {
219
227
  this.input.off('data', this.handleData);
220
228
  try { this.input.setRawMode(false); } catch (e) { /* already closed */ }
221
229
  this.input.pause();
230
+ if (this.exitHook) {
231
+ process.removeListener('exit', this.exitHook);
232
+ this.exitHook = null;
233
+ }
222
234
  }
223
235
 
224
236
  /**
@@ -265,7 +265,7 @@ export class StageSurface {
265
265
  }
266
266
 
267
267
  enableMouse() {
268
- if (!this.mouseWanted || this.mouseOn) return false;
268
+ if (!this.mouseWanted || this.mouseOn || !this.stage.reserved) return false;
269
269
  this.out.write(mouseTracking(true));
270
270
  this.out.write(mouseHoverTracking(true, this.env));
271
271
  this.mouseCaptured = true;
@@ -273,12 +273,14 @@ export class StageSurface {
273
273
  return true;
274
274
  }
275
275
 
276
- disableMouse() {
277
- if (!this.mouseOn) return false;
278
- this.out.write(mouseHoverTracking(false, this.env));
276
+ disableMouse(force = false) {
277
+ if (!force && !this.mouseOn && !this.mouseCaptured) return false;
278
+ // Restore terminal motion modes, including stale tracking from an interrupted turn.
279
+ this.out.write(mouseHoverTracking(false, { ...this.env, CAUSYNE_MOUSE_HOVER: '1' }));
279
280
  this.out.write(mouseTracking(false));
280
281
  this.mouseCaptured = false;
281
282
  this.mouseOn = false;
283
+ this.detached = false;
282
284
  return true;
283
285
  }
284
286
 
@@ -310,9 +312,8 @@ export class StageSurface {
310
312
  }
311
313
 
312
314
  close() {
313
- // Mouse first, unconditionally: it is the one piece of state that outlives
314
- // the process and damages the terminal the user goes back to.
315
- this.disableMouse();
315
+ // Force the terminal to release tracking, even if internal flags were stale.
316
+ this.disableMouse(true);
316
317
  if (this.unregisterConsoleGuard) {
317
318
  this.unregisterConsoleGuard();
318
319
  this.unregisterConsoleGuard = null;
@@ -766,7 +767,8 @@ export class StageSurface {
766
767
 
767
768
  /** Take it back, once the user is driving the band again. */
768
769
  captureMouse() {
769
- if (this.mouseCaptured) return false;
770
+ // Home and suspended stages must not arm modes their teardown cannot observe.
771
+ if (!this.mouseWanted || !this.mouseOn || !this.stage.reserved || this.mouseCaptured) return false;
770
772
  this.out.write(mouseTracking(true));
771
773
  this.out.write(mouseHoverTracking(true, this.env));
772
774
  this.mouseCaptured = true;
@@ -789,11 +791,8 @@ export function createStageSurface({ out = process.stdout, env = process.env, co
789
791
  if (env.CAUSYNE_SIMPLE_INPUT === '1') return null;
790
792
  if (stageHeight(out, env) < 1) return null;
791
793
 
792
- const effectiveEnv = env.CAUSYNE_MOUSE_HOVER === undefined
793
- ? { ...env, CAUSYNE_MOUSE_HOVER: '1' }
794
- : env;
795
-
796
- const surface = new StageSurface({ out, env: effectiveEnv, config, speed, openingWidth });
794
+ // Terminal-wide motion tracking is opt-in, never silently enabled by the TUI.
795
+ const surface = new StageSurface({ out, env, config, speed, openingWidth });
797
796
  if (!surface.open()) return null;
798
797
  return surface;
799
798
  }
package/src/userSkills.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { causyneHome } from './utils/paths.js';
4
- import { assertSkillFileSafe, assertSkillTreeSafe, writeSkillFileSafely } from './skills/skillResourceSafety.js';
4
+ import { assertSkillFileSafe, assertSkillTreeSafe, writeSkillFileSafely, isPathWithin } from './skills/skillResourceSafety.js';
5
5
  // Bounds. Every one of these protects the context window, which is the resource
6
6
  // a skill library actually spends.
7
7
  export const MAX_USER_SKILLS = 200;
@@ -224,7 +224,7 @@ export function writeUserSkill({ domain, name, content, overwrite = false }, roo
224
224
  // segment has been joined. Validation above already makes this unreachable.
225
225
  const resolvedRoot = path.resolve(root);
226
226
  const resolvedFile = path.resolve(file);
227
- if (resolvedFile !== resolvedRoot && !resolvedFile.startsWith(resolvedRoot + path.sep)) {
227
+ if (!isPathWithin(resolvedFile, resolvedRoot)) {
228
228
  return { ok: false, error: 'refusing to write outside the skills directory' };
229
229
  }
230
230
  if (!overwrite && fs.existsSync(file)) {
package/src/userSkills.ts CHANGED
@@ -4,7 +4,8 @@ import { causyneHome } from './utils/paths.js';
4
4
  import {
5
5
  assertSkillFileSafe,
6
6
  assertSkillTreeSafe,
7
- writeSkillFileSafely
7
+ writeSkillFileSafely,
8
+ isPathWithin
8
9
  } from './skills/skillResourceSafety.js';
9
10
 
10
11
  export interface UserSkill {
@@ -256,7 +257,7 @@ export function writeUserSkill(
256
257
  // segment has been joined. Validation above already makes this unreachable.
257
258
  const resolvedRoot = path.resolve(root);
258
259
  const resolvedFile = path.resolve(file);
259
- if (resolvedFile !== resolvedRoot && !resolvedFile.startsWith(resolvedRoot + path.sep)) {
260
+ if (!isPathWithin(resolvedFile, resolvedRoot)) {
260
261
  return { ok: false, error: 'refusing to write outside the skills directory' };
261
262
  }
262
263
 
@@ -1,7 +0,0 @@
1
- export function detectWorkspaceDomains(...args: any[]): any;
2
- export function ensureSkillRepo(...args: any[]): any;
3
- export function getSkillDomainHeader(...args: any[]): any;
4
- export function listCompiledSkills(): Array<{ id: string; name: string; domain: string; description?: string; source?: string }>;
5
- export function readCompiledSkill(domain: string, skillId: string): string;
6
- export function invalidateUserSkills(): void;
7
- export function userSkillProblems(): string[];