@causyne/agent 1.20.78 → 1.20.79

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,6 +1,7 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
4
5
 
5
6
  export interface FsWriteArgs {
6
7
  path: string;
@@ -8,16 +9,81 @@ export interface FsWriteArgs {
8
9
  createDirectories?: boolean;
9
10
  }
10
11
 
12
+ export interface FsWriteContext {
13
+ workspaceRoot?: string;
14
+ workspacePaths?: string[];
15
+ grantAllAccess?: boolean;
16
+ parentLoop?: { workspaceRoot?: string };
17
+ }
18
+
11
19
  export interface FsWriteResult {
12
20
  success: boolean;
13
21
  output?: string;
14
22
  error?: string;
15
23
  }
16
24
 
25
+ function expandHome(value: string): string {
26
+ return value === '~' ? os.homedir()
27
+ : value.startsWith('~/') || value.startsWith('~\\')
28
+ ? path.join(os.homedir(), value.slice(2))
29
+ : value;
30
+ }
31
+
32
+ function inside(root: string, target: string): boolean {
33
+ const relative = path.relative(root, target);
34
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`)
35
+ && !path.isAbsolute(relative));
36
+ }
37
+
38
+ async function physicalTarget(target: string): Promise<string> {
39
+ // Resolves symlinks in the longest existing ancestor, including a symlinked
40
+ // parent of a new file. It is not a substitute for OS-level isolation.
41
+ let current = target;
42
+ const missing: string[] = [];
43
+ while (true) {
44
+ try {
45
+ const resolved = await fs.realpath(current);
46
+ return path.join(resolved, ...missing.reverse());
47
+ } catch (error: unknown) {
48
+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error;
49
+ const parent = path.dirname(current);
50
+ if (parent === current) throw new Error('Could not resolve target ancestry');
51
+ missing.push(path.basename(current));
52
+ current = parent;
53
+ }
54
+ }
55
+ }
56
+
57
+ async function checkScope(target: string, context?: FsWriteContext): Promise<void> {
58
+ if (!context || context.grantAllAccess === true) return;
59
+ const roots = Array.isArray(context.workspacePaths) && context.workspacePaths.length > 0
60
+ ? context.workspacePaths
61
+ : [context.parentLoop?.workspaceRoot, context.workspaceRoot].filter(
62
+ (value): value is string => typeof value === 'string' && value.length > 0
63
+ );
64
+ if (roots.length === 0) return;
65
+ const physical = await physicalTarget(target);
66
+ for (const root of roots) {
67
+ try {
68
+ const resolvedRoot = await fs.realpath(path.resolve(expandHome(root)));
69
+ if (inside(resolvedRoot, physical)) return;
70
+ } catch { /* A non-existent authorized root is not permission to escape. */ }
71
+ }
72
+ throw new Error(`Target resolves outside the selected workspace: ${target}`);
73
+ }
74
+
75
+ function writeError(error: unknown, target: string): string {
76
+ const code = (error as NodeJS.ErrnoException)?.code;
77
+ if (code === 'EISDIR' || code === 'ENOTEMPTY') {
78
+ return `Cannot write file: "${target}" is an existing directory. Supply a filename inside it, such as ${path.join(target, 'index.html')}.`;
79
+ }
80
+ return `Atomic file write failed: ${error instanceof Error ? error.message : String(error)}`;
81
+ }
82
+
17
83
  export const fsWrite = {
18
84
  schema: {
19
85
  name: 'fs.write',
20
- description: 'Create or overwrite a file with content using Zero-Corruption Atomic Swap. Guarantees safe file writing.',
86
+ description: 'Write a complete UTF-8 file using atomic rename. Path must be a file, not a directory.',
21
87
  parameters: {
22
88
  type: 'object',
23
89
  properties: {
@@ -28,39 +94,76 @@ export const fsWrite = {
28
94
  required: ['path', 'content']
29
95
  }
30
96
  },
31
- async execute(args: FsWriteArgs): Promise<FsWriteResult> {
32
- try {
33
- const target = args.path.replace(/^~\//, os.homedir() + '/');
34
97
 
35
- // Prevent EISDIR if target path is already an existing directory
98
+ async execute(args: FsWriteArgs, context?: FsWriteContext): Promise<FsWriteResult> {
99
+ if (!args || typeof args.path !== 'string' || !args.path.trim()) {
100
+ return { success: false, error: 'fs_write requires a nonempty path pointing to a FILE.' };
101
+ }
102
+ if (typeof args.content !== 'string') {
103
+ return { success: false, error: 'fs_write requires content as a string. Do not infer or invent missing file content.' };
104
+ }
105
+ if (args.path.endsWith('/') || args.path.endsWith('\\')) {
106
+ return { success: false, error: `Target ${args.path} ends in a directory separator. Add a filename such as index.html.` };
107
+ }
108
+
109
+ const target = path.resolve(expandHome(args.path.trim()));
110
+ let temporary = '';
111
+ try {
112
+ await checkScope(target, context);
113
+ let originalMode: number | undefined;
36
114
  try {
37
- const stat = await fs.stat(target);
115
+ const stat = await fs.lstat(target);
38
116
  if (stat.isDirectory()) {
39
- return {
40
- success: false,
41
- error: `Cannot write file: "${args.path}" is an existing directory. Specify a target file path inside this directory (e.g. "${args.path}/index.js").`
42
- };
117
+ return { success: false, error: `Cannot write file: "${target}" is an existing directory. Specify a target file path inside this directory (e.g. "${path.join(target, 'index.html')}").` };
118
+ }
119
+ if (stat.isSymbolicLink()) {
120
+ return { success: false, error: `Refusing to replace symbolic link ${target}; use a regular file in the selected workspace.` };
43
121
  }
44
- } catch {
45
- // Target does not exist yet, safe to proceed
122
+ if (!stat.isFile()) {
123
+ return { success: false, error: `Target ${target} is not a regular file.` };
124
+ }
125
+ originalMode = stat.mode & 0o777;
126
+ } catch (error: unknown) {
127
+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error;
46
128
  }
47
129
 
48
130
  if (args.createDirectories !== false) {
49
131
  await fs.mkdir(path.dirname(target), { recursive: true });
50
132
  }
51
-
52
- // Phase 4 AGI Upgrade: Atomic File Swap
53
- // Prevent zero-byte file corruption if Node crashes during a huge write.
54
- const tempPath = `${target}.causyne_tmp_${Date.now()}`;
55
- await fs.writeFile(tempPath, args.content, 'utf8');
56
-
57
- // Atomic rename (POSIX standard guarantee)
58
- await fs.rename(tempPath, target);
59
-
60
- return { success: true, output: `Atomically wrote ${Buffer.byteLength(args.content, 'utf8')} bytes to ${args.path}` };
61
- } catch (e: unknown) {
62
- const msg = e instanceof Error ? e.message : String(e);
63
- return { success: false, error: `Atomic Write Failed: ${msg}` };
133
+ // Re-check after creating parents: an existing parent might be a symlink.
134
+ await checkScope(target, context);
135
+ temporary = path.join(path.dirname(target), `.${path.basename(target)}.causyne-${randomUUID()}.tmp`);
136
+ const file = await fs.open(temporary, 'wx', originalMode ?? 0o600);
137
+ try {
138
+ await file.writeFile(args.content, { encoding: 'utf8' });
139
+ await file.sync();
140
+ } finally {
141
+ await file.close();
142
+ }
143
+ // Never reinterpret a directory as a file if the destination changed.
144
+ const destinationStat = await fs.lstat(target).catch((error: NodeJS.ErrnoException) => {
145
+ if (error.code === 'ENOENT') return null;
146
+ throw error;
147
+ });
148
+ if (destinationStat && !destinationStat.isFile()) {
149
+ throw new Error(`Destination is no longer a regular file: ${target}`);
150
+ }
151
+ await checkScope(target, context);
152
+ await fs.rename(temporary, target);
153
+ temporary = '';
154
+ // Flushing the parent directory is best effort: some platforms disallow it.
155
+ try {
156
+ const directory = await fs.open(path.dirname(target), 'r');
157
+ try { await directory.sync(); } finally { await directory.close(); }
158
+ } catch { /* Do not claim crash-durable guarantees on unsupported FS. */ }
159
+ return {
160
+ success: true,
161
+ output: `Wrote ${Buffer.byteLength(args.content, 'utf8')} bytes to ${target}`
162
+ };
163
+ } catch (error: unknown) {
164
+ return { success: false, error: writeError(error, target) };
165
+ } finally {
166
+ if (temporary) await fs.unlink(temporary).catch(() => {});
64
167
  }
65
168
  }
66
- };
169
+ };